Bug Summary

File:tools/clang/lib/Sema/SemaDecl.cpp
Warning:line 6517, column 9
Null pointer passed as an argument to a 'nonnull' parameter

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaDecl.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn329677/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/lib/Sema -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-04-11-031539-24776-1 -x c++ /build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp

/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp

1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
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 implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "TypeLocBuilder.h"
15#include "clang/AST/ASTConsumer.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTLambda.h"
18#include "clang/AST/CXXInheritance.h"
19#include "clang/AST/CharUnits.h"
20#include "clang/AST/CommentDiagnostic.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
23#include "clang/AST/DeclTemplate.h"
24#include "clang/AST/EvaluatedExprVisitor.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/StmtCXX.h"
27#include "clang/Basic/Builtins.h"
28#include "clang/Basic/PartialDiagnostic.h"
29#include "clang/Basic/SourceManager.h"
30#include "clang/Basic/TargetInfo.h"
31#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35#include "clang/Sema/CXXFieldCollector.h"
36#include "clang/Sema/DeclSpec.h"
37#include "clang/Sema/DelayedDiagnostic.h"
38#include "clang/Sema/Initialization.h"
39#include "clang/Sema/Lookup.h"
40#include "clang/Sema/ParsedTemplate.h"
41#include "clang/Sema/Scope.h"
42#include "clang/Sema/ScopeInfo.h"
43#include "clang/Sema/SemaInternal.h"
44#include "clang/Sema/Template.h"
45#include "llvm/ADT/SmallString.h"
46#include "llvm/ADT/Triple.h"
47#include <algorithm>
48#include <cstring>
49#include <functional>
50
51using namespace clang;
52using namespace sema;
53
54Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55 if (OwnedType) {
56 Decl *Group[2] = { OwnedType, Ptr };
57 return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58 }
59
60 return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61}
62
63namespace {
64
65class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66 public:
67 TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
68 bool AllowTemplates = false,
69 bool AllowNonTemplates = true)
70 : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
71 AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
72 WantExpressionKeywords = false;
73 WantCXXNamedCasts = false;
74 WantRemainingKeywords = false;
75 }
76
77 bool ValidateCandidate(const TypoCorrection &candidate) override {
78 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
79 if (!AllowInvalidDecl && ND->isInvalidDecl())
80 return false;
81
82 if (getAsTypeTemplateDecl(ND))
83 return AllowTemplates;
84
85 bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
86 if (!IsType)
87 return false;
88
89 if (AllowNonTemplates)
90 return true;
91
92 // An injected-class-name of a class template (specialization) is valid
93 // as a template or as a non-template.
94 if (AllowTemplates) {
95 auto *RD = dyn_cast<CXXRecordDecl>(ND);
96 if (!RD || !RD->isInjectedClassName())
97 return false;
98 RD = cast<CXXRecordDecl>(RD->getDeclContext());
99 return RD->getDescribedClassTemplate() ||
100 isa<ClassTemplateSpecializationDecl>(RD);
101 }
102
103 return false;
104 }
105
106 return !WantClassName && candidate.isKeyword();
107 }
108
109 private:
110 bool AllowInvalidDecl;
111 bool WantClassName;
112 bool AllowTemplates;
113 bool AllowNonTemplates;
114};
115
116} // end anonymous namespace
117
118/// \brief Determine whether the token kind starts a simple-type-specifier.
119bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
120 switch (Kind) {
121 // FIXME: Take into account the current language when deciding whether a
122 // token kind is a valid type specifier
123 case tok::kw_short:
124 case tok::kw_long:
125 case tok::kw___int64:
126 case tok::kw___int128:
127 case tok::kw_signed:
128 case tok::kw_unsigned:
129 case tok::kw_void:
130 case tok::kw_char:
131 case tok::kw_int:
132 case tok::kw_half:
133 case tok::kw_float:
134 case tok::kw_double:
135 case tok::kw__Float16:
136 case tok::kw___float128:
137 case tok::kw_wchar_t:
138 case tok::kw_bool:
139 case tok::kw___underlying_type:
140 case tok::kw___auto_type:
141 return true;
142
143 case tok::annot_typename:
144 case tok::kw_char16_t:
145 case tok::kw_char32_t:
146 case tok::kw_typeof:
147 case tok::annot_decltype:
148 case tok::kw_decltype:
149 return getLangOpts().CPlusPlus;
150
151 default:
152 break;
153 }
154
155 return false;
156}
157
158namespace {
159enum class UnqualifiedTypeNameLookupResult {
160 NotFound,
161 FoundNonType,
162 FoundType
163};
164} // end anonymous namespace
165
166/// \brief Tries to perform unqualified lookup of the type decls in bases for
167/// dependent class.
168/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
169/// type decl, \a FoundType if only type decls are found.
170static UnqualifiedTypeNameLookupResult
171lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
172 SourceLocation NameLoc,
173 const CXXRecordDecl *RD) {
174 if (!RD->hasDefinition())
175 return UnqualifiedTypeNameLookupResult::NotFound;
176 // Look for type decls in base classes.
177 UnqualifiedTypeNameLookupResult FoundTypeDecl =
178 UnqualifiedTypeNameLookupResult::NotFound;
179 for (const auto &Base : RD->bases()) {
180 const CXXRecordDecl *BaseRD = nullptr;
181 if (auto *BaseTT = Base.getType()->getAs<TagType>())
182 BaseRD = BaseTT->getAsCXXRecordDecl();
183 else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
184 // Look for type decls in dependent base classes that have known primary
185 // templates.
186 if (!TST || !TST->isDependentType())
187 continue;
188 auto *TD = TST->getTemplateName().getAsTemplateDecl();
189 if (!TD)
190 continue;
191 if (auto *BasePrimaryTemplate =
192 dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
193 if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
194 BaseRD = BasePrimaryTemplate;
195 else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
196 if (const ClassTemplatePartialSpecializationDecl *PS =
197 CTD->findPartialSpecialization(Base.getType()))
198 if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
199 BaseRD = PS;
200 }
201 }
202 }
203 if (BaseRD) {
204 for (NamedDecl *ND : BaseRD->lookup(&II)) {
205 if (!isa<TypeDecl>(ND))
206 return UnqualifiedTypeNameLookupResult::FoundNonType;
207 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
208 }
209 if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
210 switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
211 case UnqualifiedTypeNameLookupResult::FoundNonType:
212 return UnqualifiedTypeNameLookupResult::FoundNonType;
213 case UnqualifiedTypeNameLookupResult::FoundType:
214 FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
215 break;
216 case UnqualifiedTypeNameLookupResult::NotFound:
217 break;
218 }
219 }
220 }
221 }
222
223 return FoundTypeDecl;
224}
225
226static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
227 const IdentifierInfo &II,
228 SourceLocation NameLoc) {
229 // Lookup in the parent class template context, if any.
230 const CXXRecordDecl *RD = nullptr;
231 UnqualifiedTypeNameLookupResult FoundTypeDecl =
232 UnqualifiedTypeNameLookupResult::NotFound;
233 for (DeclContext *DC = S.CurContext;
234 DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
235 DC = DC->getParent()) {
236 // Look for type decls in dependent base classes that have known primary
237 // templates.
238 RD = dyn_cast<CXXRecordDecl>(DC);
239 if (RD && RD->getDescribedClassTemplate())
240 FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
241 }
242 if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
243 return nullptr;
244
245 // We found some types in dependent base classes. Recover as if the user
246 // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
247 // lookup during template instantiation.
248 S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
249
250 ASTContext &Context = S.Context;
251 auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
252 cast<Type>(Context.getRecordType(RD)));
253 QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
254
255 CXXScopeSpec SS;
256 SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
257
258 TypeLocBuilder Builder;
259 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
260 DepTL.setNameLoc(NameLoc);
261 DepTL.setElaboratedKeywordLoc(SourceLocation());
262 DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
263 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
264}
265
266/// \brief If the identifier refers to a type name within this scope,
267/// return the declaration of that type.
268///
269/// This routine performs ordinary name lookup of the identifier II
270/// within the given scope, with optional C++ scope specifier SS, to
271/// determine whether the name refers to a type. If so, returns an
272/// opaque pointer (actually a QualType) corresponding to that
273/// type. Otherwise, returns NULL.
274ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
275 Scope *S, CXXScopeSpec *SS,
276 bool isClassName, bool HasTrailingDot,
277 ParsedType ObjectTypePtr,
278 bool IsCtorOrDtorName,
279 bool WantNontrivialTypeSourceInfo,
280 bool IsClassTemplateDeductionContext,
281 IdentifierInfo **CorrectedII) {
282 // FIXME: Consider allowing this outside C++1z mode as an extension.
283 bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
284 getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
285 !isClassName && !HasTrailingDot;
286
287 // Determine where we will perform name lookup.
288 DeclContext *LookupCtx = nullptr;
289 if (ObjectTypePtr) {
290 QualType ObjectType = ObjectTypePtr.get();
291 if (ObjectType->isRecordType())
292 LookupCtx = computeDeclContext(ObjectType);
293 } else if (SS && SS->isNotEmpty()) {
294 LookupCtx = computeDeclContext(*SS, false);
295
296 if (!LookupCtx) {
297 if (isDependentScopeSpecifier(*SS)) {
298 // C++ [temp.res]p3:
299 // A qualified-id that refers to a type and in which the
300 // nested-name-specifier depends on a template-parameter (14.6.2)
301 // shall be prefixed by the keyword typename to indicate that the
302 // qualified-id denotes a type, forming an
303 // elaborated-type-specifier (7.1.5.3).
304 //
305 // We therefore do not perform any name lookup if the result would
306 // refer to a member of an unknown specialization.
307 if (!isClassName && !IsCtorOrDtorName)
308 return nullptr;
309
310 // We know from the grammar that this name refers to a type,
311 // so build a dependent node to describe the type.
312 if (WantNontrivialTypeSourceInfo)
313 return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
314
315 NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
316 QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
317 II, NameLoc);
318 return ParsedType::make(T);
319 }
320
321 return nullptr;
322 }
323
324 if (!LookupCtx->isDependentContext() &&
325 RequireCompleteDeclContext(*SS, LookupCtx))
326 return nullptr;
327 }
328
329 // FIXME: LookupNestedNameSpecifierName isn't the right kind of
330 // lookup for class-names.
331 LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
332 LookupOrdinaryName;
333 LookupResult Result(*this, &II, NameLoc, Kind);
334 if (LookupCtx) {
335 // Perform "qualified" name lookup into the declaration context we
336 // computed, which is either the type of the base of a member access
337 // expression or the declaration context associated with a prior
338 // nested-name-specifier.
339 LookupQualifiedName(Result, LookupCtx);
340
341 if (ObjectTypePtr && Result.empty()) {
342 // C++ [basic.lookup.classref]p3:
343 // If the unqualified-id is ~type-name, the type-name is looked up
344 // in the context of the entire postfix-expression. If the type T of
345 // the object expression is of a class type C, the type-name is also
346 // looked up in the scope of class C. At least one of the lookups shall
347 // find a name that refers to (possibly cv-qualified) T.
348 LookupName(Result, S);
349 }
350 } else {
351 // Perform unqualified name lookup.
352 LookupName(Result, S);
353
354 // For unqualified lookup in a class template in MSVC mode, look into
355 // dependent base classes where the primary class template is known.
356 if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
357 if (ParsedType TypeInBase =
358 recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
359 return TypeInBase;
360 }
361 }
362
363 NamedDecl *IIDecl = nullptr;
364 switch (Result.getResultKind()) {
365 case LookupResult::NotFound:
366 case LookupResult::NotFoundInCurrentInstantiation:
367 if (CorrectedII) {
368 TypoCorrection Correction =
369 CorrectTypo(Result.getLookupNameInfo(), Kind, S, SS,
370 llvm::make_unique<TypeNameValidatorCCC>(
371 true, isClassName, AllowDeducedTemplate),
372 CTK_ErrorRecovery);
373 IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
374 TemplateTy Template;
375 bool MemberOfUnknownSpecialization;
376 UnqualifiedId TemplateName;
377 TemplateName.setIdentifier(NewII, NameLoc);
378 NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
379 CXXScopeSpec NewSS, *NewSSPtr = SS;
380 if (SS && NNS) {
381 NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
382 NewSSPtr = &NewSS;
383 }
384 if (Correction && (NNS || NewII != &II) &&
385 // Ignore a correction to a template type as the to-be-corrected
386 // identifier is not a template (typo correction for template names
387 // is handled elsewhere).
388 !(getLangOpts().CPlusPlus && NewSSPtr &&
389 isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
390 Template, MemberOfUnknownSpecialization))) {
391 ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
392 isClassName, HasTrailingDot, ObjectTypePtr,
393 IsCtorOrDtorName,
394 WantNontrivialTypeSourceInfo,
395 IsClassTemplateDeductionContext);
396 if (Ty) {
397 diagnoseTypo(Correction,
398 PDiag(diag::err_unknown_type_or_class_name_suggest)
399 << Result.getLookupName() << isClassName);
400 if (SS && NNS)
401 SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
402 *CorrectedII = NewII;
403 return Ty;
404 }
405 }
406 }
407 // If typo correction failed or was not performed, fall through
408 LLVM_FALLTHROUGH[[clang::fallthrough]];
409 case LookupResult::FoundOverloaded:
410 case LookupResult::FoundUnresolvedValue:
411 Result.suppressDiagnostics();
412 return nullptr;
413
414 case LookupResult::Ambiguous:
415 // Recover from type-hiding ambiguities by hiding the type. We'll
416 // do the lookup again when looking for an object, and we can
417 // diagnose the error then. If we don't do this, then the error
418 // about hiding the type will be immediately followed by an error
419 // that only makes sense if the identifier was treated like a type.
420 if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
421 Result.suppressDiagnostics();
422 return nullptr;
423 }
424
425 // Look to see if we have a type anywhere in the list of results.
426 for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
427 Res != ResEnd; ++Res) {
428 if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
429 (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
430 if (!IIDecl ||
431 (*Res)->getLocation().getRawEncoding() <
432 IIDecl->getLocation().getRawEncoding())
433 IIDecl = *Res;
434 }
435 }
436
437 if (!IIDecl) {
438 // None of the entities we found is a type, so there is no way
439 // to even assume that the result is a type. In this case, don't
440 // complain about the ambiguity. The parser will either try to
441 // perform this lookup again (e.g., as an object name), which
442 // will produce the ambiguity, or will complain that it expected
443 // a type name.
444 Result.suppressDiagnostics();
445 return nullptr;
446 }
447
448 // We found a type within the ambiguous lookup; diagnose the
449 // ambiguity and then return that type. This might be the right
450 // answer, or it might not be, but it suppresses any attempt to
451 // perform the name lookup again.
452 break;
453
454 case LookupResult::Found:
455 IIDecl = Result.getFoundDecl();
456 break;
457 }
458
459 assert(IIDecl && "Didn't find decl")(static_cast <bool> (IIDecl && "Didn't find decl"
) ? void (0) : __assert_fail ("IIDecl && \"Didn't find decl\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 459, __extension__ __PRETTY_FUNCTION__))
;
460
461 QualType T;
462 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
463 // C++ [class.qual]p2: A lookup that would find the injected-class-name
464 // instead names the constructors of the class, except when naming a class.
465 // This is ill-formed when we're not actually forming a ctor or dtor name.
466 auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
467 auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
468 if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
469 FoundRD->isInjectedClassName() &&
470 declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
471 Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
472 << &II << /*Type*/1;
473
474 DiagnoseUseOfDecl(IIDecl, NameLoc);
475
476 T = Context.getTypeDeclType(TD);
477 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
478 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
479 (void)DiagnoseUseOfDecl(IDecl, NameLoc);
480 if (!HasTrailingDot)
481 T = Context.getObjCInterfaceType(IDecl);
482 } else if (AllowDeducedTemplate) {
483 if (auto *TD = getAsTypeTemplateDecl(IIDecl))
484 T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
485 QualType(), false);
486 }
487
488 if (T.isNull()) {
489 // If it's not plausibly a type, suppress diagnostics.
490 Result.suppressDiagnostics();
491 return nullptr;
492 }
493
494 // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
495 // constructor or destructor name (in such a case, the scope specifier
496 // will be attached to the enclosing Expr or Decl node).
497 if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
498 !isa<ObjCInterfaceDecl>(IIDecl)) {
499 if (WantNontrivialTypeSourceInfo) {
500 // Construct a type with type-source information.
501 TypeLocBuilder Builder;
502 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
503
504 T = getElaboratedType(ETK_None, *SS, T);
505 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
506 ElabTL.setElaboratedKeywordLoc(SourceLocation());
507 ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
508 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
509 } else {
510 T = getElaboratedType(ETK_None, *SS, T);
511 }
512 }
513
514 return ParsedType::make(T);
515}
516
517// Builds a fake NNS for the given decl context.
518static NestedNameSpecifier *
519synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
520 for (;; DC = DC->getLookupParent()) {
521 DC = DC->getPrimaryContext();
522 auto *ND = dyn_cast<NamespaceDecl>(DC);
523 if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
524 return NestedNameSpecifier::Create(Context, nullptr, ND);
525 else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
526 return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
527 RD->getTypeForDecl());
528 else if (isa<TranslationUnitDecl>(DC))
529 return NestedNameSpecifier::GlobalSpecifier(Context);
530 }
531 llvm_unreachable("something isn't in TU scope?")::llvm::llvm_unreachable_internal("something isn't in TU scope?"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 531)
;
532}
533
534/// Find the parent class with dependent bases of the innermost enclosing method
535/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
536/// up allowing unqualified dependent type names at class-level, which MSVC
537/// correctly rejects.
538static const CXXRecordDecl *
539findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
540 for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
541 DC = DC->getPrimaryContext();
542 if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
543 if (MD->getParent()->hasAnyDependentBases())
544 return MD->getParent();
545 }
546 return nullptr;
547}
548
549ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
550 SourceLocation NameLoc,
551 bool IsTemplateTypeArg) {
552 assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode")(static_cast <bool> (getLangOpts().MSVCCompat &&
"shouldn't be called in non-MSVC mode") ? void (0) : __assert_fail
("getLangOpts().MSVCCompat && \"shouldn't be called in non-MSVC mode\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 552, __extension__ __PRETTY_FUNCTION__))
;
553
554 NestedNameSpecifier *NNS = nullptr;
555 if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
556 // If we weren't able to parse a default template argument, delay lookup
557 // until instantiation time by making a non-dependent DependentTypeName. We
558 // pretend we saw a NestedNameSpecifier referring to the current scope, and
559 // lookup is retried.
560 // FIXME: This hurts our diagnostic quality, since we get errors like "no
561 // type named 'Foo' in 'current_namespace'" when the user didn't write any
562 // name specifiers.
563 NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
564 Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
565 } else if (const CXXRecordDecl *RD =
566 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
567 // Build a DependentNameType that will perform lookup into RD at
568 // instantiation time.
569 NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
570 RD->getTypeForDecl());
571
572 // Diagnose that this identifier was undeclared, and retry the lookup during
573 // template instantiation.
574 Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
575 << RD;
576 } else {
577 // This is not a situation that we should recover from.
578 return ParsedType();
579 }
580
581 QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
582
583 // Build type location information. We synthesized the qualifier, so we have
584 // to build a fake NestedNameSpecifierLoc.
585 NestedNameSpecifierLocBuilder NNSLocBuilder;
586 NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
587 NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
588
589 TypeLocBuilder Builder;
590 DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
591 DepTL.setNameLoc(NameLoc);
592 DepTL.setElaboratedKeywordLoc(SourceLocation());
593 DepTL.setQualifierLoc(QualifierLoc);
594 return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
595}
596
597/// isTagName() - This method is called *for error recovery purposes only*
598/// to determine if the specified name is a valid tag name ("struct foo"). If
599/// so, this returns the TST for the tag corresponding to it (TST_enum,
600/// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
601/// cases in C where the user forgot to specify the tag.
602DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
603 // Do a tag name lookup in this scope.
604 LookupResult R(*this, &II, SourceLocation(), LookupTagName);
605 LookupName(R, S, false);
606 R.suppressDiagnostics();
607 if (R.getResultKind() == LookupResult::Found)
608 if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
609 switch (TD->getTagKind()) {
610 case TTK_Struct: return DeclSpec::TST_struct;
611 case TTK_Interface: return DeclSpec::TST_interface;
612 case TTK_Union: return DeclSpec::TST_union;
613 case TTK_Class: return DeclSpec::TST_class;
614 case TTK_Enum: return DeclSpec::TST_enum;
615 }
616 }
617
618 return DeclSpec::TST_unspecified;
619}
620
621/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
622/// if a CXXScopeSpec's type is equal to the type of one of the base classes
623/// then downgrade the missing typename error to a warning.
624/// This is needed for MSVC compatibility; Example:
625/// @code
626/// template<class T> class A {
627/// public:
628/// typedef int TYPE;
629/// };
630/// template<class T> class B : public A<T> {
631/// public:
632/// A<T>::TYPE a; // no typename required because A<T> is a base class.
633/// };
634/// @endcode
635bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
636 if (CurContext->isRecord()) {
637 if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
638 return true;
639
640 const Type *Ty = SS->getScopeRep()->getAsType();
641
642 CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
643 for (const auto &Base : RD->bases())
644 if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
645 return true;
646 return S->isFunctionPrototypeScope();
647 }
648 return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
649}
650
651void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
652 SourceLocation IILoc,
653 Scope *S,
654 CXXScopeSpec *SS,
655 ParsedType &SuggestedType,
656 bool IsTemplateName) {
657 // Don't report typename errors for editor placeholders.
658 if (II->isEditorPlaceholder())
659 return;
660 // We don't have anything to suggest (yet).
661 SuggestedType = nullptr;
662
663 // There may have been a typo in the name of the type. Look up typo
664 // results, in case we have something that we can suggest.
665 if (TypoCorrection Corrected =
666 CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
667 llvm::make_unique<TypeNameValidatorCCC>(
668 false, false, IsTemplateName, !IsTemplateName),
669 CTK_ErrorRecovery)) {
670 // FIXME: Support error recovery for the template-name case.
671 bool CanRecover = !IsTemplateName;
672 if (Corrected.isKeyword()) {
673 // We corrected to a keyword.
674 diagnoseTypo(Corrected,
675 PDiag(IsTemplateName ? diag::err_no_template_suggest
676 : diag::err_unknown_typename_suggest)
677 << II);
678 II = Corrected.getCorrectionAsIdentifierInfo();
679 } else {
680 // We found a similarly-named type or interface; suggest that.
681 if (!SS || !SS->isSet()) {
682 diagnoseTypo(Corrected,
683 PDiag(IsTemplateName ? diag::err_no_template_suggest
684 : diag::err_unknown_typename_suggest)
685 << II, CanRecover);
686 } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
687 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
688 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
689 II->getName().equals(CorrectedStr);
690 diagnoseTypo(Corrected,
691 PDiag(IsTemplateName
692 ? diag::err_no_member_template_suggest
693 : diag::err_unknown_nested_typename_suggest)
694 << II << DC << DroppedSpecifier << SS->getRange(),
695 CanRecover);
696 } else {
697 llvm_unreachable("could not have corrected a typo here")::llvm::llvm_unreachable_internal("could not have corrected a typo here"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 697)
;
698 }
699
700 if (!CanRecover)
701 return;
702
703 CXXScopeSpec tmpSS;
704 if (Corrected.getCorrectionSpecifier())
705 tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
706 SourceRange(IILoc));
707 // FIXME: Support class template argument deduction here.
708 SuggestedType =
709 getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
710 tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
711 /*IsCtorOrDtorName=*/false,
712 /*NonTrivialTypeSourceInfo=*/true);
713 }
714 return;
715 }
716
717 if (getLangOpts().CPlusPlus && !IsTemplateName) {
718 // See if II is a class template that the user forgot to pass arguments to.
719 UnqualifiedId Name;
720 Name.setIdentifier(II, IILoc);
721 CXXScopeSpec EmptySS;
722 TemplateTy TemplateResult;
723 bool MemberOfUnknownSpecialization;
724 if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
725 Name, nullptr, true, TemplateResult,
726 MemberOfUnknownSpecialization) == TNK_Type_template) {
727 TemplateName TplName = TemplateResult.get();
728 Diag(IILoc, diag::err_template_missing_args)
729 << (int)getTemplateNameKindForDiagnostics(TplName) << TplName;
730 if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
731 Diag(TplDecl->getLocation(), diag::note_template_decl_here)
732 << TplDecl->getTemplateParameters()->getSourceRange();
733 }
734 return;
735 }
736 }
737
738 // FIXME: Should we move the logic that tries to recover from a missing tag
739 // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
740
741 if (!SS || (!SS->isSet() && !SS->isInvalid()))
742 Diag(IILoc, IsTemplateName ? diag::err_no_template
743 : diag::err_unknown_typename)
744 << II;
745 else if (DeclContext *DC = computeDeclContext(*SS, false))
746 Diag(IILoc, IsTemplateName ? diag::err_no_member_template
747 : diag::err_typename_nested_not_found)
748 << II << DC << SS->getRange();
749 else if (isDependentScopeSpecifier(*SS)) {
750 unsigned DiagID = diag::err_typename_missing;
751 if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
752 DiagID = diag::ext_typename_missing;
753
754 Diag(SS->getRange().getBegin(), DiagID)
755 << SS->getScopeRep() << II->getName()
756 << SourceRange(SS->getRange().getBegin(), IILoc)
757 << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
758 SuggestedType = ActOnTypenameType(S, SourceLocation(),
759 *SS, *II, IILoc).get();
760 } else {
761 assert(SS && SS->isInvalid() &&(static_cast <bool> (SS && SS->isInvalid() &&
"Invalid scope specifier has already been diagnosed") ? void
(0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 762, __extension__ __PRETTY_FUNCTION__))
762 "Invalid scope specifier has already been diagnosed")(static_cast <bool> (SS && SS->isInvalid() &&
"Invalid scope specifier has already been diagnosed") ? void
(0) : __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 762, __extension__ __PRETTY_FUNCTION__))
;
763 }
764}
765
766/// \brief Determine whether the given result set contains either a type name
767/// or
768static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
769 bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
770 NextToken.is(tok::less);
771
772 for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
773 if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
774 return true;
775
776 if (CheckTemplate && isa<TemplateDecl>(*I))
777 return true;
778 }
779
780 return false;
781}
782
783static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
784 Scope *S, CXXScopeSpec &SS,
785 IdentifierInfo *&Name,
786 SourceLocation NameLoc) {
787 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
788 SemaRef.LookupParsedName(R, S, &SS);
789 if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
790 StringRef FixItTagName;
791 switch (Tag->getTagKind()) {
792 case TTK_Class:
793 FixItTagName = "class ";
794 break;
795
796 case TTK_Enum:
797 FixItTagName = "enum ";
798 break;
799
800 case TTK_Struct:
801 FixItTagName = "struct ";
802 break;
803
804 case TTK_Interface:
805 FixItTagName = "__interface ";
806 break;
807
808 case TTK_Union:
809 FixItTagName = "union ";
810 break;
811 }
812
813 StringRef TagName = FixItTagName.drop_back();
814 SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
815 << Name << TagName << SemaRef.getLangOpts().CPlusPlus
816 << FixItHint::CreateInsertion(NameLoc, FixItTagName);
817
818 for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
819 I != IEnd; ++I)
820 SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
821 << Name << TagName;
822
823 // Replace lookup results with just the tag decl.
824 Result.clear(Sema::LookupTagName);
825 SemaRef.LookupParsedName(Result, S, &SS);
826 return true;
827 }
828
829 return false;
830}
831
832/// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
833static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
834 QualType T, SourceLocation NameLoc) {
835 ASTContext &Context = S.Context;
836
837 TypeLocBuilder Builder;
838 Builder.pushTypeSpec(T).setNameLoc(NameLoc);
839
840 T = S.getElaboratedType(ETK_None, SS, T);
841 ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
842 ElabTL.setElaboratedKeywordLoc(SourceLocation());
843 ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
844 return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
845}
846
847Sema::NameClassification
848Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
849 SourceLocation NameLoc, const Token &NextToken,
850 bool IsAddressOfOperand,
851 std::unique_ptr<CorrectionCandidateCallback> CCC) {
852 DeclarationNameInfo NameInfo(Name, NameLoc);
853 ObjCMethodDecl *CurMethod = getCurMethodDecl();
854
855 if (NextToken.is(tok::coloncolon)) {
856 NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
857 BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
858 } else if (getLangOpts().CPlusPlus && SS.isSet() &&
859 isCurrentClassName(*Name, S, &SS)) {
860 // Per [class.qual]p2, this names the constructors of SS, not the
861 // injected-class-name. We don't have a classification for that.
862 // There's not much point caching this result, since the parser
863 // will reject it later.
864 return NameClassification::Unknown();
865 }
866
867 LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
868 LookupParsedName(Result, S, &SS, !CurMethod);
869
870 // For unqualified lookup in a class template in MSVC mode, look into
871 // dependent base classes where the primary class template is known.
872 if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
873 if (ParsedType TypeInBase =
874 recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
875 return TypeInBase;
876 }
877
878 // Perform lookup for Objective-C instance variables (including automatically
879 // synthesized instance variables), if we're in an Objective-C method.
880 // FIXME: This lookup really, really needs to be folded in to the normal
881 // unqualified lookup mechanism.
882 if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
883 ExprResult E = LookupInObjCMethod(Result, S, Name, true);
884 if (E.get() || E.isInvalid())
885 return E;
886 }
887
888 bool SecondTry = false;
889 bool IsFilteredTemplateName = false;
890
891Corrected:
892 switch (Result.getResultKind()) {
893 case LookupResult::NotFound:
894 // If an unqualified-id is followed by a '(', then we have a function
895 // call.
896 if (!SS.isSet() && NextToken.is(tok::l_paren)) {
897 // In C++, this is an ADL-only call.
898 // FIXME: Reference?
899 if (getLangOpts().CPlusPlus)
900 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
901
902 // C90 6.3.2.2:
903 // If the expression that precedes the parenthesized argument list in a
904 // function call consists solely of an identifier, and if no
905 // declaration is visible for this identifier, the identifier is
906 // implicitly declared exactly as if, in the innermost block containing
907 // the function call, the declaration
908 //
909 // extern int identifier ();
910 //
911 // appeared.
912 //
913 // We also allow this in C99 as an extension.
914 if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
915 Result.addDecl(D);
916 Result.resolveKind();
917 return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
918 }
919 }
920
921 // In C, we first see whether there is a tag type by the same name, in
922 // which case it's likely that the user just forgot to write "enum",
923 // "struct", or "union".
924 if (!getLangOpts().CPlusPlus && !SecondTry &&
925 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
926 break;
927 }
928
929 // Perform typo correction to determine if there is another name that is
930 // close to this name.
931 if (!SecondTry && CCC) {
932 SecondTry = true;
933 if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
934 Result.getLookupKind(), S,
935 &SS, std::move(CCC),
936 CTK_ErrorRecovery)) {
937 unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
938 unsigned QualifiedDiag = diag::err_no_member_suggest;
939
940 NamedDecl *FirstDecl = Corrected.getFoundDecl();
941 NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
942 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
943 UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
944 UnqualifiedDiag = diag::err_no_template_suggest;
945 QualifiedDiag = diag::err_no_member_template_suggest;
946 } else if (UnderlyingFirstDecl &&
947 (isa<TypeDecl>(UnderlyingFirstDecl) ||
948 isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
949 isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
950 UnqualifiedDiag = diag::err_unknown_typename_suggest;
951 QualifiedDiag = diag::err_unknown_nested_typename_suggest;
952 }
953
954 if (SS.isEmpty()) {
955 diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
956 } else {// FIXME: is this even reachable? Test it.
957 std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
958 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
959 Name->getName().equals(CorrectedStr);
960 diagnoseTypo(Corrected, PDiag(QualifiedDiag)
961 << Name << computeDeclContext(SS, false)
962 << DroppedSpecifier << SS.getRange());
963 }
964
965 // Update the name, so that the caller has the new name.
966 Name = Corrected.getCorrectionAsIdentifierInfo();
967
968 // Typo correction corrected to a keyword.
969 if (Corrected.isKeyword())
970 return Name;
971
972 // Also update the LookupResult...
973 // FIXME: This should probably go away at some point
974 Result.clear();
975 Result.setLookupName(Corrected.getCorrection());
976 if (FirstDecl)
977 Result.addDecl(FirstDecl);
978
979 // If we found an Objective-C instance variable, let
980 // LookupInObjCMethod build the appropriate expression to
981 // reference the ivar.
982 // FIXME: This is a gross hack.
983 if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
984 Result.clear();
985 ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
986 return E;
987 }
988
989 goto Corrected;
990 }
991 }
992
993 // We failed to correct; just fall through and let the parser deal with it.
994 Result.suppressDiagnostics();
995 return NameClassification::Unknown();
996
997 case LookupResult::NotFoundInCurrentInstantiation: {
998 // We performed name lookup into the current instantiation, and there were
999 // dependent bases, so we treat this result the same way as any other
1000 // dependent nested-name-specifier.
1001
1002 // C++ [temp.res]p2:
1003 // A name used in a template declaration or definition and that is
1004 // dependent on a template-parameter is assumed not to name a type
1005 // unless the applicable name lookup finds a type name or the name is
1006 // qualified by the keyword typename.
1007 //
1008 // FIXME: If the next token is '<', we might want to ask the parser to
1009 // perform some heroics to see if we actually have a
1010 // template-argument-list, which would indicate a missing 'template'
1011 // keyword here.
1012 return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1013 NameInfo, IsAddressOfOperand,
1014 /*TemplateArgs=*/nullptr);
1015 }
1016
1017 case LookupResult::Found:
1018 case LookupResult::FoundOverloaded:
1019 case LookupResult::FoundUnresolvedValue:
1020 break;
1021
1022 case LookupResult::Ambiguous:
1023 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1024 hasAnyAcceptableTemplateNames(Result)) {
1025 // C++ [temp.local]p3:
1026 // A lookup that finds an injected-class-name (10.2) can result in an
1027 // ambiguity in certain cases (for example, if it is found in more than
1028 // one base class). If all of the injected-class-names that are found
1029 // refer to specializations of the same class template, and if the name
1030 // is followed by a template-argument-list, the reference refers to the
1031 // class template itself and not a specialization thereof, and is not
1032 // ambiguous.
1033 //
1034 // This filtering can make an ambiguous result into an unambiguous one,
1035 // so try again after filtering out template names.
1036 FilterAcceptableTemplateNames(Result);
1037 if (!Result.isAmbiguous()) {
1038 IsFilteredTemplateName = true;
1039 break;
1040 }
1041 }
1042
1043 // Diagnose the ambiguity and return an error.
1044 return NameClassification::Error();
1045 }
1046
1047 if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1048 (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
1049 // C++ [temp.names]p3:
1050 // After name lookup (3.4) finds that a name is a template-name or that
1051 // an operator-function-id or a literal- operator-id refers to a set of
1052 // overloaded functions any member of which is a function template if
1053 // this is followed by a <, the < is always taken as the delimiter of a
1054 // template-argument-list and never as the less-than operator.
1055 if (!IsFilteredTemplateName)
1056 FilterAcceptableTemplateNames(Result);
1057
1058 if (!Result.empty()) {
1059 bool IsFunctionTemplate;
1060 bool IsVarTemplate;
1061 TemplateName Template;
1062 if (Result.end() - Result.begin() > 1) {
1063 IsFunctionTemplate = true;
1064 Template = Context.getOverloadedTemplateName(Result.begin(),
1065 Result.end());
1066 } else {
1067 TemplateDecl *TD
1068 = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1069 IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1070 IsVarTemplate = isa<VarTemplateDecl>(TD);
1071
1072 if (SS.isSet() && !SS.isInvalid())
1073 Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1074 /*TemplateKeyword=*/false,
1075 TD);
1076 else
1077 Template = TemplateName(TD);
1078 }
1079
1080 if (IsFunctionTemplate) {
1081 // Function templates always go through overload resolution, at which
1082 // point we'll perform the various checks (e.g., accessibility) we need
1083 // to based on which function we selected.
1084 Result.suppressDiagnostics();
1085
1086 return NameClassification::FunctionTemplate(Template);
1087 }
1088
1089 return IsVarTemplate ? NameClassification::VarTemplate(Template)
1090 : NameClassification::TypeTemplate(Template);
1091 }
1092 }
1093
1094 NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1095 if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1096 DiagnoseUseOfDecl(Type, NameLoc);
1097 MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1098 QualType T = Context.getTypeDeclType(Type);
1099 if (SS.isNotEmpty())
1100 return buildNestedType(*this, SS, T, NameLoc);
1101 return ParsedType::make(T);
1102 }
1103
1104 ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1105 if (!Class) {
1106 // FIXME: It's unfortunate that we don't have a Type node for handling this.
1107 if (ObjCCompatibleAliasDecl *Alias =
1108 dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1109 Class = Alias->getClassInterface();
1110 }
1111
1112 if (Class) {
1113 DiagnoseUseOfDecl(Class, NameLoc);
1114
1115 if (NextToken.is(tok::period)) {
1116 // Interface. <something> is parsed as a property reference expression.
1117 // Just return "unknown" as a fall-through for now.
1118 Result.suppressDiagnostics();
1119 return NameClassification::Unknown();
1120 }
1121
1122 QualType T = Context.getObjCInterfaceType(Class);
1123 return ParsedType::make(T);
1124 }
1125
1126 // We can have a type template here if we're classifying a template argument.
1127 if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1128 !isa<VarTemplateDecl>(FirstDecl))
1129 return NameClassification::TypeTemplate(
1130 TemplateName(cast<TemplateDecl>(FirstDecl)));
1131
1132 // Check for a tag type hidden by a non-type decl in a few cases where it
1133 // seems likely a type is wanted instead of the non-type that was found.
1134 bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1135 if ((NextToken.is(tok::identifier) ||
1136 (NextIsOp &&
1137 FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1138 isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1139 TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1140 DiagnoseUseOfDecl(Type, NameLoc);
1141 QualType T = Context.getTypeDeclType(Type);
1142 if (SS.isNotEmpty())
1143 return buildNestedType(*this, SS, T, NameLoc);
1144 return ParsedType::make(T);
1145 }
1146
1147 if (FirstDecl->isCXXClassMember())
1148 return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1149 nullptr, S);
1150
1151 bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1152 return BuildDeclarationNameExpr(SS, Result, ADL);
1153}
1154
1155Sema::TemplateNameKindForDiagnostics
1156Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1157 auto *TD = Name.getAsTemplateDecl();
1158 if (!TD)
1159 return TemplateNameKindForDiagnostics::DependentTemplate;
1160 if (isa<ClassTemplateDecl>(TD))
1161 return TemplateNameKindForDiagnostics::ClassTemplate;
1162 if (isa<FunctionTemplateDecl>(TD))
1163 return TemplateNameKindForDiagnostics::FunctionTemplate;
1164 if (isa<VarTemplateDecl>(TD))
1165 return TemplateNameKindForDiagnostics::VarTemplate;
1166 if (isa<TypeAliasTemplateDecl>(TD))
1167 return TemplateNameKindForDiagnostics::AliasTemplate;
1168 if (isa<TemplateTemplateParmDecl>(TD))
1169 return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1170 return TemplateNameKindForDiagnostics::DependentTemplate;
1171}
1172
1173// Determines the context to return to after temporarily entering a
1174// context. This depends in an unnecessarily complicated way on the
1175// exact ordering of callbacks from the parser.
1176DeclContext *Sema::getContainingDC(DeclContext *DC) {
1177
1178 // Functions defined inline within classes aren't parsed until we've
1179 // finished parsing the top-level class, so the top-level class is
1180 // the context we'll need to return to.
1181 // A Lambda call operator whose parent is a class must not be treated
1182 // as an inline member function. A Lambda can be used legally
1183 // either as an in-class member initializer or a default argument. These
1184 // are parsed once the class has been marked complete and so the containing
1185 // context would be the nested class (when the lambda is defined in one);
1186 // If the class is not complete, then the lambda is being used in an
1187 // ill-formed fashion (such as to specify the width of a bit-field, or
1188 // in an array-bound) - in which case we still want to return the
1189 // lexically containing DC (which could be a nested class).
1190 if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1191 DC = DC->getLexicalParent();
1192
1193 // A function not defined within a class will always return to its
1194 // lexical context.
1195 if (!isa<CXXRecordDecl>(DC))
1196 return DC;
1197
1198 // A C++ inline method/friend is parsed *after* the topmost class
1199 // it was declared in is fully parsed ("complete"); the topmost
1200 // class is the context we need to return to.
1201 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1202 DC = RD;
1203
1204 // Return the declaration context of the topmost class the inline method is
1205 // declared in.
1206 return DC;
1207 }
1208
1209 return DC->getLexicalParent();
1210}
1211
1212void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1213 assert(getContainingDC(DC) == CurContext &&(static_cast <bool> (getContainingDC(DC) == CurContext &&
"The next DeclContext should be lexically contained in the current one."
) ? void (0) : __assert_fail ("getContainingDC(DC) == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 1214, __extension__ __PRETTY_FUNCTION__))
1214 "The next DeclContext should be lexically contained in the current one.")(static_cast <bool> (getContainingDC(DC) == CurContext &&
"The next DeclContext should be lexically contained in the current one."
) ? void (0) : __assert_fail ("getContainingDC(DC) == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 1214, __extension__ __PRETTY_FUNCTION__))
;
1215 CurContext = DC;
1216 S->setEntity(DC);
1217}
1218
1219void Sema::PopDeclContext() {
1220 assert(CurContext && "DeclContext imbalance!")(static_cast <bool> (CurContext && "DeclContext imbalance!"
) ? void (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 1220, __extension__ __PRETTY_FUNCTION__))
;
1221
1222 CurContext = getContainingDC(CurContext);
1223 assert(CurContext && "Popped translation unit!")(static_cast <bool> (CurContext && "Popped translation unit!"
) ? void (0) : __assert_fail ("CurContext && \"Popped translation unit!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 1223, __extension__ __PRETTY_FUNCTION__))
;
1224}
1225
1226Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1227 Decl *D) {
1228 // Unlike PushDeclContext, the context to which we return is not necessarily
1229 // the containing DC of TD, because the new context will be some pre-existing
1230 // TagDecl definition instead of a fresh one.
1231 auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1232 CurContext = cast<TagDecl>(D)->getDefinition();
1233 assert(CurContext && "skipping definition of undefined tag")(static_cast <bool> (CurContext && "skipping definition of undefined tag"
) ? void (0) : __assert_fail ("CurContext && \"skipping definition of undefined tag\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 1233, __extension__ __PRETTY_FUNCTION__))
;
1234 // Start lookups from the parent of the current context; we don't want to look
1235 // into the pre-existing complete definition.
1236 S->setEntity(CurContext->getLookupParent());
1237 return Result;
1238}
1239
1240void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1241 CurContext = static_cast<decltype(CurContext)>(Context);
1242}
1243
1244/// EnterDeclaratorContext - Used when we must lookup names in the context
1245/// of a declarator's nested name specifier.
1246///
1247void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1248 // C++0x [basic.lookup.unqual]p13:
1249 // A name used in the definition of a static data member of class
1250 // X (after the qualified-id of the static member) is looked up as
1251 // if the name was used in a member function of X.
1252 // C++0x [basic.lookup.unqual]p14:
1253 // If a variable member of a namespace is defined outside of the
1254 // scope of its namespace then any name used in the definition of
1255 // the variable member (after the declarator-id) is looked up as
1256 // if the definition of the variable member occurred in its
1257 // namespace.
1258 // Both of these imply that we should push a scope whose context
1259 // is the semantic context of the declaration. We can't use
1260 // PushDeclContext here because that context is not necessarily
1261 // lexically contained in the current context. Fortunately,
1262 // the containing scope should have the appropriate information.
1263
1264 assert(!S->getEntity() && "scope already has entity")(static_cast <bool> (!S->getEntity() && "scope already has entity"
) ? void (0) : __assert_fail ("!S->getEntity() && \"scope already has entity\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 1264, __extension__ __PRETTY_FUNCTION__))
;
1265
1266#ifndef NDEBUG
1267 Scope *Ancestor = S->getParent();
1268 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1269 assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch")(static_cast <bool> (Ancestor->getEntity() == CurContext
&& "ancestor context mismatch") ? void (0) : __assert_fail
("Ancestor->getEntity() == CurContext && \"ancestor context mismatch\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 1269, __extension__ __PRETTY_FUNCTION__))
;
1270#endif
1271
1272 CurContext = DC;
1273 S->setEntity(DC);
1274}
1275
1276void Sema::ExitDeclaratorContext(Scope *S) {
1277 assert(S->getEntity() == CurContext && "Context imbalance!")(static_cast <bool> (S->getEntity() == CurContext &&
"Context imbalance!") ? void (0) : __assert_fail ("S->getEntity() == CurContext && \"Context imbalance!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 1277, __extension__ __PRETTY_FUNCTION__))
;
1278
1279 // Switch back to the lexical context. The safety of this is
1280 // enforced by an assert in EnterDeclaratorContext.
1281 Scope *Ancestor = S->getParent();
1282 while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1283 CurContext = Ancestor->getEntity();
1284
1285 // We don't need to do anything with the scope, which is going to
1286 // disappear.
1287}
1288
1289void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1290 // We assume that the caller has already called
1291 // ActOnReenterTemplateScope so getTemplatedDecl() works.
1292 FunctionDecl *FD = D->getAsFunction();
1293 if (!FD)
1294 return;
1295
1296 // Same implementation as PushDeclContext, but enters the context
1297 // from the lexical parent, rather than the top-level class.
1298 assert(CurContext == FD->getLexicalParent() &&(static_cast <bool> (CurContext == FD->getLexicalParent
() && "The next DeclContext should be lexically contained in the current one."
) ? void (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 1299, __extension__ __PRETTY_FUNCTION__))
1299 "The next DeclContext should be lexically contained in the current one.")(static_cast <bool> (CurContext == FD->getLexicalParent
() && "The next DeclContext should be lexically contained in the current one."
) ? void (0) : __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 1299, __extension__ __PRETTY_FUNCTION__))
;
1300 CurContext = FD;
1301 S->setEntity(CurContext);
1302
1303 for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1304 ParmVarDecl *Param = FD->getParamDecl(P);
1305 // If the parameter has an identifier, then add it to the scope
1306 if (Param->getIdentifier()) {
1307 S->AddDecl(Param);
1308 IdResolver.AddDecl(Param);
1309 }
1310 }
1311}
1312
1313void Sema::ActOnExitFunctionContext() {
1314 // Same implementation as PopDeclContext, but returns to the lexical parent,
1315 // rather than the top-level class.
1316 assert(CurContext && "DeclContext imbalance!")(static_cast <bool> (CurContext && "DeclContext imbalance!"
) ? void (0) : __assert_fail ("CurContext && \"DeclContext imbalance!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 1316, __extension__ __PRETTY_FUNCTION__))
;
1317 CurContext = CurContext->getLexicalParent();
1318 assert(CurContext && "Popped translation unit!")(static_cast <bool> (CurContext && "Popped translation unit!"
) ? void (0) : __assert_fail ("CurContext && \"Popped translation unit!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 1318, __extension__ __PRETTY_FUNCTION__))
;
1319}
1320
1321/// \brief Determine whether we allow overloading of the function
1322/// PrevDecl with another declaration.
1323///
1324/// This routine determines whether overloading is possible, not
1325/// whether some new function is actually an overload. It will return
1326/// true in C++ (where we can always provide overloads) or, as an
1327/// extension, in C when the previous function is already an
1328/// overloaded function declaration or has the "overloadable"
1329/// attribute.
1330static bool AllowOverloadingOfFunction(LookupResult &Previous,
1331 ASTContext &Context,
1332 const FunctionDecl *New) {
1333 if (Context.getLangOpts().CPlusPlus)
1334 return true;
1335
1336 if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1337 return true;
1338
1339 return Previous.getResultKind() == LookupResult::Found &&
1340 (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1341 New->hasAttr<OverloadableAttr>());
1342}
1343
1344/// Add this decl to the scope shadowed decl chains.
1345void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1346 // Move up the scope chain until we find the nearest enclosing
1347 // non-transparent context. The declaration will be introduced into this
1348 // scope.
1349 while (S->getEntity() && S->getEntity()->isTransparentContext())
1350 S = S->getParent();
1351
1352 // Add scoped declarations into their context, so that they can be
1353 // found later. Declarations without a context won't be inserted
1354 // into any context.
1355 if (AddToContext)
1356 CurContext->addDecl(D);
1357
1358 // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1359 // are function-local declarations.
1360 if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1361 !D->getDeclContext()->getRedeclContext()->Equals(
1362 D->getLexicalDeclContext()->getRedeclContext()) &&
1363 !D->getLexicalDeclContext()->isFunctionOrMethod())
1364 return;
1365
1366 // Template instantiations should also not be pushed into scope.
1367 if (isa<FunctionDecl>(D) &&
1368 cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1369 return;
1370
1371 // If this replaces anything in the current scope,
1372 IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1373 IEnd = IdResolver.end();
1374 for (; I != IEnd; ++I) {
1375 if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1376 S->RemoveDecl(*I);
1377 IdResolver.RemoveDecl(*I);
1378
1379 // Should only need to replace one decl.
1380 break;
1381 }
1382 }
1383
1384 S->AddDecl(D);
1385
1386 if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1387 // Implicitly-generated labels may end up getting generated in an order that
1388 // isn't strictly lexical, which breaks name lookup. Be careful to insert
1389 // the label at the appropriate place in the identifier chain.
1390 for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1391 DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1392 if (IDC == CurContext) {
1393 if (!S->isDeclScope(*I))
1394 continue;
1395 } else if (IDC->Encloses(CurContext))
1396 break;
1397 }
1398
1399 IdResolver.InsertDeclAfter(I, D);
1400 } else {
1401 IdResolver.AddDecl(D);
1402 }
1403}
1404
1405void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1406 if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1407 TUScope->AddDecl(D);
1408}
1409
1410bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1411 bool AllowInlineNamespace) {
1412 return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1413}
1414
1415Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1416 DeclContext *TargetDC = DC->getPrimaryContext();
1417 do {
1418 if (DeclContext *ScopeDC = S->getEntity())
1419 if (ScopeDC->getPrimaryContext() == TargetDC)
1420 return S;
1421 } while ((S = S->getParent()));
1422
1423 return nullptr;
1424}
1425
1426static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1427 DeclContext*,
1428 ASTContext&);
1429
1430/// Filters out lookup results that don't fall within the given scope
1431/// as determined by isDeclInScope.
1432void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1433 bool ConsiderLinkage,
1434 bool AllowInlineNamespace) {
1435 LookupResult::Filter F = R.makeFilter();
1436 while (F.hasNext()) {
1437 NamedDecl *D = F.next();
1438
1439 if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1440 continue;
1441
1442 if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1443 continue;
1444
1445 F.erase();
1446 }
1447
1448 F.done();
1449}
1450
1451/// We've determined that \p New is a redeclaration of \p Old. Check that they
1452/// have compatible owning modules.
1453bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old) {
1454 // FIXME: The Modules TS is not clear about how friend declarations are
1455 // to be treated. It's not meaningful to have different owning modules for
1456 // linkage in redeclarations of the same entity, so for now allow the
1457 // redeclaration and change the owning modules to match.
1458 if (New->getFriendObjectKind() &&
1459 Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1460 New->setLocalOwningModule(Old->getOwningModule());
1461 makeMergedDefinitionVisible(New);
1462 return false;
1463 }
1464
1465 Module *NewM = New->getOwningModule();
1466 Module *OldM = Old->getOwningModule();
1467 if (NewM == OldM)
1468 return false;
1469
1470 // FIXME: Check proclaimed-ownership-declarations here too.
1471 bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit;
1472 bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit;
1473 if (NewIsModuleInterface || OldIsModuleInterface) {
1474 // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1475 // if a declaration of D [...] appears in the purview of a module, all
1476 // other such declarations shall appear in the purview of the same module
1477 Diag(New->getLocation(), diag::err_mismatched_owning_module)
1478 << New
1479 << NewIsModuleInterface
1480 << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1481 << OldIsModuleInterface
1482 << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1483 Diag(Old->getLocation(), diag::note_previous_declaration);
1484 New->setInvalidDecl();
1485 return true;
1486 }
1487
1488 return false;
1489}
1490
1491static bool isUsingDecl(NamedDecl *D) {
1492 return isa<UsingShadowDecl>(D) ||
1493 isa<UnresolvedUsingTypenameDecl>(D) ||
1494 isa<UnresolvedUsingValueDecl>(D);
1495}
1496
1497/// Removes using shadow declarations from the lookup results.
1498static void RemoveUsingDecls(LookupResult &R) {
1499 LookupResult::Filter F = R.makeFilter();
1500 while (F.hasNext())
1501 if (isUsingDecl(F.next()))
1502 F.erase();
1503
1504 F.done();
1505}
1506
1507/// \brief Check for this common pattern:
1508/// @code
1509/// class S {
1510/// S(const S&); // DO NOT IMPLEMENT
1511/// void operator=(const S&); // DO NOT IMPLEMENT
1512/// };
1513/// @endcode
1514static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1515 // FIXME: Should check for private access too but access is set after we get
1516 // the decl here.
1517 if (D->doesThisDeclarationHaveABody())
1518 return false;
1519
1520 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1521 return CD->isCopyConstructor();
1522 return D->isCopyAssignmentOperator();
1523}
1524
1525// We need this to handle
1526//
1527// typedef struct {
1528// void *foo() { return 0; }
1529// } A;
1530//
1531// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1532// for example. If 'A', foo will have external linkage. If we have '*A',
1533// foo will have no linkage. Since we can't know until we get to the end
1534// of the typedef, this function finds out if D might have non-external linkage.
1535// Callers should verify at the end of the TU if it D has external linkage or
1536// not.
1537bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1538 const DeclContext *DC = D->getDeclContext();
1539 while (!DC->isTranslationUnit()) {
1540 if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1541 if (!RD->hasNameForLinkage())
1542 return true;
1543 }
1544 DC = DC->getParent();
1545 }
1546
1547 return !D->isExternallyVisible();
1548}
1549
1550// FIXME: This needs to be refactored; some other isInMainFile users want
1551// these semantics.
1552static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1553 if (S.TUKind != TU_Complete)
1554 return false;
1555 return S.SourceMgr.isInMainFile(Loc);
1556}
1557
1558bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1559 assert(D)(static_cast <bool> (D) ? void (0) : __assert_fail ("D"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 1559, __extension__ __PRETTY_FUNCTION__))
;
1560
1561 if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1562 return false;
1563
1564 // Ignore all entities declared within templates, and out-of-line definitions
1565 // of members of class templates.
1566 if (D->getDeclContext()->isDependentContext() ||
1567 D->getLexicalDeclContext()->isDependentContext())
1568 return false;
1569
1570 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1571 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1572 return false;
1573 // A non-out-of-line declaration of a member specialization was implicitly
1574 // instantiated; it's the out-of-line declaration that we're interested in.
1575 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1576 FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1577 return false;
1578
1579 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1580 if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1581 return false;
1582 } else {
1583 // 'static inline' functions are defined in headers; don't warn.
1584 if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1585 return false;
1586 }
1587
1588 if (FD->doesThisDeclarationHaveABody() &&
1589 Context.DeclMustBeEmitted(FD))
1590 return false;
1591 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1592 // Constants and utility variables are defined in headers with internal
1593 // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1594 // like "inline".)
1595 if (!isMainFileLoc(*this, VD->getLocation()))
1596 return false;
1597
1598 if (Context.DeclMustBeEmitted(VD))
1599 return false;
1600
1601 if (VD->isStaticDataMember() &&
1602 VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1603 return false;
1604 if (VD->isStaticDataMember() &&
1605 VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1606 VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1607 return false;
1608
1609 if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1610 return false;
1611 } else {
1612 return false;
1613 }
1614
1615 // Only warn for unused decls internal to the translation unit.
1616 // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1617 // for inline functions defined in the main source file, for instance.
1618 return mightHaveNonExternalLinkage(D);
1619}
1620
1621void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1622 if (!D)
1623 return;
1624
1625 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1626 const FunctionDecl *First = FD->getFirstDecl();
1627 if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1628 return; // First should already be in the vector.
1629 }
1630
1631 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1632 const VarDecl *First = VD->getFirstDecl();
1633 if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1634 return; // First should already be in the vector.
1635 }
1636
1637 if (ShouldWarnIfUnusedFileScopedDecl(D))
1638 UnusedFileScopedDecls.push_back(D);
1639}
1640
1641static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1642 if (D->isInvalidDecl())
1643 return false;
1644
1645 bool Referenced = false;
1646 if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1647 // For a decomposition declaration, warn if none of the bindings are
1648 // referenced, instead of if the variable itself is referenced (which
1649 // it is, by the bindings' expressions).
1650 for (auto *BD : DD->bindings()) {
1651 if (BD->isReferenced()) {
1652 Referenced = true;
1653 break;
1654 }
1655 }
1656 } else if (!D->getDeclName()) {
1657 return false;
1658 } else if (D->isReferenced() || D->isUsed()) {
1659 Referenced = true;
1660 }
1661
1662 if (Referenced || D->hasAttr<UnusedAttr>() ||
1663 D->hasAttr<ObjCPreciseLifetimeAttr>())
1664 return false;
1665
1666 if (isa<LabelDecl>(D))
1667 return true;
1668
1669 // Except for labels, we only care about unused decls that are local to
1670 // functions.
1671 bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1672 if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1673 // For dependent types, the diagnostic is deferred.
1674 WithinFunction =
1675 WithinFunction || (R->isLocalClass() && !R->isDependentType());
1676 if (!WithinFunction)
1677 return false;
1678
1679 if (isa<TypedefNameDecl>(D))
1680 return true;
1681
1682 // White-list anything that isn't a local variable.
1683 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1684 return false;
1685
1686 // Types of valid local variables should be complete, so this should succeed.
1687 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1688
1689 // White-list anything with an __attribute__((unused)) type.
1690 const auto *Ty = VD->getType().getTypePtr();
1691
1692 // Only look at the outermost level of typedef.
1693 if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1694 if (TT->getDecl()->hasAttr<UnusedAttr>())
1695 return false;
1696 }
1697
1698 // If we failed to complete the type for some reason, or if the type is
1699 // dependent, don't diagnose the variable.
1700 if (Ty->isIncompleteType() || Ty->isDependentType())
1701 return false;
1702
1703 // Look at the element type to ensure that the warning behaviour is
1704 // consistent for both scalars and arrays.
1705 Ty = Ty->getBaseElementTypeUnsafe();
1706
1707 if (const TagType *TT = Ty->getAs<TagType>()) {
1708 const TagDecl *Tag = TT->getDecl();
1709 if (Tag->hasAttr<UnusedAttr>())
1710 return false;
1711
1712 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1713 if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1714 return false;
1715
1716 if (const Expr *Init = VD->getInit()) {
1717 if (const ExprWithCleanups *Cleanups =
1718 dyn_cast<ExprWithCleanups>(Init))
1719 Init = Cleanups->getSubExpr();
1720 const CXXConstructExpr *Construct =
1721 dyn_cast<CXXConstructExpr>(Init);
1722 if (Construct && !Construct->isElidable()) {
1723 CXXConstructorDecl *CD = Construct->getConstructor();
1724 if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1725 (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1726 return false;
1727 }
1728 }
1729 }
1730 }
1731
1732 // TODO: __attribute__((unused)) templates?
1733 }
1734
1735 return true;
1736}
1737
1738static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1739 FixItHint &Hint) {
1740 if (isa<LabelDecl>(D)) {
1741 SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1742 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1743 if (AfterColon.isInvalid())
1744 return;
1745 Hint = FixItHint::CreateRemoval(CharSourceRange::
1746 getCharRange(D->getLocStart(), AfterColon));
1747 }
1748}
1749
1750void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1751 if (D->getTypeForDecl()->isDependentType())
1752 return;
1753
1754 for (auto *TmpD : D->decls()) {
1755 if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1756 DiagnoseUnusedDecl(T);
1757 else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1758 DiagnoseUnusedNestedTypedefs(R);
1759 }
1760}
1761
1762/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1763/// unless they are marked attr(unused).
1764void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1765 if (!ShouldDiagnoseUnusedDecl(D))
1766 return;
1767
1768 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1769 // typedefs can be referenced later on, so the diagnostics are emitted
1770 // at end-of-translation-unit.
1771 UnusedLocalTypedefNameCandidates.insert(TD);
1772 return;
1773 }
1774
1775 FixItHint Hint;
1776 GenerateFixForUnusedDecl(D, Context, Hint);
1777
1778 unsigned DiagID;
1779 if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1780 DiagID = diag::warn_unused_exception_param;
1781 else if (isa<LabelDecl>(D))
1782 DiagID = diag::warn_unused_label;
1783 else
1784 DiagID = diag::warn_unused_variable;
1785
1786 Diag(D->getLocation(), DiagID) << D << Hint;
1787}
1788
1789static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1790 // Verify that we have no forward references left. If so, there was a goto
1791 // or address of a label taken, but no definition of it. Label fwd
1792 // definitions are indicated with a null substmt which is also not a resolved
1793 // MS inline assembly label name.
1794 bool Diagnose = false;
1795 if (L->isMSAsmLabel())
1796 Diagnose = !L->isResolvedMSAsmLabel();
1797 else
1798 Diagnose = L->getStmt() == nullptr;
1799 if (Diagnose)
1800 S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1801}
1802
1803void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1804 S->mergeNRVOIntoParent();
1805
1806 if (S->decl_empty()) return;
1807 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&(static_cast <bool> ((S->getFlags() & (Scope::DeclScope
| Scope::TemplateParamScope)) && "Scope shouldn't contain decls!"
) ? void (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 1808, __extension__ __PRETTY_FUNCTION__))
1808 "Scope shouldn't contain decls!")(static_cast <bool> ((S->getFlags() & (Scope::DeclScope
| Scope::TemplateParamScope)) && "Scope shouldn't contain decls!"
) ? void (0) : __assert_fail ("(S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) && \"Scope shouldn't contain decls!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 1808, __extension__ __PRETTY_FUNCTION__))
;
1809
1810 for (auto *TmpD : S->decls()) {
1811 assert(TmpD && "This decl didn't get pushed??")(static_cast <bool> (TmpD && "This decl didn't get pushed??"
) ? void (0) : __assert_fail ("TmpD && \"This decl didn't get pushed??\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 1811, __extension__ __PRETTY_FUNCTION__))
;
1812
1813 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?")(static_cast <bool> (isa<NamedDecl>(TmpD) &&
"Decl isn't NamedDecl?") ? void (0) : __assert_fail ("isa<NamedDecl>(TmpD) && \"Decl isn't NamedDecl?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 1813, __extension__ __PRETTY_FUNCTION__))
;
1814 NamedDecl *D = cast<NamedDecl>(TmpD);
1815
1816 // Diagnose unused variables in this scope.
1817 if (!S->hasUnrecoverableErrorOccurred()) {
1818 DiagnoseUnusedDecl(D);
1819 if (const auto *RD = dyn_cast<RecordDecl>(D))
1820 DiagnoseUnusedNestedTypedefs(RD);
1821 }
1822
1823 if (!D->getDeclName()) continue;
1824
1825 // If this was a forward reference to a label, verify it was defined.
1826 if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1827 CheckPoppedLabel(LD, *this);
1828
1829 // Remove this name from our lexical scope, and warn on it if we haven't
1830 // already.
1831 IdResolver.RemoveDecl(D);
1832 auto ShadowI = ShadowingDecls.find(D);
1833 if (ShadowI != ShadowingDecls.end()) {
1834 if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1835 Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1836 << D << FD << FD->getParent();
1837 Diag(FD->getLocation(), diag::note_previous_declaration);
1838 }
1839 ShadowingDecls.erase(ShadowI);
1840 }
1841 }
1842}
1843
1844/// \brief Look for an Objective-C class in the translation unit.
1845///
1846/// \param Id The name of the Objective-C class we're looking for. If
1847/// typo-correction fixes this name, the Id will be updated
1848/// to the fixed name.
1849///
1850/// \param IdLoc The location of the name in the translation unit.
1851///
1852/// \param DoTypoCorrection If true, this routine will attempt typo correction
1853/// if there is no class with the given name.
1854///
1855/// \returns The declaration of the named Objective-C class, or NULL if the
1856/// class could not be found.
1857ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1858 SourceLocation IdLoc,
1859 bool DoTypoCorrection) {
1860 // The third "scope" argument is 0 since we aren't enabling lazy built-in
1861 // creation from this context.
1862 NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1863
1864 if (!IDecl && DoTypoCorrection) {
1865 // Perform typo correction at the given location, but only if we
1866 // find an Objective-C class name.
1867 if (TypoCorrection C = CorrectTypo(
1868 DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1869 llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1870 CTK_ErrorRecovery)) {
1871 diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1872 IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1873 Id = IDecl->getIdentifier();
1874 }
1875 }
1876 ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1877 // This routine must always return a class definition, if any.
1878 if (Def && Def->getDefinition())
1879 Def = Def->getDefinition();
1880 return Def;
1881}
1882
1883/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1884/// from S, where a non-field would be declared. This routine copes
1885/// with the difference between C and C++ scoping rules in structs and
1886/// unions. For example, the following code is well-formed in C but
1887/// ill-formed in C++:
1888/// @code
1889/// struct S6 {
1890/// enum { BAR } e;
1891/// };
1892///
1893/// void test_S6() {
1894/// struct S6 a;
1895/// a.e = BAR;
1896/// }
1897/// @endcode
1898/// For the declaration of BAR, this routine will return a different
1899/// scope. The scope S will be the scope of the unnamed enumeration
1900/// within S6. In C++, this routine will return the scope associated
1901/// with S6, because the enumeration's scope is a transparent
1902/// context but structures can contain non-field names. In C, this
1903/// routine will return the translation unit scope, since the
1904/// enumeration's scope is a transparent context and structures cannot
1905/// contain non-field names.
1906Scope *Sema::getNonFieldDeclScope(Scope *S) {
1907 while (((S->getFlags() & Scope::DeclScope) == 0) ||
1908 (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1909 (S->isClassScope() && !getLangOpts().CPlusPlus))
1910 S = S->getParent();
1911 return S;
1912}
1913
1914/// \brief Looks up the declaration of "struct objc_super" and
1915/// saves it for later use in building builtin declaration of
1916/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1917/// pre-existing declaration exists no action takes place.
1918static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1919 IdentifierInfo *II) {
1920 if (!II->isStr("objc_msgSendSuper"))
1921 return;
1922 ASTContext &Context = ThisSema.Context;
1923
1924 LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1925 SourceLocation(), Sema::LookupTagName);
1926 ThisSema.LookupName(Result, S);
1927 if (Result.getResultKind() == LookupResult::Found)
1928 if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1929 Context.setObjCSuperType(Context.getTagDeclType(TD));
1930}
1931
1932static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1933 switch (Error) {
1934 case ASTContext::GE_None:
1935 return "";
1936 case ASTContext::GE_Missing_stdio:
1937 return "stdio.h";
1938 case ASTContext::GE_Missing_setjmp:
1939 return "setjmp.h";
1940 case ASTContext::GE_Missing_ucontext:
1941 return "ucontext.h";
1942 }
1943 llvm_unreachable("unhandled error kind")::llvm::llvm_unreachable_internal("unhandled error kind", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 1943)
;
1944}
1945
1946/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1947/// file scope. lazily create a decl for it. ForRedeclaration is true
1948/// if we're creating this built-in in anticipation of redeclaring the
1949/// built-in.
1950NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1951 Scope *S, bool ForRedeclaration,
1952 SourceLocation Loc) {
1953 LookupPredefedObjCSuperType(*this, S, II);
1954
1955 ASTContext::GetBuiltinTypeError Error;
1956 QualType R = Context.GetBuiltinType(ID, Error);
1957 if (Error) {
1958 if (ForRedeclaration)
1959 Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1960 << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1961 return nullptr;
1962 }
1963
1964 if (!ForRedeclaration &&
1965 (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1966 Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1967 Diag(Loc, diag::ext_implicit_lib_function_decl)
1968 << Context.BuiltinInfo.getName(ID) << R;
1969 if (Context.BuiltinInfo.getHeaderName(ID) &&
1970 !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1971 Diag(Loc, diag::note_include_header_or_declare)
1972 << Context.BuiltinInfo.getHeaderName(ID)
1973 << Context.BuiltinInfo.getName(ID);
1974 }
1975
1976 if (R.isNull())
1977 return nullptr;
1978
1979 DeclContext *Parent = Context.getTranslationUnitDecl();
1980 if (getLangOpts().CPlusPlus) {
1981 LinkageSpecDecl *CLinkageDecl =
1982 LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1983 LinkageSpecDecl::lang_c, false);
1984 CLinkageDecl->setImplicit();
1985 Parent->addDecl(CLinkageDecl);
1986 Parent = CLinkageDecl;
1987 }
1988
1989 FunctionDecl *New = FunctionDecl::Create(Context,
1990 Parent,
1991 Loc, Loc, II, R, /*TInfo=*/nullptr,
1992 SC_Extern,
1993 false,
1994 R->isFunctionProtoType());
1995 New->setImplicit();
1996
1997 // Create Decl objects for each parameter, adding them to the
1998 // FunctionDecl.
1999 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2000 SmallVector<ParmVarDecl*, 16> Params;
2001 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2002 ParmVarDecl *parm =
2003 ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
2004 nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
2005 SC_None, nullptr);
2006 parm->setScopeInfo(0, i);
2007 Params.push_back(parm);
2008 }
2009 New->setParams(Params);
2010 }
2011
2012 AddKnownFunctionAttributes(New);
2013 RegisterLocallyScopedExternCDecl(New, S);
2014
2015 // TUScope is the translation-unit scope to insert this function into.
2016 // FIXME: This is hideous. We need to teach PushOnScopeChains to
2017 // relate Scopes to DeclContexts, and probably eliminate CurContext
2018 // entirely, but we're not there yet.
2019 DeclContext *SavedContext = CurContext;
2020 CurContext = Parent;
2021 PushOnScopeChains(New, TUScope);
2022 CurContext = SavedContext;
2023 return New;
2024}
2025
2026/// Typedef declarations don't have linkage, but they still denote the same
2027/// entity if their types are the same.
2028/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2029/// isSameEntity.
2030static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2031 TypedefNameDecl *Decl,
2032 LookupResult &Previous) {
2033 // This is only interesting when modules are enabled.
2034 if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2035 return;
2036
2037 // Empty sets are uninteresting.
2038 if (Previous.empty())
2039 return;
2040
2041 LookupResult::Filter Filter = Previous.makeFilter();
2042 while (Filter.hasNext()) {
2043 NamedDecl *Old = Filter.next();
2044
2045 // Non-hidden declarations are never ignored.
2046 if (S.isVisible(Old))
2047 continue;
2048
2049 // Declarations of the same entity are not ignored, even if they have
2050 // different linkages.
2051 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2052 if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2053 Decl->getUnderlyingType()))
2054 continue;
2055
2056 // If both declarations give a tag declaration a typedef name for linkage
2057 // purposes, then they declare the same entity.
2058 if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2059 Decl->getAnonDeclWithTypedefName())
2060 continue;
2061 }
2062
2063 Filter.erase();
2064 }
2065
2066 Filter.done();
2067}
2068
2069bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
2070 QualType OldType;
2071 if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2072 OldType = OldTypedef->getUnderlyingType();
2073 else
2074 OldType = Context.getTypeDeclType(Old);
2075 QualType NewType = New->getUnderlyingType();
2076
2077 if (NewType->isVariablyModifiedType()) {
2078 // Must not redefine a typedef with a variably-modified type.
2079 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2080 Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2081 << Kind << NewType;
2082 if (Old->getLocation().isValid())
2083 notePreviousDefinition(Old, New->getLocation());
2084 New->setInvalidDecl();
2085 return true;
2086 }
2087
2088 if (OldType != NewType &&
2089 !OldType->isDependentType() &&
2090 !NewType->isDependentType() &&
2091 !Context.hasSameType(OldType, NewType)) {
2092 int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2093 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2094 << Kind << NewType << OldType;
2095 if (Old->getLocation().isValid())
2096 notePreviousDefinition(Old, New->getLocation());
2097 New->setInvalidDecl();
2098 return true;
2099 }
2100 return false;
2101}
2102
2103/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2104/// same name and scope as a previous declaration 'Old'. Figure out
2105/// how to resolve this situation, merging decls or emitting
2106/// diagnostics as appropriate. If there was an error, set New to be invalid.
2107///
2108void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
2109 LookupResult &OldDecls) {
2110 // If the new decl is known invalid already, don't bother doing any
2111 // merging checks.
2112 if (New->isInvalidDecl()) return;
2113
2114 // Allow multiple definitions for ObjC built-in typedefs.
2115 // FIXME: Verify the underlying types are equivalent!
2116 if (getLangOpts().ObjC1) {
2117 const IdentifierInfo *TypeID = New->getIdentifier();
2118 switch (TypeID->getLength()) {
2119 default: break;
2120 case 2:
2121 {
2122 if (!TypeID->isStr("id"))
2123 break;
2124 QualType T = New->getUnderlyingType();
2125 if (!T->isPointerType())
2126 break;
2127 if (!T->isVoidPointerType()) {
2128 QualType PT = T->getAs<PointerType>()->getPointeeType();
2129 if (!PT->isStructureType())
2130 break;
2131 }
2132 Context.setObjCIdRedefinitionType(T);
2133 // Install the built-in type for 'id', ignoring the current definition.
2134 New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2135 return;
2136 }
2137 case 5:
2138 if (!TypeID->isStr("Class"))
2139 break;
2140 Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2141 // Install the built-in type for 'Class', ignoring the current definition.
2142 New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2143 return;
2144 case 3:
2145 if (!TypeID->isStr("SEL"))
2146 break;
2147 Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2148 // Install the built-in type for 'SEL', ignoring the current definition.
2149 New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2150 return;
2151 }
2152 // Fall through - the typedef name was not a builtin type.
2153 }
2154
2155 // Verify the old decl was also a type.
2156 TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2157 if (!Old) {
2158 Diag(New->getLocation(), diag::err_redefinition_different_kind)
2159 << New->getDeclName();
2160
2161 NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2162 if (OldD->getLocation().isValid())
2163 notePreviousDefinition(OldD, New->getLocation());
2164
2165 return New->setInvalidDecl();
2166 }
2167
2168 // If the old declaration is invalid, just give up here.
2169 if (Old->isInvalidDecl())
2170 return New->setInvalidDecl();
2171
2172 if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2173 auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2174 auto *NewTag = New->getAnonDeclWithTypedefName();
2175 NamedDecl *Hidden = nullptr;
2176 if (OldTag && NewTag &&
2177 OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2178 !hasVisibleDefinition(OldTag, &Hidden)) {
2179 // There is a definition of this tag, but it is not visible. Use it
2180 // instead of our tag.
2181 New->setTypeForDecl(OldTD->getTypeForDecl());
2182 if (OldTD->isModed())
2183 New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2184 OldTD->getUnderlyingType());
2185 else
2186 New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2187
2188 // Make the old tag definition visible.
2189 makeMergedDefinitionVisible(Hidden);
2190
2191 // If this was an unscoped enumeration, yank all of its enumerators
2192 // out of the scope.
2193 if (isa<EnumDecl>(NewTag)) {
2194 Scope *EnumScope = getNonFieldDeclScope(S);
2195 for (auto *D : NewTag->decls()) {
2196 auto *ED = cast<EnumConstantDecl>(D);
2197 assert(EnumScope->isDeclScope(ED))(static_cast <bool> (EnumScope->isDeclScope(ED)) ? void
(0) : __assert_fail ("EnumScope->isDeclScope(ED)", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 2197, __extension__ __PRETTY_FUNCTION__))
;
2198 EnumScope->RemoveDecl(ED);
2199 IdResolver.RemoveDecl(ED);
2200 ED->getLexicalDeclContext()->removeDecl(ED);
2201 }
2202 }
2203 }
2204 }
2205
2206 // If the typedef types are not identical, reject them in all languages and
2207 // with any extensions enabled.
2208 if (isIncompatibleTypedef(Old, New))
2209 return;
2210
2211 // The types match. Link up the redeclaration chain and merge attributes if
2212 // the old declaration was a typedef.
2213 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2214 New->setPreviousDecl(Typedef);
2215 mergeDeclAttributes(New, Old);
2216 }
2217
2218 if (getLangOpts().MicrosoftExt)
2219 return;
2220
2221 if (getLangOpts().CPlusPlus) {
2222 // C++ [dcl.typedef]p2:
2223 // In a given non-class scope, a typedef specifier can be used to
2224 // redefine the name of any type declared in that scope to refer
2225 // to the type to which it already refers.
2226 if (!isa<CXXRecordDecl>(CurContext))
2227 return;
2228
2229 // C++0x [dcl.typedef]p4:
2230 // In a given class scope, a typedef specifier can be used to redefine
2231 // any class-name declared in that scope that is not also a typedef-name
2232 // to refer to the type to which it already refers.
2233 //
2234 // This wording came in via DR424, which was a correction to the
2235 // wording in DR56, which accidentally banned code like:
2236 //
2237 // struct S {
2238 // typedef struct A { } A;
2239 // };
2240 //
2241 // in the C++03 standard. We implement the C++0x semantics, which
2242 // allow the above but disallow
2243 //
2244 // struct S {
2245 // typedef int I;
2246 // typedef int I;
2247 // };
2248 //
2249 // since that was the intent of DR56.
2250 if (!isa<TypedefNameDecl>(Old))
2251 return;
2252
2253 Diag(New->getLocation(), diag::err_redefinition)
2254 << New->getDeclName();
2255 notePreviousDefinition(Old, New->getLocation());
2256 return New->setInvalidDecl();
2257 }
2258
2259 // Modules always permit redefinition of typedefs, as does C11.
2260 if (getLangOpts().Modules || getLangOpts().C11)
2261 return;
2262
2263 // If we have a redefinition of a typedef in C, emit a warning. This warning
2264 // is normally mapped to an error, but can be controlled with
2265 // -Wtypedef-redefinition. If either the original or the redefinition is
2266 // in a system header, don't emit this for compatibility with GCC.
2267 if (getDiagnostics().getSuppressSystemWarnings() &&
2268 // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2269 (Old->isImplicit() ||
2270 Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2271 Context.getSourceManager().isInSystemHeader(New->getLocation())))
2272 return;
2273
2274 Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2275 << New->getDeclName();
2276 notePreviousDefinition(Old, New->getLocation());
2277}
2278
2279/// DeclhasAttr - returns true if decl Declaration already has the target
2280/// attribute.
2281static bool DeclHasAttr(const Decl *D, const Attr *A) {
2282 const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2283 const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2284 for (const auto *i : D->attrs())
2285 if (i->getKind() == A->getKind()) {
2286 if (Ann) {
2287 if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2288 return true;
2289 continue;
2290 }
2291 // FIXME: Don't hardcode this check
2292 if (OA && isa<OwnershipAttr>(i))
2293 return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2294 return true;
2295 }
2296
2297 return false;
2298}
2299
2300static bool isAttributeTargetADefinition(Decl *D) {
2301 if (VarDecl *VD = dyn_cast<VarDecl>(D))
2302 return VD->isThisDeclarationADefinition();
2303 if (TagDecl *TD = dyn_cast<TagDecl>(D))
2304 return TD->isCompleteDefinition() || TD->isBeingDefined();
2305 return true;
2306}
2307
2308/// Merge alignment attributes from \p Old to \p New, taking into account the
2309/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2310///
2311/// \return \c true if any attributes were added to \p New.
2312static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2313 // Look for alignas attributes on Old, and pick out whichever attribute
2314 // specifies the strictest alignment requirement.
2315 AlignedAttr *OldAlignasAttr = nullptr;
2316 AlignedAttr *OldStrictestAlignAttr = nullptr;
2317 unsigned OldAlign = 0;
2318 for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2319 // FIXME: We have no way of representing inherited dependent alignments
2320 // in a case like:
2321 // template<int A, int B> struct alignas(A) X;
2322 // template<int A, int B> struct alignas(B) X {};
2323 // For now, we just ignore any alignas attributes which are not on the
2324 // definition in such a case.
2325 if (I->isAlignmentDependent())
2326 return false;
2327
2328 if (I->isAlignas())
2329 OldAlignasAttr = I;
2330
2331 unsigned Align = I->getAlignment(S.Context);
2332 if (Align > OldAlign) {
2333 OldAlign = Align;
2334 OldStrictestAlignAttr = I;
2335 }
2336 }
2337
2338 // Look for alignas attributes on New.
2339 AlignedAttr *NewAlignasAttr = nullptr;
2340 unsigned NewAlign = 0;
2341 for (auto *I : New->specific_attrs<AlignedAttr>()) {
2342 if (I->isAlignmentDependent())
2343 return false;
2344
2345 if (I->isAlignas())
2346 NewAlignasAttr = I;
2347
2348 unsigned Align = I->getAlignment(S.Context);
2349 if (Align > NewAlign)
2350 NewAlign = Align;
2351 }
2352
2353 if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2354 // Both declarations have 'alignas' attributes. We require them to match.
2355 // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2356 // fall short. (If two declarations both have alignas, they must both match
2357 // every definition, and so must match each other if there is a definition.)
2358
2359 // If either declaration only contains 'alignas(0)' specifiers, then it
2360 // specifies the natural alignment for the type.
2361 if (OldAlign == 0 || NewAlign == 0) {
2362 QualType Ty;
2363 if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2364 Ty = VD->getType();
2365 else
2366 Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2367
2368 if (OldAlign == 0)
2369 OldAlign = S.Context.getTypeAlign(Ty);
2370 if (NewAlign == 0)
2371 NewAlign = S.Context.getTypeAlign(Ty);
2372 }
2373
2374 if (OldAlign != NewAlign) {
2375 S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2376 << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2377 << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2378 S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2379 }
2380 }
2381
2382 if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2383 // C++11 [dcl.align]p6:
2384 // if any declaration of an entity has an alignment-specifier,
2385 // every defining declaration of that entity shall specify an
2386 // equivalent alignment.
2387 // C11 6.7.5/7:
2388 // If the definition of an object does not have an alignment
2389 // specifier, any other declaration of that object shall also
2390 // have no alignment specifier.
2391 S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2392 << OldAlignasAttr;
2393 S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2394 << OldAlignasAttr;
2395 }
2396
2397 bool AnyAdded = false;
2398
2399 // Ensure we have an attribute representing the strictest alignment.
2400 if (OldAlign > NewAlign) {
2401 AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2402 Clone->setInherited(true);
2403 New->addAttr(Clone);
2404 AnyAdded = true;
2405 }
2406
2407 // Ensure we have an alignas attribute if the old declaration had one.
2408 if (OldAlignasAttr && !NewAlignasAttr &&
2409 !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2410 AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2411 Clone->setInherited(true);
2412 New->addAttr(Clone);
2413 AnyAdded = true;
2414 }
2415
2416 return AnyAdded;
2417}
2418
2419static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2420 const InheritableAttr *Attr,
2421 Sema::AvailabilityMergeKind AMK) {
2422 // This function copies an attribute Attr from a previous declaration to the
2423 // new declaration D if the new declaration doesn't itself have that attribute
2424 // yet or if that attribute allows duplicates.
2425 // If you're adding a new attribute that requires logic different from
2426 // "use explicit attribute on decl if present, else use attribute from
2427 // previous decl", for example if the attribute needs to be consistent
2428 // between redeclarations, you need to call a custom merge function here.
2429 InheritableAttr *NewAttr = nullptr;
2430 unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2431 if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2432 NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2433 AA->isImplicit(), AA->getIntroduced(),
2434 AA->getDeprecated(),
2435 AA->getObsoleted(), AA->getUnavailable(),
2436 AA->getMessage(), AA->getStrict(),
2437 AA->getReplacement(), AMK,
2438 AttrSpellingListIndex);
2439 else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2440 NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2441 AttrSpellingListIndex);
2442 else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2443 NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2444 AttrSpellingListIndex);
2445 else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2446 NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2447 AttrSpellingListIndex);
2448 else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2449 NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2450 AttrSpellingListIndex);
2451 else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2452 NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2453 FA->getFormatIdx(), FA->getFirstArg(),
2454 AttrSpellingListIndex);
2455 else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2456 NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2457 AttrSpellingListIndex);
2458 else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2459 NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2460 AttrSpellingListIndex,
2461 IA->getSemanticSpelling());
2462 else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2463 NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2464 &S.Context.Idents.get(AA->getSpelling()),
2465 AttrSpellingListIndex);
2466 else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2467 (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2468 isa<CUDAGlobalAttr>(Attr))) {
2469 // CUDA target attributes are part of function signature for
2470 // overloading purposes and must not be merged.
2471 return false;
2472 } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2473 NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2474 else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2475 NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2476 else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2477 NewAttr = S.mergeInternalLinkageAttr(
2478 D, InternalLinkageA->getRange(),
2479 &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2480 AttrSpellingListIndex);
2481 else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2482 NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2483 &S.Context.Idents.get(CommonA->getSpelling()),
2484 AttrSpellingListIndex);
2485 else if (isa<AlignedAttr>(Attr))
2486 // AlignedAttrs are handled separately, because we need to handle all
2487 // such attributes on a declaration at the same time.
2488 NewAttr = nullptr;
2489 else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2490 (AMK == Sema::AMK_Override ||
2491 AMK == Sema::AMK_ProtocolImplementation))
2492 NewAttr = nullptr;
2493 else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2494 NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2495 UA->getGuid());
2496 else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2497 NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2498
2499 if (NewAttr) {
2500 NewAttr->setInherited(true);
2501 D->addAttr(NewAttr);
2502 if (isa<MSInheritanceAttr>(NewAttr))
2503 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2504 return true;
2505 }
2506
2507 return false;
2508}
2509
2510static const NamedDecl *getDefinition(const Decl *D) {
2511 if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2512 return TD->getDefinition();
2513 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2514 const VarDecl *Def = VD->getDefinition();
2515 if (Def)
2516 return Def;
2517 return VD->getActingDefinition();
2518 }
2519 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2520 return FD->getDefinition();
2521 return nullptr;
2522}
2523
2524static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2525 for (const auto *Attribute : D->attrs())
2526 if (Attribute->getKind() == Kind)
2527 return true;
2528 return false;
2529}
2530
2531/// checkNewAttributesAfterDef - If we already have a definition, check that
2532/// there are no new attributes in this declaration.
2533static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2534 if (!New->hasAttrs())
2535 return;
2536
2537 const NamedDecl *Def = getDefinition(Old);
2538 if (!Def || Def == New)
2539 return;
2540
2541 AttrVec &NewAttributes = New->getAttrs();
2542 for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2543 const Attr *NewAttribute = NewAttributes[I];
2544
2545 if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2546 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2547 Sema::SkipBodyInfo SkipBody;
2548 S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2549
2550 // If we're skipping this definition, drop the "alias" attribute.
2551 if (SkipBody.ShouldSkip) {
2552 NewAttributes.erase(NewAttributes.begin() + I);
2553 --E;
2554 continue;
2555 }
2556 } else {
2557 VarDecl *VD = cast<VarDecl>(New);
2558 unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2559 VarDecl::TentativeDefinition
2560 ? diag::err_alias_after_tentative
2561 : diag::err_redefinition;
2562 S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2563 if (Diag == diag::err_redefinition)
2564 S.notePreviousDefinition(Def, VD->getLocation());
2565 else
2566 S.Diag(Def->getLocation(), diag::note_previous_definition);
2567 VD->setInvalidDecl();
2568 }
2569 ++I;
2570 continue;
2571 }
2572
2573 if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2574 // Tentative definitions are only interesting for the alias check above.
2575 if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2576 ++I;
2577 continue;
2578 }
2579 }
2580
2581 if (hasAttribute(Def, NewAttribute->getKind())) {
2582 ++I;
2583 continue; // regular attr merging will take care of validating this.
2584 }
2585
2586 if (isa<C11NoReturnAttr>(NewAttribute)) {
2587 // C's _Noreturn is allowed to be added to a function after it is defined.
2588 ++I;
2589 continue;
2590 } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2591 if (AA->isAlignas()) {
2592 // C++11 [dcl.align]p6:
2593 // if any declaration of an entity has an alignment-specifier,
2594 // every defining declaration of that entity shall specify an
2595 // equivalent alignment.
2596 // C11 6.7.5/7:
2597 // If the definition of an object does not have an alignment
2598 // specifier, any other declaration of that object shall also
2599 // have no alignment specifier.
2600 S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2601 << AA;
2602 S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2603 << AA;
2604 NewAttributes.erase(NewAttributes.begin() + I);
2605 --E;
2606 continue;
2607 }
2608 }
2609
2610 S.Diag(NewAttribute->getLocation(),
2611 diag::warn_attribute_precede_definition);
2612 S.Diag(Def->getLocation(), diag::note_previous_definition);
2613 NewAttributes.erase(NewAttributes.begin() + I);
2614 --E;
2615 }
2616}
2617
2618/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2619void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2620 AvailabilityMergeKind AMK) {
2621 if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2622 UsedAttr *NewAttr = OldAttr->clone(Context);
2623 NewAttr->setInherited(true);
2624 New->addAttr(NewAttr);
2625 }
2626
2627 if (!Old->hasAttrs() && !New->hasAttrs())
2628 return;
2629
2630 // Attributes declared post-definition are currently ignored.
2631 checkNewAttributesAfterDef(*this, New, Old);
2632
2633 if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2634 if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2635 if (OldA->getLabel() != NewA->getLabel()) {
2636 // This redeclaration changes __asm__ label.
2637 Diag(New->getLocation(), diag::err_different_asm_label);
2638 Diag(OldA->getLocation(), diag::note_previous_declaration);
2639 }
2640 } else if (Old->isUsed()) {
2641 // This redeclaration adds an __asm__ label to a declaration that has
2642 // already been ODR-used.
2643 Diag(New->getLocation(), diag::err_late_asm_label_name)
2644 << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2645 }
2646 }
2647
2648 // Re-declaration cannot add abi_tag's.
2649 if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2650 if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2651 for (const auto &NewTag : NewAbiTagAttr->tags()) {
2652 if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2653 NewTag) == OldAbiTagAttr->tags_end()) {
2654 Diag(NewAbiTagAttr->getLocation(),
2655 diag::err_new_abi_tag_on_redeclaration)
2656 << NewTag;
2657 Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2658 }
2659 }
2660 } else {
2661 Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2662 Diag(Old->getLocation(), diag::note_previous_declaration);
2663 }
2664 }
2665
2666 // This redeclaration adds a section attribute.
2667 if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2668 if (auto *VD = dyn_cast<VarDecl>(New)) {
2669 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2670 Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2671 Diag(Old->getLocation(), diag::note_previous_declaration);
2672 }
2673 }
2674 }
2675
2676 if (!Old->hasAttrs())
2677 return;
2678
2679 bool foundAny = New->hasAttrs();
2680
2681 // Ensure that any moving of objects within the allocated map is done before
2682 // we process them.
2683 if (!foundAny) New->setAttrs(AttrVec());
2684
2685 for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2686 // Ignore deprecated/unavailable/availability attributes if requested.
2687 AvailabilityMergeKind LocalAMK = AMK_None;
2688 if (isa<DeprecatedAttr>(I) ||
2689 isa<UnavailableAttr>(I) ||
2690 isa<AvailabilityAttr>(I)) {
2691 switch (AMK) {
2692 case AMK_None:
2693 continue;
2694
2695 case AMK_Redeclaration:
2696 case AMK_Override:
2697 case AMK_ProtocolImplementation:
2698 LocalAMK = AMK;
2699 break;
2700 }
2701 }
2702
2703 // Already handled.
2704 if (isa<UsedAttr>(I))
2705 continue;
2706
2707 if (mergeDeclAttribute(*this, New, I, LocalAMK))
2708 foundAny = true;
2709 }
2710
2711 if (mergeAlignedAttrs(*this, New, Old))
2712 foundAny = true;
2713
2714 if (!foundAny) New->dropAttrs();
2715}
2716
2717/// mergeParamDeclAttributes - Copy attributes from the old parameter
2718/// to the new one.
2719static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2720 const ParmVarDecl *oldDecl,
2721 Sema &S) {
2722 // C++11 [dcl.attr.depend]p2:
2723 // The first declaration of a function shall specify the
2724 // carries_dependency attribute for its declarator-id if any declaration
2725 // of the function specifies the carries_dependency attribute.
2726 const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2727 if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2728 S.Diag(CDA->getLocation(),
2729 diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2730 // Find the first declaration of the parameter.
2731 // FIXME: Should we build redeclaration chains for function parameters?
2732 const FunctionDecl *FirstFD =
2733 cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2734 const ParmVarDecl *FirstVD =
2735 FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2736 S.Diag(FirstVD->getLocation(),
2737 diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2738 }
2739
2740 if (!oldDecl->hasAttrs())
2741 return;
2742
2743 bool foundAny = newDecl->hasAttrs();
2744
2745 // Ensure that any moving of objects within the allocated map is
2746 // done before we process them.
2747 if (!foundAny) newDecl->setAttrs(AttrVec());
2748
2749 for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2750 if (!DeclHasAttr(newDecl, I)) {
2751 InheritableAttr *newAttr =
2752 cast<InheritableParamAttr>(I->clone(S.Context));
2753 newAttr->setInherited(true);
2754 newDecl->addAttr(newAttr);
2755 foundAny = true;
2756 }
2757 }
2758
2759 if (!foundAny) newDecl->dropAttrs();
2760}
2761
2762static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2763 const ParmVarDecl *OldParam,
2764 Sema &S) {
2765 if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2766 if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2767 if (*Oldnullability != *Newnullability) {
2768 S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2769 << DiagNullabilityKind(
2770 *Newnullability,
2771 ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2772 != 0))
2773 << DiagNullabilityKind(
2774 *Oldnullability,
2775 ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2776 != 0));
2777 S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2778 }
2779 } else {
2780 QualType NewT = NewParam->getType();
2781 NewT = S.Context.getAttributedType(
2782 AttributedType::getNullabilityAttrKind(*Oldnullability),
2783 NewT, NewT);
2784 NewParam->setType(NewT);
2785 }
2786 }
2787}
2788
2789namespace {
2790
2791/// Used in MergeFunctionDecl to keep track of function parameters in
2792/// C.
2793struct GNUCompatibleParamWarning {
2794 ParmVarDecl *OldParm;
2795 ParmVarDecl *NewParm;
2796 QualType PromotedType;
2797};
2798
2799} // end anonymous namespace
2800
2801/// getSpecialMember - get the special member enum for a method.
2802Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2803 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2804 if (Ctor->isDefaultConstructor())
2805 return Sema::CXXDefaultConstructor;
2806
2807 if (Ctor->isCopyConstructor())
2808 return Sema::CXXCopyConstructor;
2809
2810 if (Ctor->isMoveConstructor())
2811 return Sema::CXXMoveConstructor;
2812 } else if (isa<CXXDestructorDecl>(MD)) {
2813 return Sema::CXXDestructor;
2814 } else if (MD->isCopyAssignmentOperator()) {
2815 return Sema::CXXCopyAssignment;
2816 } else if (MD->isMoveAssignmentOperator()) {
2817 return Sema::CXXMoveAssignment;
2818 }
2819
2820 return Sema::CXXInvalid;
2821}
2822
2823// Determine whether the previous declaration was a definition, implicit
2824// declaration, or a declaration.
2825template <typename T>
2826static std::pair<diag::kind, SourceLocation>
2827getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2828 diag::kind PrevDiag;
2829 SourceLocation OldLocation = Old->getLocation();
2830 if (Old->isThisDeclarationADefinition())
2831 PrevDiag = diag::note_previous_definition;
2832 else if (Old->isImplicit()) {
2833 PrevDiag = diag::note_previous_implicit_declaration;
2834 if (OldLocation.isInvalid())
2835 OldLocation = New->getLocation();
2836 } else
2837 PrevDiag = diag::note_previous_declaration;
2838 return std::make_pair(PrevDiag, OldLocation);
2839}
2840
2841/// canRedefineFunction - checks if a function can be redefined. Currently,
2842/// only extern inline functions can be redefined, and even then only in
2843/// GNU89 mode.
2844static bool canRedefineFunction(const FunctionDecl *FD,
2845 const LangOptions& LangOpts) {
2846 return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2847 !LangOpts.CPlusPlus &&
2848 FD->isInlineSpecified() &&
2849 FD->getStorageClass() == SC_Extern);
2850}
2851
2852const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2853 const AttributedType *AT = T->getAs<AttributedType>();
2854 while (AT && !AT->isCallingConv())
2855 AT = AT->getModifiedType()->getAs<AttributedType>();
2856 return AT;
2857}
2858
2859template <typename T>
2860static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2861 const DeclContext *DC = Old->getDeclContext();
2862 if (DC->isRecord())
2863 return false;
2864
2865 LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2866 if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2867 return true;
2868 if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2869 return true;
2870 return false;
2871}
2872
2873template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2874static bool isExternC(VarTemplateDecl *) { return false; }
2875
2876/// \brief Check whether a redeclaration of an entity introduced by a
2877/// using-declaration is valid, given that we know it's not an overload
2878/// (nor a hidden tag declaration).
2879template<typename ExpectedDecl>
2880static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2881 ExpectedDecl *New) {
2882 // C++11 [basic.scope.declarative]p4:
2883 // Given a set of declarations in a single declarative region, each of
2884 // which specifies the same unqualified name,
2885 // -- they shall all refer to the same entity, or all refer to functions
2886 // and function templates; or
2887 // -- exactly one declaration shall declare a class name or enumeration
2888 // name that is not a typedef name and the other declarations shall all
2889 // refer to the same variable or enumerator, or all refer to functions
2890 // and function templates; in this case the class name or enumeration
2891 // name is hidden (3.3.10).
2892
2893 // C++11 [namespace.udecl]p14:
2894 // If a function declaration in namespace scope or block scope has the
2895 // same name and the same parameter-type-list as a function introduced
2896 // by a using-declaration, and the declarations do not declare the same
2897 // function, the program is ill-formed.
2898
2899 auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2900 if (Old &&
2901 !Old->getDeclContext()->getRedeclContext()->Equals(
2902 New->getDeclContext()->getRedeclContext()) &&
2903 !(isExternC(Old) && isExternC(New)))
2904 Old = nullptr;
2905
2906 if (!Old) {
2907 S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2908 S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2909 S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2910 return true;
2911 }
2912 return false;
2913}
2914
2915static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2916 const FunctionDecl *B) {
2917 assert(A->getNumParams() == B->getNumParams())(static_cast <bool> (A->getNumParams() == B->getNumParams
()) ? void (0) : __assert_fail ("A->getNumParams() == B->getNumParams()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 2917, __extension__ __PRETTY_FUNCTION__))
;
2918
2919 auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2920 const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2921 const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2922 if (AttrA == AttrB)
2923 return true;
2924 return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2925 };
2926
2927 return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2928}
2929
2930/// If necessary, adjust the semantic declaration context for a qualified
2931/// declaration to name the correct inline namespace within the qualifier.
2932static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
2933 DeclaratorDecl *OldD) {
2934 // The only case where we need to update the DeclContext is when
2935 // redeclaration lookup for a qualified name finds a declaration
2936 // in an inline namespace within the context named by the qualifier:
2937 //
2938 // inline namespace N { int f(); }
2939 // int ::f(); // Sema DC needs adjusting from :: to N::.
2940 //
2941 // For unqualified declarations, the semantic context *can* change
2942 // along the redeclaration chain (for local extern declarations,
2943 // extern "C" declarations, and friend declarations in particular).
2944 if (!NewD->getQualifier())
2945 return;
2946
2947 // NewD is probably already in the right context.
2948 auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
2949 auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
2950 if (NamedDC->Equals(SemaDC))
2951 return;
2952
2953 assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||(static_cast <bool> ((NamedDC->InEnclosingNamespaceSetOf
(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl
()) && "unexpected context for redeclaration") ? void
(0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 2955, __extension__ __PRETTY_FUNCTION__))
2954 NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&(static_cast <bool> ((NamedDC->InEnclosingNamespaceSetOf
(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl
()) && "unexpected context for redeclaration") ? void
(0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 2955, __extension__ __PRETTY_FUNCTION__))
2955 "unexpected context for redeclaration")(static_cast <bool> ((NamedDC->InEnclosingNamespaceSetOf
(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl
()) && "unexpected context for redeclaration") ? void
(0) : __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 2955, __extension__ __PRETTY_FUNCTION__))
;
2956
2957 auto *LexDC = NewD->getLexicalDeclContext();
2958 auto FixSemaDC = [=](NamedDecl *D) {
2959 if (!D)
2960 return;
2961 D->setDeclContext(SemaDC);
2962 D->setLexicalDeclContext(LexDC);
2963 };
2964
2965 FixSemaDC(NewD);
2966 if (auto *FD = dyn_cast<FunctionDecl>(NewD))
2967 FixSemaDC(FD->getDescribedFunctionTemplate());
2968 else if (auto *VD = dyn_cast<VarDecl>(NewD))
2969 FixSemaDC(VD->getDescribedVarTemplate());
2970}
2971
2972/// MergeFunctionDecl - We just parsed a function 'New' from
2973/// declarator D which has the same name and scope as a previous
2974/// declaration 'Old'. Figure out how to resolve this situation,
2975/// merging decls or emitting diagnostics as appropriate.
2976///
2977/// In C++, New and Old must be declarations that are not
2978/// overloaded. Use IsOverload to determine whether New and Old are
2979/// overloaded, and to select the Old declaration that New should be
2980/// merged with.
2981///
2982/// Returns true if there was an error, false otherwise.
2983bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2984 Scope *S, bool MergeTypeWithOld) {
2985 // Verify the old decl was also a function.
2986 FunctionDecl *Old = OldD->getAsFunction();
2987 if (!Old) {
2988 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2989 if (New->getFriendObjectKind()) {
2990 Diag(New->getLocation(), diag::err_using_decl_friend);
2991 Diag(Shadow->getTargetDecl()->getLocation(),
2992 diag::note_using_decl_target);
2993 Diag(Shadow->getUsingDecl()->getLocation(),
2994 diag::note_using_decl) << 0;
2995 return true;
2996 }
2997
2998 // Check whether the two declarations might declare the same function.
2999 if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3000 return true;
3001 OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3002 } else {
3003 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3004 << New->getDeclName();
3005 notePreviousDefinition(OldD, New->getLocation());
3006 return true;
3007 }
3008 }
3009
3010 // If the old declaration is invalid, just give up here.
3011 if (Old->isInvalidDecl())
3012 return true;
3013
3014 diag::kind PrevDiag;
3015 SourceLocation OldLocation;
3016 std::tie(PrevDiag, OldLocation) =
3017 getNoteDiagForInvalidRedeclaration(Old, New);
3018
3019 // Don't complain about this if we're in GNU89 mode and the old function
3020 // is an extern inline function.
3021 // Don't complain about specializations. They are not supposed to have
3022 // storage classes.
3023 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3024 New->getStorageClass() == SC_Static &&
3025 Old->hasExternalFormalLinkage() &&
3026 !New->getTemplateSpecializationInfo() &&
3027 !canRedefineFunction(Old, getLangOpts())) {
3028 if (getLangOpts().MicrosoftExt) {
3029 Diag(New->getLocation(), diag::ext_static_non_static) << New;
3030 Diag(OldLocation, PrevDiag);
3031 } else {
3032 Diag(New->getLocation(), diag::err_static_non_static) << New;
3033 Diag(OldLocation, PrevDiag);
3034 return true;
3035 }
3036 }
3037
3038 if (New->hasAttr<InternalLinkageAttr>() &&
3039 !Old->hasAttr<InternalLinkageAttr>()) {
3040 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3041 << New->getDeclName();
3042 notePreviousDefinition(Old, New->getLocation());
3043 New->dropAttr<InternalLinkageAttr>();
3044 }
3045
3046 if (CheckRedeclarationModuleOwnership(New, Old))
3047 return true;
3048
3049 if (!getLangOpts().CPlusPlus) {
3050 bool OldOvl = Old->hasAttr<OverloadableAttr>();
3051 if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3052 Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3053 << New << OldOvl;
3054
3055 // Try our best to find a decl that actually has the overloadable
3056 // attribute for the note. In most cases (e.g. programs with only one
3057 // broken declaration/definition), this won't matter.
3058 //
3059 // FIXME: We could do this if we juggled some extra state in
3060 // OverloadableAttr, rather than just removing it.
3061 const Decl *DiagOld = Old;
3062 if (OldOvl) {
3063 auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3064 const auto *A = D->getAttr<OverloadableAttr>();
3065 return A && !A->isImplicit();
3066 });
3067 // If we've implicitly added *all* of the overloadable attrs to this
3068 // chain, emitting a "previous redecl" note is pointless.
3069 DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3070 }
3071
3072 if (DiagOld)
3073 Diag(DiagOld->getLocation(),
3074 diag::note_attribute_overloadable_prev_overload)
3075 << OldOvl;
3076
3077 if (OldOvl)
3078 New->addAttr(OverloadableAttr::CreateImplicit(Context));
3079 else
3080 New->dropAttr<OverloadableAttr>();
3081 }
3082 }
3083
3084 // If a function is first declared with a calling convention, but is later
3085 // declared or defined without one, all following decls assume the calling
3086 // convention of the first.
3087 //
3088 // It's OK if a function is first declared without a calling convention,
3089 // but is later declared or defined with the default calling convention.
3090 //
3091 // To test if either decl has an explicit calling convention, we look for
3092 // AttributedType sugar nodes on the type as written. If they are missing or
3093 // were canonicalized away, we assume the calling convention was implicit.
3094 //
3095 // Note also that we DO NOT return at this point, because we still have
3096 // other tests to run.
3097 QualType OldQType = Context.getCanonicalType(Old->getType());
3098 QualType NewQType = Context.getCanonicalType(New->getType());
3099 const FunctionType *OldType = cast<FunctionType>(OldQType);
3100 const FunctionType *NewType = cast<FunctionType>(NewQType);
3101 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3102 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3103 bool RequiresAdjustment = false;
3104
3105 if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3106 FunctionDecl *First = Old->getFirstDecl();
3107 const FunctionType *FT =
3108 First->getType().getCanonicalType()->castAs<FunctionType>();
3109 FunctionType::ExtInfo FI = FT->getExtInfo();
3110 bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3111 if (!NewCCExplicit) {
3112 // Inherit the CC from the previous declaration if it was specified
3113 // there but not here.
3114 NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3115 RequiresAdjustment = true;
3116 } else {
3117 // Calling conventions aren't compatible, so complain.
3118 bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3119 Diag(New->getLocation(), diag::err_cconv_change)
3120 << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3121 << !FirstCCExplicit
3122 << (!FirstCCExplicit ? "" :
3123 FunctionType::getNameForCallConv(FI.getCC()));
3124
3125 // Put the note on the first decl, since it is the one that matters.
3126 Diag(First->getLocation(), diag::note_previous_declaration);
3127 return true;
3128 }
3129 }
3130
3131 // FIXME: diagnose the other way around?
3132 if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3133 NewTypeInfo = NewTypeInfo.withNoReturn(true);
3134 RequiresAdjustment = true;
3135 }
3136
3137 // Merge regparm attribute.
3138 if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3139 OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3140 if (NewTypeInfo.getHasRegParm()) {
3141 Diag(New->getLocation(), diag::err_regparm_mismatch)
3142 << NewType->getRegParmType()
3143 << OldType->getRegParmType();
3144 Diag(OldLocation, diag::note_previous_declaration);
3145 return true;
3146 }
3147
3148 NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3149 RequiresAdjustment = true;
3150 }
3151
3152 // Merge ns_returns_retained attribute.
3153 if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3154 if (NewTypeInfo.getProducesResult()) {
3155 Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3156 << "'ns_returns_retained'";
3157 Diag(OldLocation, diag::note_previous_declaration);
3158 return true;
3159 }
3160
3161 NewTypeInfo = NewTypeInfo.withProducesResult(true);
3162 RequiresAdjustment = true;
3163 }
3164
3165 if (OldTypeInfo.getNoCallerSavedRegs() !=
3166 NewTypeInfo.getNoCallerSavedRegs()) {
3167 if (NewTypeInfo.getNoCallerSavedRegs()) {
3168 AnyX86NoCallerSavedRegistersAttr *Attr =
3169 New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3170 Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3171 Diag(OldLocation, diag::note_previous_declaration);
3172 return true;
3173 }
3174
3175 NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3176 RequiresAdjustment = true;
3177 }
3178
3179 if (RequiresAdjustment) {
3180 const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3181 AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3182 New->setType(QualType(AdjustedType, 0));
3183 NewQType = Context.getCanonicalType(New->getType());
3184 NewType = cast<FunctionType>(NewQType);
3185 }
3186
3187 // If this redeclaration makes the function inline, we may need to add it to
3188 // UndefinedButUsed.
3189 if (!Old->isInlined() && New->isInlined() &&
3190 !New->hasAttr<GNUInlineAttr>() &&
3191 !getLangOpts().GNUInline &&
3192 Old->isUsed(false) &&
3193 !Old->isDefined() && !New->isThisDeclarationADefinition())
3194 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3195 SourceLocation()));
3196
3197 // If this redeclaration makes it newly gnu_inline, we don't want to warn
3198 // about it.
3199 if (New->hasAttr<GNUInlineAttr>() &&
3200 Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3201 UndefinedButUsed.erase(Old->getCanonicalDecl());
3202 }
3203
3204 // If pass_object_size params don't match up perfectly, this isn't a valid
3205 // redeclaration.
3206 if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3207 !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3208 Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3209 << New->getDeclName();
3210 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3211 return true;
3212 }
3213
3214 if (getLangOpts().CPlusPlus) {
3215 // C++1z [over.load]p2
3216 // Certain function declarations cannot be overloaded:
3217 // -- Function declarations that differ only in the return type,
3218 // the exception specification, or both cannot be overloaded.
3219
3220 // Check the exception specifications match. This may recompute the type of
3221 // both Old and New if it resolved exception specifications, so grab the
3222 // types again after this. Because this updates the type, we do this before
3223 // any of the other checks below, which may update the "de facto" NewQType
3224 // but do not necessarily update the type of New.
3225 if (CheckEquivalentExceptionSpec(Old, New))
3226 return true;
3227 OldQType = Context.getCanonicalType(Old->getType());
3228 NewQType = Context.getCanonicalType(New->getType());
3229
3230 // Go back to the type source info to compare the declared return types,
3231 // per C++1y [dcl.type.auto]p13:
3232 // Redeclarations or specializations of a function or function template
3233 // with a declared return type that uses a placeholder type shall also
3234 // use that placeholder, not a deduced type.
3235 QualType OldDeclaredReturnType =
3236 (Old->getTypeSourceInfo()
3237 ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3238 : OldType)->getReturnType();
3239 QualType NewDeclaredReturnType =
3240 (New->getTypeSourceInfo()
3241 ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3242 : NewType)->getReturnType();
3243 if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3244 !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3245 New->isLocalExternDecl())) {
3246 QualType ResQT;
3247 if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3248 OldDeclaredReturnType->isObjCObjectPointerType())
3249 ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3250 if (ResQT.isNull()) {
3251 if (New->isCXXClassMember() && New->isOutOfLine())
3252 Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3253 << New << New->getReturnTypeSourceRange();
3254 else
3255 Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3256 << New->getReturnTypeSourceRange();
3257 Diag(OldLocation, PrevDiag) << Old << Old->getType()
3258 << Old->getReturnTypeSourceRange();
3259 return true;
3260 }
3261 else
3262 NewQType = ResQT;
3263 }
3264
3265 QualType OldReturnType = OldType->getReturnType();
3266 QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3267 if (OldReturnType != NewReturnType) {
3268 // If this function has a deduced return type and has already been
3269 // defined, copy the deduced value from the old declaration.
3270 AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3271 if (OldAT && OldAT->isDeduced()) {
3272 New->setType(
3273 SubstAutoType(New->getType(),
3274 OldAT->isDependentType() ? Context.DependentTy
3275 : OldAT->getDeducedType()));
3276 NewQType = Context.getCanonicalType(
3277 SubstAutoType(NewQType,
3278 OldAT->isDependentType() ? Context.DependentTy
3279 : OldAT->getDeducedType()));
3280 }
3281 }
3282
3283 const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3284 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3285 if (OldMethod && NewMethod) {
3286 // Preserve triviality.
3287 NewMethod->setTrivial(OldMethod->isTrivial());
3288
3289 // MSVC allows explicit template specialization at class scope:
3290 // 2 CXXMethodDecls referring to the same function will be injected.
3291 // We don't want a redeclaration error.
3292 bool IsClassScopeExplicitSpecialization =
3293 OldMethod->isFunctionTemplateSpecialization() &&
3294 NewMethod->isFunctionTemplateSpecialization();
3295 bool isFriend = NewMethod->getFriendObjectKind();
3296
3297 if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3298 !IsClassScopeExplicitSpecialization) {
3299 // -- Member function declarations with the same name and the
3300 // same parameter types cannot be overloaded if any of them
3301 // is a static member function declaration.
3302 if (OldMethod->isStatic() != NewMethod->isStatic()) {
3303 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3304 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3305 return true;
3306 }
3307
3308 // C++ [class.mem]p1:
3309 // [...] A member shall not be declared twice in the
3310 // member-specification, except that a nested class or member
3311 // class template can be declared and then later defined.
3312 if (!inTemplateInstantiation()) {
3313 unsigned NewDiag;
3314 if (isa<CXXConstructorDecl>(OldMethod))
3315 NewDiag = diag::err_constructor_redeclared;
3316 else if (isa<CXXDestructorDecl>(NewMethod))
3317 NewDiag = diag::err_destructor_redeclared;
3318 else if (isa<CXXConversionDecl>(NewMethod))
3319 NewDiag = diag::err_conv_function_redeclared;
3320 else
3321 NewDiag = diag::err_member_redeclared;
3322
3323 Diag(New->getLocation(), NewDiag);
3324 } else {
3325 Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3326 << New << New->getType();
3327 }
3328 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3329 return true;
3330
3331 // Complain if this is an explicit declaration of a special
3332 // member that was initially declared implicitly.
3333 //
3334 // As an exception, it's okay to befriend such methods in order
3335 // to permit the implicit constructor/destructor/operator calls.
3336 } else if (OldMethod->isImplicit()) {
3337 if (isFriend) {
3338 NewMethod->setImplicit();
3339 } else {
3340 Diag(NewMethod->getLocation(),
3341 diag::err_definition_of_implicitly_declared_member)
3342 << New << getSpecialMember(OldMethod);
3343 return true;
3344 }
3345 } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3346 Diag(NewMethod->getLocation(),
3347 diag::err_definition_of_explicitly_defaulted_member)
3348 << getSpecialMember(OldMethod);
3349 return true;
3350 }
3351 }
3352
3353 // C++11 [dcl.attr.noreturn]p1:
3354 // The first declaration of a function shall specify the noreturn
3355 // attribute if any declaration of that function specifies the noreturn
3356 // attribute.
3357 const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3358 if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3359 Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3360 Diag(Old->getFirstDecl()->getLocation(),
3361 diag::note_noreturn_missing_first_decl);
3362 }
3363
3364 // C++11 [dcl.attr.depend]p2:
3365 // The first declaration of a function shall specify the
3366 // carries_dependency attribute for its declarator-id if any declaration
3367 // of the function specifies the carries_dependency attribute.
3368 const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3369 if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3370 Diag(CDA->getLocation(),
3371 diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3372 Diag(Old->getFirstDecl()->getLocation(),
3373 diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3374 }
3375
3376 // (C++98 8.3.5p3):
3377 // All declarations for a function shall agree exactly in both the
3378 // return type and the parameter-type-list.
3379 // We also want to respect all the extended bits except noreturn.
3380
3381 // noreturn should now match unless the old type info didn't have it.
3382 QualType OldQTypeForComparison = OldQType;
3383 if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3384 auto *OldType = OldQType->castAs<FunctionProtoType>();
3385 const FunctionType *OldTypeForComparison
3386 = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3387 OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3388 assert(OldQTypeForComparison.isCanonical())(static_cast <bool> (OldQTypeForComparison.isCanonical(
)) ? void (0) : __assert_fail ("OldQTypeForComparison.isCanonical()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 3388, __extension__ __PRETTY_FUNCTION__))
;
3389 }
3390
3391 if (haveIncompatibleLanguageLinkages(Old, New)) {
3392 // As a special case, retain the language linkage from previous
3393 // declarations of a friend function as an extension.
3394 //
3395 // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3396 // and is useful because there's otherwise no way to specify language
3397 // linkage within class scope.
3398 //
3399 // Check cautiously as the friend object kind isn't yet complete.
3400 if (New->getFriendObjectKind() != Decl::FOK_None) {
3401 Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3402 Diag(OldLocation, PrevDiag);
3403 } else {
3404 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3405 Diag(OldLocation, PrevDiag);
3406 return true;
3407 }
3408 }
3409
3410 if (OldQTypeForComparison == NewQType)
3411 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3412
3413 if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3414 New->isLocalExternDecl()) {
3415 // It's OK if we couldn't merge types for a local function declaraton
3416 // if either the old or new type is dependent. We'll merge the types
3417 // when we instantiate the function.
3418 return false;
3419 }
3420
3421 // Fall through for conflicting redeclarations and redefinitions.
3422 }
3423
3424 // C: Function types need to be compatible, not identical. This handles
3425 // duplicate function decls like "void f(int); void f(enum X);" properly.
3426 if (!getLangOpts().CPlusPlus &&
3427 Context.typesAreCompatible(OldQType, NewQType)) {
3428 const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3429 const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3430 const FunctionProtoType *OldProto = nullptr;
3431 if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3432 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3433 // The old declaration provided a function prototype, but the
3434 // new declaration does not. Merge in the prototype.
3435 assert(!OldProto->hasExceptionSpec() && "Exception spec in C")(static_cast <bool> (!OldProto->hasExceptionSpec() &&
"Exception spec in C") ? void (0) : __assert_fail ("!OldProto->hasExceptionSpec() && \"Exception spec in C\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 3435, __extension__ __PRETTY_FUNCTION__))
;
3436 SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3437 NewQType =
3438 Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3439 OldProto->getExtProtoInfo());
3440 New->setType(NewQType);
3441 New->setHasInheritedPrototype();
3442
3443 // Synthesize parameters with the same types.
3444 SmallVector<ParmVarDecl*, 16> Params;
3445 for (const auto &ParamType : OldProto->param_types()) {
3446 ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3447 SourceLocation(), nullptr,
3448 ParamType, /*TInfo=*/nullptr,
3449 SC_None, nullptr);
3450 Param->setScopeInfo(0, Params.size());
3451 Param->setImplicit();
3452 Params.push_back(Param);
3453 }
3454
3455 New->setParams(Params);
3456 }
3457
3458 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3459 }
3460
3461 // GNU C permits a K&R definition to follow a prototype declaration
3462 // if the declared types of the parameters in the K&R definition
3463 // match the types in the prototype declaration, even when the
3464 // promoted types of the parameters from the K&R definition differ
3465 // from the types in the prototype. GCC then keeps the types from
3466 // the prototype.
3467 //
3468 // If a variadic prototype is followed by a non-variadic K&R definition,
3469 // the K&R definition becomes variadic. This is sort of an edge case, but
3470 // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3471 // C99 6.9.1p8.
3472 if (!getLangOpts().CPlusPlus &&
3473 Old->hasPrototype() && !New->hasPrototype() &&
3474 New->getType()->getAs<FunctionProtoType>() &&
3475 Old->getNumParams() == New->getNumParams()) {
3476 SmallVector<QualType, 16> ArgTypes;
3477 SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3478 const FunctionProtoType *OldProto
3479 = Old->getType()->getAs<FunctionProtoType>();
3480 const FunctionProtoType *NewProto
3481 = New->getType()->getAs<FunctionProtoType>();
3482
3483 // Determine whether this is the GNU C extension.
3484 QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3485 NewProto->getReturnType());
3486 bool LooseCompatible = !MergedReturn.isNull();
3487 for (unsigned Idx = 0, End = Old->getNumParams();
3488 LooseCompatible && Idx != End; ++Idx) {
3489 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3490 ParmVarDecl *NewParm = New->getParamDecl(Idx);
3491 if (Context.typesAreCompatible(OldParm->getType(),
3492 NewProto->getParamType(Idx))) {
3493 ArgTypes.push_back(NewParm->getType());
3494 } else if (Context.typesAreCompatible(OldParm->getType(),
3495 NewParm->getType(),
3496 /*CompareUnqualified=*/true)) {
3497 GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3498 NewProto->getParamType(Idx) };
3499 Warnings.push_back(Warn);
3500 ArgTypes.push_back(NewParm->getType());
3501 } else
3502 LooseCompatible = false;
3503 }
3504
3505 if (LooseCompatible) {
3506 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3507 Diag(Warnings[Warn].NewParm->getLocation(),
3508 diag::ext_param_promoted_not_compatible_with_prototype)
3509 << Warnings[Warn].PromotedType
3510 << Warnings[Warn].OldParm->getType();
3511 if (Warnings[Warn].OldParm->getLocation().isValid())
3512 Diag(Warnings[Warn].OldParm->getLocation(),
3513 diag::note_previous_declaration);
3514 }
3515
3516 if (MergeTypeWithOld)
3517 New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3518 OldProto->getExtProtoInfo()));
3519 return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3520 }
3521
3522 // Fall through to diagnose conflicting types.
3523 }
3524
3525 // A function that has already been declared has been redeclared or
3526 // defined with a different type; show an appropriate diagnostic.
3527
3528 // If the previous declaration was an implicitly-generated builtin
3529 // declaration, then at the very least we should use a specialized note.
3530 unsigned BuiltinID;
3531 if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3532 // If it's actually a library-defined builtin function like 'malloc'
3533 // or 'printf', just warn about the incompatible redeclaration.
3534 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3535 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3536 Diag(OldLocation, diag::note_previous_builtin_declaration)
3537 << Old << Old->getType();
3538
3539 // If this is a global redeclaration, just forget hereafter
3540 // about the "builtin-ness" of the function.
3541 //
3542 // Doing this for local extern declarations is problematic. If
3543 // the builtin declaration remains visible, a second invalid
3544 // local declaration will produce a hard error; if it doesn't
3545 // remain visible, a single bogus local redeclaration (which is
3546 // actually only a warning) could break all the downstream code.
3547 if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3548 New->getIdentifier()->revertBuiltin();
3549
3550 return false;
3551 }
3552
3553 PrevDiag = diag::note_previous_builtin_declaration;
3554 }
3555
3556 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3557 Diag(OldLocation, PrevDiag) << Old << Old->getType();
3558 return true;
3559}
3560
3561/// \brief Completes the merge of two function declarations that are
3562/// known to be compatible.
3563///
3564/// This routine handles the merging of attributes and other
3565/// properties of function declarations from the old declaration to
3566/// the new declaration, once we know that New is in fact a
3567/// redeclaration of Old.
3568///
3569/// \returns false
3570bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3571 Scope *S, bool MergeTypeWithOld) {
3572 // Merge the attributes
3573 mergeDeclAttributes(New, Old);
3574
3575 // Merge "pure" flag.
3576 if (Old->isPure())
3577 New->setPure();
3578
3579 // Merge "used" flag.
3580 if (Old->getMostRecentDecl()->isUsed(false))
3581 New->setIsUsed();
3582
3583 // Merge attributes from the parameters. These can mismatch with K&R
3584 // declarations.
3585 if (New->getNumParams() == Old->getNumParams())
3586 for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3587 ParmVarDecl *NewParam = New->getParamDecl(i);
3588 ParmVarDecl *OldParam = Old->getParamDecl(i);
3589 mergeParamDeclAttributes(NewParam, OldParam, *this);
3590 mergeParamDeclTypes(NewParam, OldParam, *this);
3591 }
3592
3593 if (getLangOpts().CPlusPlus)
3594 return MergeCXXFunctionDecl(New, Old, S);
3595
3596 // Merge the function types so the we get the composite types for the return
3597 // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3598 // was visible.
3599 QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3600 if (!Merged.isNull() && MergeTypeWithOld)
3601 New->setType(Merged);
3602
3603 return false;
3604}
3605
3606void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3607 ObjCMethodDecl *oldMethod) {
3608 // Merge the attributes, including deprecated/unavailable
3609 AvailabilityMergeKind MergeKind =
3610 isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3611 ? AMK_ProtocolImplementation
3612 : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3613 : AMK_Override;
3614
3615 mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3616
3617 // Merge attributes from the parameters.
3618 ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3619 oe = oldMethod->param_end();
3620 for (ObjCMethodDecl::param_iterator
3621 ni = newMethod->param_begin(), ne = newMethod->param_end();
3622 ni != ne && oi != oe; ++ni, ++oi)
3623 mergeParamDeclAttributes(*ni, *oi, *this);
3624
3625 CheckObjCMethodOverride(newMethod, oldMethod);
3626}
3627
3628static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3629 assert(!S.Context.hasSameType(New->getType(), Old->getType()))(static_cast <bool> (!S.Context.hasSameType(New->getType
(), Old->getType())) ? void (0) : __assert_fail ("!S.Context.hasSameType(New->getType(), Old->getType())"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 3629, __extension__ __PRETTY_FUNCTION__))
;
3630
3631 S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3632 ? diag::err_redefinition_different_type
3633 : diag::err_redeclaration_different_type)
3634 << New->getDeclName() << New->getType() << Old->getType();
3635
3636 diag::kind PrevDiag;
3637 SourceLocation OldLocation;
3638 std::tie(PrevDiag, OldLocation)
3639 = getNoteDiagForInvalidRedeclaration(Old, New);
3640 S.Diag(OldLocation, PrevDiag);
3641 New->setInvalidDecl();
3642}
3643
3644/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3645/// scope as a previous declaration 'Old'. Figure out how to merge their types,
3646/// emitting diagnostics as appropriate.
3647///
3648/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3649/// to here in AddInitializerToDecl. We can't check them before the initializer
3650/// is attached.
3651void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3652 bool MergeTypeWithOld) {
3653 if (New->isInvalidDecl() || Old->isInvalidDecl())
3654 return;
3655
3656 QualType MergedT;
3657 if (getLangOpts().CPlusPlus) {
3658 if (New->getType()->isUndeducedType()) {
3659 // We don't know what the new type is until the initializer is attached.
3660 return;
3661 } else if (Context.hasSameType(New->getType(), Old->getType())) {
3662 // These could still be something that needs exception specs checked.
3663 return MergeVarDeclExceptionSpecs(New, Old);
3664 }
3665 // C++ [basic.link]p10:
3666 // [...] the types specified by all declarations referring to a given
3667 // object or function shall be identical, except that declarations for an
3668 // array object can specify array types that differ by the presence or
3669 // absence of a major array bound (8.3.4).
3670 else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3671 const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3672 const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3673
3674 // We are merging a variable declaration New into Old. If it has an array
3675 // bound, and that bound differs from Old's bound, we should diagnose the
3676 // mismatch.
3677 if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3678 for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3679 PrevVD = PrevVD->getPreviousDecl()) {
3680 const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3681 if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3682 continue;
3683
3684 if (!Context.hasSameType(NewArray, PrevVDTy))
3685 return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3686 }
3687 }
3688
3689 if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3690 if (Context.hasSameType(OldArray->getElementType(),
3691 NewArray->getElementType()))
3692 MergedT = New->getType();
3693 }
3694 // FIXME: Check visibility. New is hidden but has a complete type. If New
3695 // has no array bound, it should not inherit one from Old, if Old is not
3696 // visible.
3697 else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3698 if (Context.hasSameType(OldArray->getElementType(),
3699 NewArray->getElementType()))
3700 MergedT = Old->getType();
3701 }
3702 }
3703 else if (New->getType()->isObjCObjectPointerType() &&
3704 Old->getType()->isObjCObjectPointerType()) {
3705 MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3706 Old->getType());
3707 }
3708 } else {
3709 // C 6.2.7p2:
3710 // All declarations that refer to the same object or function shall have
3711 // compatible type.
3712 MergedT = Context.mergeTypes(New->getType(), Old->getType());
3713 }
3714 if (MergedT.isNull()) {
3715 // It's OK if we couldn't merge types if either type is dependent, for a
3716 // block-scope variable. In other cases (static data members of class
3717 // templates, variable templates, ...), we require the types to be
3718 // equivalent.
3719 // FIXME: The C++ standard doesn't say anything about this.
3720 if ((New->getType()->isDependentType() ||
3721 Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3722 // If the old type was dependent, we can't merge with it, so the new type
3723 // becomes dependent for now. We'll reproduce the original type when we
3724 // instantiate the TypeSourceInfo for the variable.
3725 if (!New->getType()->isDependentType() && MergeTypeWithOld)
3726 New->setType(Context.DependentTy);
3727 return;
3728 }
3729 return diagnoseVarDeclTypeMismatch(*this, New, Old);
3730 }
3731
3732 // Don't actually update the type on the new declaration if the old
3733 // declaration was an extern declaration in a different scope.
3734 if (MergeTypeWithOld)
3735 New->setType(MergedT);
3736}
3737
3738static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3739 LookupResult &Previous) {
3740 // C11 6.2.7p4:
3741 // For an identifier with internal or external linkage declared
3742 // in a scope in which a prior declaration of that identifier is
3743 // visible, if the prior declaration specifies internal or
3744 // external linkage, the type of the identifier at the later
3745 // declaration becomes the composite type.
3746 //
3747 // If the variable isn't visible, we do not merge with its type.
3748 if (Previous.isShadowed())
3749 return false;
3750
3751 if (S.getLangOpts().CPlusPlus) {
3752 // C++11 [dcl.array]p3:
3753 // If there is a preceding declaration of the entity in the same
3754 // scope in which the bound was specified, an omitted array bound
3755 // is taken to be the same as in that earlier declaration.
3756 return NewVD->isPreviousDeclInSameBlockScope() ||
3757 (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3758 !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3759 } else {
3760 // If the old declaration was function-local, don't merge with its
3761 // type unless we're in the same function.
3762 return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3763 OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3764 }
3765}
3766
3767/// MergeVarDecl - We just parsed a variable 'New' which has the same name
3768/// and scope as a previous declaration 'Old'. Figure out how to resolve this
3769/// situation, merging decls or emitting diagnostics as appropriate.
3770///
3771/// Tentative definition rules (C99 6.9.2p2) are checked by
3772/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3773/// definitions here, since the initializer hasn't been attached.
3774///
3775void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3776 // If the new decl is already invalid, don't do any other checking.
3777 if (New->isInvalidDecl())
3778 return;
3779
3780 if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3781 return;
3782
3783 VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3784
3785 // Verify the old decl was also a variable or variable template.
3786 VarDecl *Old = nullptr;
3787 VarTemplateDecl *OldTemplate = nullptr;
3788 if (Previous.isSingleResult()) {
3789 if (NewTemplate) {
3790 OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3791 Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3792
3793 if (auto *Shadow =
3794 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3795 if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3796 return New->setInvalidDecl();
3797 } else {
3798 Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3799
3800 if (auto *Shadow =
3801 dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3802 if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3803 return New->setInvalidDecl();
3804 }
3805 }
3806 if (!Old) {
3807 Diag(New->getLocation(), diag::err_redefinition_different_kind)
3808 << New->getDeclName();
3809 notePreviousDefinition(Previous.getRepresentativeDecl(),
3810 New->getLocation());
3811 return New->setInvalidDecl();
3812 }
3813
3814 // Ensure the template parameters are compatible.
3815 if (NewTemplate &&
3816 !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3817 OldTemplate->getTemplateParameters(),
3818 /*Complain=*/true, TPL_TemplateMatch))
3819 return New->setInvalidDecl();
3820
3821 // C++ [class.mem]p1:
3822 // A member shall not be declared twice in the member-specification [...]
3823 //
3824 // Here, we need only consider static data members.
3825 if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3826 Diag(New->getLocation(), diag::err_duplicate_member)
3827 << New->getIdentifier();
3828 Diag(Old->getLocation(), diag::note_previous_declaration);
3829 New->setInvalidDecl();
3830 }
3831
3832 mergeDeclAttributes(New, Old);
3833 // Warn if an already-declared variable is made a weak_import in a subsequent
3834 // declaration
3835 if (New->hasAttr<WeakImportAttr>() &&
3836 Old->getStorageClass() == SC_None &&
3837 !Old->hasAttr<WeakImportAttr>()) {
3838 Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3839 notePreviousDefinition(Old, New->getLocation());
3840 // Remove weak_import attribute on new declaration.
3841 New->dropAttr<WeakImportAttr>();
3842 }
3843
3844 if (New->hasAttr<InternalLinkageAttr>() &&
3845 !Old->hasAttr<InternalLinkageAttr>()) {
3846 Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3847 << New->getDeclName();
3848 notePreviousDefinition(Old, New->getLocation());
3849 New->dropAttr<InternalLinkageAttr>();
3850 }
3851
3852 // Merge the types.
3853 VarDecl *MostRecent = Old->getMostRecentDecl();
3854 if (MostRecent != Old) {
3855 MergeVarDeclTypes(New, MostRecent,
3856 mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3857 if (New->isInvalidDecl())
3858 return;
3859 }
3860
3861 MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3862 if (New->isInvalidDecl())
3863 return;
3864
3865 diag::kind PrevDiag;
3866 SourceLocation OldLocation;
3867 std::tie(PrevDiag, OldLocation) =
3868 getNoteDiagForInvalidRedeclaration(Old, New);
3869
3870 // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3871 if (New->getStorageClass() == SC_Static &&
3872 !New->isStaticDataMember() &&
3873 Old->hasExternalFormalLinkage()) {
3874 if (getLangOpts().MicrosoftExt) {
3875 Diag(New->getLocation(), diag::ext_static_non_static)
3876 << New->getDeclName();
3877 Diag(OldLocation, PrevDiag);
3878 } else {
3879 Diag(New->getLocation(), diag::err_static_non_static)
3880 << New->getDeclName();
3881 Diag(OldLocation, PrevDiag);
3882 return New->setInvalidDecl();
3883 }
3884 }
3885 // C99 6.2.2p4:
3886 // For an identifier declared with the storage-class specifier
3887 // extern in a scope in which a prior declaration of that
3888 // identifier is visible,23) if the prior declaration specifies
3889 // internal or external linkage, the linkage of the identifier at
3890 // the later declaration is the same as the linkage specified at
3891 // the prior declaration. If no prior declaration is visible, or
3892 // if the prior declaration specifies no linkage, then the
3893 // identifier has external linkage.
3894 if (New->hasExternalStorage() && Old->hasLinkage())
3895 /* Okay */;
3896 else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3897 !New->isStaticDataMember() &&
3898 Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3899 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3900 Diag(OldLocation, PrevDiag);
3901 return New->setInvalidDecl();
3902 }
3903
3904 // Check if extern is followed by non-extern and vice-versa.
3905 if (New->hasExternalStorage() &&
3906 !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3907 Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3908 Diag(OldLocation, PrevDiag);
3909 return New->setInvalidDecl();
3910 }
3911 if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3912 !New->hasExternalStorage()) {
3913 Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3914 Diag(OldLocation, PrevDiag);
3915 return New->setInvalidDecl();
3916 }
3917
3918 if (CheckRedeclarationModuleOwnership(New, Old))
3919 return;
3920
3921 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3922
3923 // FIXME: The test for external storage here seems wrong? We still
3924 // need to check for mismatches.
3925 if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3926 // Don't complain about out-of-line definitions of static members.
3927 !(Old->getLexicalDeclContext()->isRecord() &&
3928 !New->getLexicalDeclContext()->isRecord())) {
3929 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3930 Diag(OldLocation, PrevDiag);
3931 return New->setInvalidDecl();
3932 }
3933
3934 if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3935 if (VarDecl *Def = Old->getDefinition()) {
3936 // C++1z [dcl.fcn.spec]p4:
3937 // If the definition of a variable appears in a translation unit before
3938 // its first declaration as inline, the program is ill-formed.
3939 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3940 Diag(Def->getLocation(), diag::note_previous_definition);
3941 }
3942 }
3943
3944 // If this redeclaration makes the variable inline, we may need to add it to
3945 // UndefinedButUsed.
3946 if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3947 !Old->getDefinition() && !New->isThisDeclarationADefinition())
3948 UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3949 SourceLocation()));
3950
3951 if (New->getTLSKind() != Old->getTLSKind()) {
3952 if (!Old->getTLSKind()) {
3953 Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3954 Diag(OldLocation, PrevDiag);
3955 } else if (!New->getTLSKind()) {
3956 Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3957 Diag(OldLocation, PrevDiag);
3958 } else {
3959 // Do not allow redeclaration to change the variable between requiring
3960 // static and dynamic initialization.
3961 // FIXME: GCC allows this, but uses the TLS keyword on the first
3962 // declaration to determine the kind. Do we need to be compatible here?
3963 Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3964 << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3965 Diag(OldLocation, PrevDiag);
3966 }
3967 }
3968
3969 // C++ doesn't have tentative definitions, so go right ahead and check here.
3970 if (getLangOpts().CPlusPlus &&
3971 New->isThisDeclarationADefinition() == VarDecl::Definition) {
3972 if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3973 Old->getCanonicalDecl()->isConstexpr()) {
3974 // This definition won't be a definition any more once it's been merged.
3975 Diag(New->getLocation(),
3976 diag::warn_deprecated_redundant_constexpr_static_def);
3977 } else if (VarDecl *Def = Old->getDefinition()) {
3978 if (checkVarDeclRedefinition(Def, New))
3979 return;
3980 }
3981 }
3982
3983 if (haveIncompatibleLanguageLinkages(Old, New)) {
3984 Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3985 Diag(OldLocation, PrevDiag);
3986 New->setInvalidDecl();
3987 return;
3988 }
3989
3990 // Merge "used" flag.
3991 if (Old->getMostRecentDecl()->isUsed(false))
3992 New->setIsUsed();
3993
3994 // Keep a chain of previous declarations.
3995 New->setPreviousDecl(Old);
3996 if (NewTemplate)
3997 NewTemplate->setPreviousDecl(OldTemplate);
3998 adjustDeclContextForDeclaratorDecl(New, Old);
3999
4000 // Inherit access appropriately.
4001 New->setAccess(Old->getAccess());
4002 if (NewTemplate)
4003 NewTemplate->setAccess(New->getAccess());
4004
4005 if (Old->isInline())
4006 New->setImplicitlyInline();
4007}
4008
4009void Sema::notePreviousDefinition(const NamedDecl *Old, SourceLocation New) {
4010 SourceManager &SrcMgr = getSourceManager();
4011 auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4012 auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4013 auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4014 auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4015 auto &HSI = PP.getHeaderSearchInfo();
4016 StringRef HdrFilename =
4017 SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4018
4019 auto noteFromModuleOrInclude = [&](Module *Mod,
4020 SourceLocation IncLoc) -> bool {
4021 // Redefinition errors with modules are common with non modular mapped
4022 // headers, example: a non-modular header H in module A that also gets
4023 // included directly in a TU. Pointing twice to the same header/definition
4024 // is confusing, try to get better diagnostics when modules is on.
4025 if (IncLoc.isValid()) {
4026 if (Mod) {
4027 Diag(IncLoc, diag::note_redefinition_modules_same_file)
4028 << HdrFilename.str() << Mod->getFullModuleName();
4029 if (!Mod->DefinitionLoc.isInvalid())
4030 Diag(Mod->DefinitionLoc, diag::note_defined_here)
4031 << Mod->getFullModuleName();
4032 } else {
4033 Diag(IncLoc, diag::note_redefinition_include_same_file)
4034 << HdrFilename.str();
4035 }
4036 return true;
4037 }
4038
4039 return false;
4040 };
4041
4042 // Is it the same file and same offset? Provide more information on why
4043 // this leads to a redefinition error.
4044 bool EmittedDiag = false;
4045 if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4046 SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4047 SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4048 EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4049 EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4050
4051 // If the header has no guards, emit a note suggesting one.
4052 if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4053 Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4054
4055 if (EmittedDiag)
4056 return;
4057 }
4058
4059 // Redefinition coming from different files or couldn't do better above.
4060 if (Old->getLocation().isValid())
4061 Diag(Old->getLocation(), diag::note_previous_definition);
4062}
4063
4064/// We've just determined that \p Old and \p New both appear to be definitions
4065/// of the same variable. Either diagnose or fix the problem.
4066bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
4067 if (!hasVisibleDefinition(Old) &&
4068 (New->getFormalLinkage() == InternalLinkage ||
4069 New->isInline() ||
4070 New->getDescribedVarTemplate() ||
4071 New->getNumTemplateParameterLists() ||
4072 New->getDeclContext()->isDependentContext())) {
4073 // The previous definition is hidden, and multiple definitions are
4074 // permitted (in separate TUs). Demote this to a declaration.
4075 New->demoteThisDefinitionToDeclaration();
4076
4077 // Make the canonical definition visible.
4078 if (auto *OldTD = Old->getDescribedVarTemplate())
4079 makeMergedDefinitionVisible(OldTD);
4080 makeMergedDefinitionVisible(Old);
4081 return false;
4082 } else {
4083 Diag(New->getLocation(), diag::err_redefinition) << New;
4084 notePreviousDefinition(Old, New->getLocation());
4085 New->setInvalidDecl();
4086 return true;
4087 }
4088}
4089
4090/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4091/// no declarator (e.g. "struct foo;") is parsed.
4092Decl *
4093Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4094 RecordDecl *&AnonRecord) {
4095 return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4096 AnonRecord);
4097}
4098
4099// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4100// disambiguate entities defined in different scopes.
4101// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4102// compatibility.
4103// We will pick our mangling number depending on which version of MSVC is being
4104// targeted.
4105static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4106 return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4107 ? S->getMSCurManglingNumber()
4108 : S->getMSLastManglingNumber();
4109}
4110
4111void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4112 if (!Context.getLangOpts().CPlusPlus)
4113 return;
4114
4115 if (isa<CXXRecordDecl>(Tag->getParent())) {
4116 // If this tag is the direct child of a class, number it if
4117 // it is anonymous.
4118 if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4119 return;
4120 MangleNumberingContext &MCtx =
4121 Context.getManglingNumberContext(Tag->getParent());
4122 Context.setManglingNumber(
4123 Tag, MCtx.getManglingNumber(
4124 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4125 return;
4126 }
4127
4128 // If this tag isn't a direct child of a class, number it if it is local.
4129 Decl *ManglingContextDecl;
4130 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4131 Tag->getDeclContext(), ManglingContextDecl)) {
4132 Context.setManglingNumber(
4133 Tag, MCtx->getManglingNumber(
4134 Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4135 }
4136}
4137
4138void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4139 TypedefNameDecl *NewTD) {
4140 if (TagFromDeclSpec->isInvalidDecl())
4141 return;
4142
4143 // Do nothing if the tag already has a name for linkage purposes.
4144 if (TagFromDeclSpec->hasNameForLinkage())
4145 return;
4146
4147 // A well-formed anonymous tag must always be a TUK_Definition.
4148 assert(TagFromDeclSpec->isThisDeclarationADefinition())(static_cast <bool> (TagFromDeclSpec->isThisDeclarationADefinition
()) ? void (0) : __assert_fail ("TagFromDeclSpec->isThisDeclarationADefinition()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 4148, __extension__ __PRETTY_FUNCTION__))
;
4149
4150 // The type must match the tag exactly; no qualifiers allowed.
4151 if (!Context.hasSameType(NewTD->getUnderlyingType(),
4152 Context.getTagDeclType(TagFromDeclSpec))) {
4153 if (getLangOpts().CPlusPlus)
4154 Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4155 return;
4156 }
4157
4158 // If we've already computed linkage for the anonymous tag, then
4159 // adding a typedef name for the anonymous decl can change that
4160 // linkage, which might be a serious problem. Diagnose this as
4161 // unsupported and ignore the typedef name. TODO: we should
4162 // pursue this as a language defect and establish a formal rule
4163 // for how to handle it.
4164 if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4165 Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4166
4167 SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4168 tagLoc = getLocForEndOfToken(tagLoc);
4169
4170 llvm::SmallString<40> textToInsert;
4171 textToInsert += ' ';
4172 textToInsert += NewTD->getIdentifier()->getName();
4173 Diag(tagLoc, diag::note_typedef_changes_linkage)
4174 << FixItHint::CreateInsertion(tagLoc, textToInsert);
4175 return;
4176 }
4177
4178 // Otherwise, set this is the anon-decl typedef for the tag.
4179 TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4180}
4181
4182static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4183 switch (T) {
4184 case DeclSpec::TST_class:
4185 return 0;
4186 case DeclSpec::TST_struct:
4187 return 1;
4188 case DeclSpec::TST_interface:
4189 return 2;
4190 case DeclSpec::TST_union:
4191 return 3;
4192 case DeclSpec::TST_enum:
4193 return 4;
4194 default:
4195 llvm_unreachable("unexpected type specifier")::llvm::llvm_unreachable_internal("unexpected type specifier"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 4195)
;
4196 }
4197}
4198
4199/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4200/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4201/// parameters to cope with template friend declarations.
4202Decl *
4203Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
4204 MultiTemplateParamsArg TemplateParams,
4205 bool IsExplicitInstantiation,
4206 RecordDecl *&AnonRecord) {
4207 Decl *TagD = nullptr;
4208 TagDecl *Tag = nullptr;
4209 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4210 DS.getTypeSpecType() == DeclSpec::TST_struct ||
4211 DS.getTypeSpecType() == DeclSpec::TST_interface ||
4212 DS.getTypeSpecType() == DeclSpec::TST_union ||
4213 DS.getTypeSpecType() == DeclSpec::TST_enum) {
4214 TagD = DS.getRepAsDecl();
4215
4216 if (!TagD) // We probably had an error
4217 return nullptr;
4218
4219 // Note that the above type specs guarantee that the
4220 // type rep is a Decl, whereas in many of the others
4221 // it's a Type.
4222 if (isa<TagDecl>(TagD))
4223 Tag = cast<TagDecl>(TagD);
4224 else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4225 Tag = CTD->getTemplatedDecl();
4226 }
4227
4228 if (Tag) {
4229 handleTagNumbering(Tag, S);
4230 Tag->setFreeStanding();
4231 if (Tag->isInvalidDecl())
4232 return Tag;
4233 }
4234
4235 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4236 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4237 // or incomplete types shall not be restrict-qualified."
4238 if (TypeQuals & DeclSpec::TQ_restrict)
4239 Diag(DS.getRestrictSpecLoc(),
4240 diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4241 << DS.getSourceRange();
4242 }
4243
4244 if (DS.isInlineSpecified())
4245 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4246 << getLangOpts().CPlusPlus17;
4247
4248 if (DS.isConstexprSpecified()) {
4249 // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4250 // and definitions of functions and variables.
4251 if (Tag)
4252 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4253 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4254 else
4255 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4256 // Don't emit warnings after this error.
4257 return TagD;
4258 }
4259
4260 DiagnoseFunctionSpecifiers(DS);
4261
4262 if (DS.isFriendSpecified()) {
4263 // If we're dealing with a decl but not a TagDecl, assume that
4264 // whatever routines created it handled the friendship aspect.
4265 if (TagD && !Tag)
4266 return nullptr;
4267 return ActOnFriendTypeDecl(S, DS, TemplateParams);
4268 }
4269
4270 const CXXScopeSpec &SS = DS.getTypeSpecScope();
4271 bool IsExplicitSpecialization =
4272 !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4273 if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4274 !IsExplicitInstantiation && !IsExplicitSpecialization &&
4275 !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4276 // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4277 // nested-name-specifier unless it is an explicit instantiation
4278 // or an explicit specialization.
4279 //
4280 // FIXME: We allow class template partial specializations here too, per the
4281 // obvious intent of DR1819.
4282 //
4283 // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4284 Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4285 << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4286 return nullptr;
4287 }
4288
4289 // Track whether this decl-specifier declares anything.
4290 bool DeclaresAnything = true;
4291
4292 // Handle anonymous struct definitions.
4293 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4294 if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4295 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4296 if (getLangOpts().CPlusPlus ||
4297 Record->getDeclContext()->isRecord()) {
4298 // If CurContext is a DeclContext that can contain statements,
4299 // RecursiveASTVisitor won't visit the decls that
4300 // BuildAnonymousStructOrUnion() will put into CurContext.
4301 // Also store them here so that they can be part of the
4302 // DeclStmt that gets created in this case.
4303 // FIXME: Also return the IndirectFieldDecls created by
4304 // BuildAnonymousStructOr union, for the same reason?
4305 if (CurContext->isFunctionOrMethod())
4306 AnonRecord = Record;
4307 return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4308 Context.getPrintingPolicy());
4309 }
4310
4311 DeclaresAnything = false;
4312 }
4313 }
4314
4315 // C11 6.7.2.1p2:
4316 // A struct-declaration that does not declare an anonymous structure or
4317 // anonymous union shall contain a struct-declarator-list.
4318 //
4319 // This rule also existed in C89 and C99; the grammar for struct-declaration
4320 // did not permit a struct-declaration without a struct-declarator-list.
4321 if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4322 DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4323 // Check for Microsoft C extension: anonymous struct/union member.
4324 // Handle 2 kinds of anonymous struct/union:
4325 // struct STRUCT;
4326 // union UNION;
4327 // and
4328 // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
4329 // UNION_TYPE; <- where UNION_TYPE is a typedef union.
4330 if ((Tag && Tag->getDeclName()) ||
4331 DS.getTypeSpecType() == DeclSpec::TST_typename) {
4332 RecordDecl *Record = nullptr;
4333 if (Tag)
4334 Record = dyn_cast<RecordDecl>(Tag);
4335 else if (const RecordType *RT =
4336 DS.getRepAsType().get()->getAsStructureType())
4337 Record = RT->getDecl();
4338 else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4339 Record = UT->getDecl();
4340
4341 if (Record && getLangOpts().MicrosoftExt) {
4342 Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4343 << Record->isUnion() << DS.getSourceRange();
4344 return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4345 }
4346
4347 DeclaresAnything = false;
4348 }
4349 }
4350
4351 // Skip all the checks below if we have a type error.
4352 if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4353 (TagD && TagD->isInvalidDecl()))
4354 return TagD;
4355
4356 if (getLangOpts().CPlusPlus &&
4357 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4358 if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4359 if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4360 !Enum->getIdentifier() && !Enum->isInvalidDecl())
4361 DeclaresAnything = false;
4362
4363 if (!DS.isMissingDeclaratorOk()) {
4364 // Customize diagnostic for a typedef missing a name.
4365 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4366 Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4367 << DS.getSourceRange();
4368 else
4369 DeclaresAnything = false;
4370 }
4371
4372 if (DS.isModulePrivateSpecified() &&
4373 Tag && Tag->getDeclContext()->isFunctionOrMethod())
4374 Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4375 << Tag->getTagKind()
4376 << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4377
4378 ActOnDocumentableDecl(TagD);
4379
4380 // C 6.7/2:
4381 // A declaration [...] shall declare at least a declarator [...], a tag,
4382 // or the members of an enumeration.
4383 // C++ [dcl.dcl]p3:
4384 // [If there are no declarators], and except for the declaration of an
4385 // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4386 // names into the program, or shall redeclare a name introduced by a
4387 // previous declaration.
4388 if (!DeclaresAnything) {
4389 // In C, we allow this as a (popular) extension / bug. Don't bother
4390 // producing further diagnostics for redundant qualifiers after this.
4391 Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4392 return TagD;
4393 }
4394
4395 // C++ [dcl.stc]p1:
4396 // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4397 // init-declarator-list of the declaration shall not be empty.
4398 // C++ [dcl.fct.spec]p1:
4399 // If a cv-qualifier appears in a decl-specifier-seq, the
4400 // init-declarator-list of the declaration shall not be empty.
4401 //
4402 // Spurious qualifiers here appear to be valid in C.
4403 unsigned DiagID = diag::warn_standalone_specifier;
4404 if (getLangOpts().CPlusPlus)
4405 DiagID = diag::ext_standalone_specifier;
4406
4407 // Note that a linkage-specification sets a storage class, but
4408 // 'extern "C" struct foo;' is actually valid and not theoretically
4409 // useless.
4410 if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4411 if (SCS == DeclSpec::SCS_mutable)
4412 // Since mutable is not a viable storage class specifier in C, there is
4413 // no reason to treat it as an extension. Instead, diagnose as an error.
4414 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4415 else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4416 Diag(DS.getStorageClassSpecLoc(), DiagID)
4417 << DeclSpec::getSpecifierName(SCS);
4418 }
4419
4420 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4421 Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4422 << DeclSpec::getSpecifierName(TSCS);
4423 if (DS.getTypeQualifiers()) {
4424 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4425 Diag(DS.getConstSpecLoc(), DiagID) << "const";
4426 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4427 Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4428 // Restrict is covered above.
4429 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4430 Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4431 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4432 Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4433 }
4434
4435 // Warn about ignored type attributes, for example:
4436 // __attribute__((aligned)) struct A;
4437 // Attributes should be placed after tag to apply to type declaration.
4438 if (!DS.getAttributes().empty()) {
4439 DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4440 if (TypeSpecType == DeclSpec::TST_class ||
4441 TypeSpecType == DeclSpec::TST_struct ||
4442 TypeSpecType == DeclSpec::TST_interface ||
4443 TypeSpecType == DeclSpec::TST_union ||
4444 TypeSpecType == DeclSpec::TST_enum) {
4445 for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4446 attrs = attrs->getNext())
4447 Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4448 << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4449 }
4450 }
4451
4452 return TagD;
4453}
4454
4455/// We are trying to inject an anonymous member into the given scope;
4456/// check if there's an existing declaration that can't be overloaded.
4457///
4458/// \return true if this is a forbidden redeclaration
4459static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4460 Scope *S,
4461 DeclContext *Owner,
4462 DeclarationName Name,
4463 SourceLocation NameLoc,
4464 bool IsUnion) {
4465 LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4466 Sema::ForVisibleRedeclaration);
4467 if (!SemaRef.LookupName(R, S)) return false;
4468
4469 // Pick a representative declaration.
4470 NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4471 assert(PrevDecl && "Expected a non-null Decl")(static_cast <bool> (PrevDecl && "Expected a non-null Decl"
) ? void (0) : __assert_fail ("PrevDecl && \"Expected a non-null Decl\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 4471, __extension__ __PRETTY_FUNCTION__))
;
4472
4473 if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4474 return false;
4475
4476 SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4477 << IsUnion << Name;
4478 SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4479
4480 return true;
4481}
4482
4483/// InjectAnonymousStructOrUnionMembers - Inject the members of the
4484/// anonymous struct or union AnonRecord into the owning context Owner
4485/// and scope S. This routine will be invoked just after we realize
4486/// that an unnamed union or struct is actually an anonymous union or
4487/// struct, e.g.,
4488///
4489/// @code
4490/// union {
4491/// int i;
4492/// float f;
4493/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4494/// // f into the surrounding scope.x
4495/// @endcode
4496///
4497/// This routine is recursive, injecting the names of nested anonymous
4498/// structs/unions into the owning context and scope as well.
4499static bool
4500InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4501 RecordDecl *AnonRecord, AccessSpecifier AS,
4502 SmallVectorImpl<NamedDecl *> &Chaining) {
4503 bool Invalid = false;
4504
4505 // Look every FieldDecl and IndirectFieldDecl with a name.
4506 for (auto *D : AnonRecord->decls()) {
4507 if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4508 cast<NamedDecl>(D)->getDeclName()) {
4509 ValueDecl *VD = cast<ValueDecl>(D);
4510 if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4511 VD->getLocation(),
4512 AnonRecord->isUnion())) {
4513 // C++ [class.union]p2:
4514 // The names of the members of an anonymous union shall be
4515 // distinct from the names of any other entity in the
4516 // scope in which the anonymous union is declared.
4517 Invalid = true;
4518 } else {
4519 // C++ [class.union]p2:
4520 // For the purpose of name lookup, after the anonymous union
4521 // definition, the members of the anonymous union are
4522 // considered to have been defined in the scope in which the
4523 // anonymous union is declared.
4524 unsigned OldChainingSize = Chaining.size();
4525 if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4526 Chaining.append(IF->chain_begin(), IF->chain_end());
4527 else
4528 Chaining.push_back(VD);
4529
4530 assert(Chaining.size() >= 2)(static_cast <bool> (Chaining.size() >= 2) ? void (0
) : __assert_fail ("Chaining.size() >= 2", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 4530, __extension__ __PRETTY_FUNCTION__))
;
4531 NamedDecl **NamedChain =
4532 new (SemaRef.Context)NamedDecl*[Chaining.size()];
4533 for (unsigned i = 0; i < Chaining.size(); i++)
4534 NamedChain[i] = Chaining[i];
4535
4536 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4537 SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4538 VD->getType(), {NamedChain, Chaining.size()});
4539
4540 for (const auto *Attr : VD->attrs())
4541 IndirectField->addAttr(Attr->clone(SemaRef.Context));
4542
4543 IndirectField->setAccess(AS);
4544 IndirectField->setImplicit();
4545 SemaRef.PushOnScopeChains(IndirectField, S);
4546
4547 // That includes picking up the appropriate access specifier.
4548 if (AS != AS_none) IndirectField->setAccess(AS);
4549
4550 Chaining.resize(OldChainingSize);
4551 }
4552 }
4553 }
4554
4555 return Invalid;
4556}
4557
4558/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4559/// a VarDecl::StorageClass. Any error reporting is up to the caller:
4560/// illegal input values are mapped to SC_None.
4561static StorageClass
4562StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4563 DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4564 assert(StorageClassSpec != DeclSpec::SCS_typedef &&(static_cast <bool> (StorageClassSpec != DeclSpec::SCS_typedef
&& "Parser allowed 'typedef' as storage class VarDecl."
) ? void (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 4565, __extension__ __PRETTY_FUNCTION__))
4565 "Parser allowed 'typedef' as storage class VarDecl.")(static_cast <bool> (StorageClassSpec != DeclSpec::SCS_typedef
&& "Parser allowed 'typedef' as storage class VarDecl."
) ? void (0) : __assert_fail ("StorageClassSpec != DeclSpec::SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 4565, __extension__ __PRETTY_FUNCTION__))
;
4566 switch (StorageClassSpec) {
4567 case DeclSpec::SCS_unspecified: return SC_None;
4568 case DeclSpec::SCS_extern:
4569 if (DS.isExternInLinkageSpec())
4570 return SC_None;
4571 return SC_Extern;
4572 case DeclSpec::SCS_static: return SC_Static;
4573 case DeclSpec::SCS_auto: return SC_Auto;
4574 case DeclSpec::SCS_register: return SC_Register;
4575 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4576 // Illegal SCSs map to None: error reporting is up to the caller.
4577 case DeclSpec::SCS_mutable: // Fall through.
4578 case DeclSpec::SCS_typedef: return SC_None;
4579 }
4580 llvm_unreachable("unknown storage class specifier")::llvm::llvm_unreachable_internal("unknown storage class specifier"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 4580)
;
4581}
4582
4583static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4584 assert(Record->hasInClassInitializer())(static_cast <bool> (Record->hasInClassInitializer()
) ? void (0) : __assert_fail ("Record->hasInClassInitializer()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 4584, __extension__ __PRETTY_FUNCTION__))
;
4585
4586 for (const auto *I : Record->decls()) {
4587 const auto *FD = dyn_cast<FieldDecl>(I);
4588 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4589 FD = IFD->getAnonField();
4590 if (FD && FD->hasInClassInitializer())
4591 return FD->getLocation();
4592 }
4593
4594 llvm_unreachable("couldn't find in-class initializer")::llvm::llvm_unreachable_internal("couldn't find in-class initializer"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 4594)
;
4595}
4596
4597static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4598 SourceLocation DefaultInitLoc) {
4599 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4600 return;
4601
4602 S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4603 S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4604}
4605
4606static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4607 CXXRecordDecl *AnonUnion) {
4608 if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4609 return;
4610
4611 checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4612}
4613
4614/// BuildAnonymousStructOrUnion - Handle the declaration of an
4615/// anonymous structure or union. Anonymous unions are a C++ feature
4616/// (C++ [class.union]) and a C11 feature; anonymous structures
4617/// are a C11 feature and GNU C++ extension.
4618Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4619 AccessSpecifier AS,
4620 RecordDecl *Record,
4621 const PrintingPolicy &Policy) {
4622 DeclContext *Owner = Record->getDeclContext();
4623
4624 // Diagnose whether this anonymous struct/union is an extension.
4625 if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4626 Diag(Record->getLocation(), diag::ext_anonymous_union);
4627 else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4628 Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4629 else if (!Record->isUnion() && !getLangOpts().C11)
4630 Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4631
4632 // C and C++ require different kinds of checks for anonymous
4633 // structs/unions.
4634 bool Invalid = false;
4635 if (getLangOpts().CPlusPlus) {
4636 const char *PrevSpec = nullptr;
4637 unsigned DiagID;
4638 if (Record->isUnion()) {
4639 // C++ [class.union]p6:
4640 // Anonymous unions declared in a named namespace or in the
4641 // global namespace shall be declared static.
4642 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4643 (isa<TranslationUnitDecl>(Owner) ||
4644 (isa<NamespaceDecl>(Owner) &&
4645 cast<NamespaceDecl>(Owner)->getDeclName()))) {
4646 Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4647 << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4648
4649 // Recover by adding 'static'.
4650 DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4651 PrevSpec, DiagID, Policy);
4652 }
4653 // C++ [class.union]p6:
4654 // A storage class is not allowed in a declaration of an
4655 // anonymous union in a class scope.
4656 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4657 isa<RecordDecl>(Owner)) {
4658 Diag(DS.getStorageClassSpecLoc(),
4659 diag::err_anonymous_union_with_storage_spec)
4660 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4661
4662 // Recover by removing the storage specifier.
4663 DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4664 SourceLocation(),
4665 PrevSpec, DiagID, Context.getPrintingPolicy());
4666 }
4667 }
4668
4669 // Ignore const/volatile/restrict qualifiers.
4670 if (DS.getTypeQualifiers()) {
4671 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4672 Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4673 << Record->isUnion() << "const"
4674 << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4675 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4676 Diag(DS.getVolatileSpecLoc(),
4677 diag::ext_anonymous_struct_union_qualified)
4678 << Record->isUnion() << "volatile"
4679 << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4680 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4681 Diag(DS.getRestrictSpecLoc(),
4682 diag::ext_anonymous_struct_union_qualified)
4683 << Record->isUnion() << "restrict"
4684 << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4685 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4686 Diag(DS.getAtomicSpecLoc(),
4687 diag::ext_anonymous_struct_union_qualified)
4688 << Record->isUnion() << "_Atomic"
4689 << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4690 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4691 Diag(DS.getUnalignedSpecLoc(),
4692 diag::ext_anonymous_struct_union_qualified)
4693 << Record->isUnion() << "__unaligned"
4694 << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4695
4696 DS.ClearTypeQualifiers();
4697 }
4698
4699 // C++ [class.union]p2:
4700 // The member-specification of an anonymous union shall only
4701 // define non-static data members. [Note: nested types and
4702 // functions cannot be declared within an anonymous union. ]
4703 for (auto *Mem : Record->decls()) {
4704 if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4705 // C++ [class.union]p3:
4706 // An anonymous union shall not have private or protected
4707 // members (clause 11).
4708 assert(FD->getAccess() != AS_none)(static_cast <bool> (FD->getAccess() != AS_none) ? void
(0) : __assert_fail ("FD->getAccess() != AS_none", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 4708, __extension__ __PRETTY_FUNCTION__))
;
4709 if (FD->getAccess() != AS_public) {
4710 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4711 << Record->isUnion() << (FD->getAccess() == AS_protected);
4712 Invalid = true;
4713 }
4714
4715 // C++ [class.union]p1
4716 // An object of a class with a non-trivial constructor, a non-trivial
4717 // copy constructor, a non-trivial destructor, or a non-trivial copy
4718 // assignment operator cannot be a member of a union, nor can an
4719 // array of such objects.
4720 if (CheckNontrivialField(FD))
4721 Invalid = true;
4722 } else if (Mem->isImplicit()) {
4723 // Any implicit members are fine.
4724 } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4725 // This is a type that showed up in an
4726 // elaborated-type-specifier inside the anonymous struct or
4727 // union, but which actually declares a type outside of the
4728 // anonymous struct or union. It's okay.
4729 } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4730 if (!MemRecord->isAnonymousStructOrUnion() &&
4731 MemRecord->getDeclName()) {
4732 // Visual C++ allows type definition in anonymous struct or union.
4733 if (getLangOpts().MicrosoftExt)
4734 Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4735 << Record->isUnion();
4736 else {
4737 // This is a nested type declaration.
4738 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4739 << Record->isUnion();
4740 Invalid = true;
4741 }
4742 } else {
4743 // This is an anonymous type definition within another anonymous type.
4744 // This is a popular extension, provided by Plan9, MSVC and GCC, but
4745 // not part of standard C++.
4746 Diag(MemRecord->getLocation(),
4747 diag::ext_anonymous_record_with_anonymous_type)
4748 << Record->isUnion();
4749 }
4750 } else if (isa<AccessSpecDecl>(Mem)) {
4751 // Any access specifier is fine.
4752 } else if (isa<StaticAssertDecl>(Mem)) {
4753 // In C++1z, static_assert declarations are also fine.
4754 } else {
4755 // We have something that isn't a non-static data
4756 // member. Complain about it.
4757 unsigned DK = diag::err_anonymous_record_bad_member;
4758 if (isa<TypeDecl>(Mem))
4759 DK = diag::err_anonymous_record_with_type;
4760 else if (isa<FunctionDecl>(Mem))
4761 DK = diag::err_anonymous_record_with_function;
4762 else if (isa<VarDecl>(Mem))
4763 DK = diag::err_anonymous_record_with_static;
4764
4765 // Visual C++ allows type definition in anonymous struct or union.
4766 if (getLangOpts().MicrosoftExt &&
4767 DK == diag::err_anonymous_record_with_type)
4768 Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4769 << Record->isUnion();
4770 else {
4771 Diag(Mem->getLocation(), DK) << Record->isUnion();
4772 Invalid = true;
4773 }
4774 }
4775 }
4776
4777 // C++11 [class.union]p8 (DR1460):
4778 // At most one variant member of a union may have a
4779 // brace-or-equal-initializer.
4780 if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4781 Owner->isRecord())
4782 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4783 cast<CXXRecordDecl>(Record));
4784 }
4785
4786 if (!Record->isUnion() && !Owner->isRecord()) {
4787 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4788 << getLangOpts().CPlusPlus;
4789 Invalid = true;
4790 }
4791
4792 // Mock up a declarator.
4793 Declarator Dc(DS, DeclaratorContext::MemberContext);
4794 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4795 assert(TInfo && "couldn't build declarator info for anonymous struct/union")(static_cast <bool> (TInfo && "couldn't build declarator info for anonymous struct/union"
) ? void (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct/union\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 4795, __extension__ __PRETTY_FUNCTION__))
;
4796
4797 // Create a declaration for this anonymous struct/union.
4798 NamedDecl *Anon = nullptr;
4799 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4800 Anon = FieldDecl::Create(Context, OwningClass,
4801 DS.getLocStart(),
4802 Record->getLocation(),
4803 /*IdentifierInfo=*/nullptr,
4804 Context.getTypeDeclType(Record),
4805 TInfo,
4806 /*BitWidth=*/nullptr, /*Mutable=*/false,
4807 /*InitStyle=*/ICIS_NoInit);
4808 Anon->setAccess(AS);
4809 if (getLangOpts().CPlusPlus)
4810 FieldCollector->Add(cast<FieldDecl>(Anon));
4811 } else {
4812 DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4813 StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4814 if (SCSpec == DeclSpec::SCS_mutable) {
4815 // mutable can only appear on non-static class members, so it's always
4816 // an error here
4817 Diag(Record->getLocation(), diag::err_mutable_nonmember);
4818 Invalid = true;
4819 SC = SC_None;
4820 }
4821
4822 Anon = VarDecl::Create(Context, Owner,
4823 DS.getLocStart(),
4824 Record->getLocation(), /*IdentifierInfo=*/nullptr,
4825 Context.getTypeDeclType(Record),
4826 TInfo, SC);
4827
4828 // Default-initialize the implicit variable. This initialization will be
4829 // trivial in almost all cases, except if a union member has an in-class
4830 // initializer:
4831 // union { int n = 0; };
4832 ActOnUninitializedDecl(Anon);
4833 }
4834 Anon->setImplicit();
4835
4836 // Mark this as an anonymous struct/union type.
4837 Record->setAnonymousStructOrUnion(true);
4838
4839 // Add the anonymous struct/union object to the current
4840 // context. We'll be referencing this object when we refer to one of
4841 // its members.
4842 Owner->addDecl(Anon);
4843
4844 // Inject the members of the anonymous struct/union into the owning
4845 // context and into the identifier resolver chain for name lookup
4846 // purposes.
4847 SmallVector<NamedDecl*, 2> Chain;
4848 Chain.push_back(Anon);
4849
4850 if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4851 Invalid = true;
4852
4853 if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4854 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4855 Decl *ManglingContextDecl;
4856 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4857 NewVD->getDeclContext(), ManglingContextDecl)) {
4858 Context.setManglingNumber(
4859 NewVD, MCtx->getManglingNumber(
4860 NewVD, getMSManglingNumber(getLangOpts(), S)));
4861 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4862 }
4863 }
4864 }
4865
4866 if (Invalid)
4867 Anon->setInvalidDecl();
4868
4869 return Anon;
4870}
4871
4872/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4873/// Microsoft C anonymous structure.
4874/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4875/// Example:
4876///
4877/// struct A { int a; };
4878/// struct B { struct A; int b; };
4879///
4880/// void foo() {
4881/// B var;
4882/// var.a = 3;
4883/// }
4884///
4885Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4886 RecordDecl *Record) {
4887 assert(Record && "expected a record!")(static_cast <bool> (Record && "expected a record!"
) ? void (0) : __assert_fail ("Record && \"expected a record!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 4887, __extension__ __PRETTY_FUNCTION__))
;
4888
4889 // Mock up a declarator.
4890 Declarator Dc(DS, DeclaratorContext::TypeNameContext);
4891 TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4892 assert(TInfo && "couldn't build declarator info for anonymous struct")(static_cast <bool> (TInfo && "couldn't build declarator info for anonymous struct"
) ? void (0) : __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 4892, __extension__ __PRETTY_FUNCTION__))
;
4893
4894 auto *ParentDecl = cast<RecordDecl>(CurContext);
4895 QualType RecTy = Context.getTypeDeclType(Record);
4896
4897 // Create a declaration for this anonymous struct.
4898 NamedDecl *Anon = FieldDecl::Create(Context,
4899 ParentDecl,
4900 DS.getLocStart(),
4901 DS.getLocStart(),
4902 /*IdentifierInfo=*/nullptr,
4903 RecTy,
4904 TInfo,
4905 /*BitWidth=*/nullptr, /*Mutable=*/false,
4906 /*InitStyle=*/ICIS_NoInit);
4907 Anon->setImplicit();
4908
4909 // Add the anonymous struct object to the current context.
4910 CurContext->addDecl(Anon);
4911
4912 // Inject the members of the anonymous struct into the current
4913 // context and into the identifier resolver chain for name lookup
4914 // purposes.
4915 SmallVector<NamedDecl*, 2> Chain;
4916 Chain.push_back(Anon);
4917
4918 RecordDecl *RecordDef = Record->getDefinition();
4919 if (RequireCompleteType(Anon->getLocation(), RecTy,
4920 diag::err_field_incomplete) ||
4921 InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4922 AS_none, Chain)) {
4923 Anon->setInvalidDecl();
4924 ParentDecl->setInvalidDecl();
4925 }
4926
4927 return Anon;
4928}
4929
4930/// GetNameForDeclarator - Determine the full declaration name for the
4931/// given Declarator.
4932DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4933 return GetNameFromUnqualifiedId(D.getName());
4934}
4935
4936/// \brief Retrieves the declaration name from a parsed unqualified-id.
4937DeclarationNameInfo
4938Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4939 DeclarationNameInfo NameInfo;
4940 NameInfo.setLoc(Name.StartLocation);
4941
4942 switch (Name.getKind()) {
4943
4944 case UnqualifiedIdKind::IK_ImplicitSelfParam:
4945 case UnqualifiedIdKind::IK_Identifier:
4946 NameInfo.setName(Name.Identifier);
4947 NameInfo.setLoc(Name.StartLocation);
4948 return NameInfo;
4949
4950 case UnqualifiedIdKind::IK_DeductionGuideName: {
4951 // C++ [temp.deduct.guide]p3:
4952 // The simple-template-id shall name a class template specialization.
4953 // The template-name shall be the same identifier as the template-name
4954 // of the simple-template-id.
4955 // These together intend to imply that the template-name shall name a
4956 // class template.
4957 // FIXME: template<typename T> struct X {};
4958 // template<typename T> using Y = X<T>;
4959 // Y(int) -> Y<int>;
4960 // satisfies these rules but does not name a class template.
4961 TemplateName TN = Name.TemplateName.get().get();
4962 auto *Template = TN.getAsTemplateDecl();
4963 if (!Template || !isa<ClassTemplateDecl>(Template)) {
4964 Diag(Name.StartLocation,
4965 diag::err_deduction_guide_name_not_class_template)
4966 << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4967 if (Template)
4968 Diag(Template->getLocation(), diag::note_template_decl_here);
4969 return DeclarationNameInfo();
4970 }
4971
4972 NameInfo.setName(
4973 Context.DeclarationNames.getCXXDeductionGuideName(Template));
4974 NameInfo.setLoc(Name.StartLocation);
4975 return NameInfo;
4976 }
4977
4978 case UnqualifiedIdKind::IK_OperatorFunctionId:
4979 NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4980 Name.OperatorFunctionId.Operator));
4981 NameInfo.setLoc(Name.StartLocation);
4982 NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4983 = Name.OperatorFunctionId.SymbolLocations[0];
4984 NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4985 = Name.EndLocation.getRawEncoding();
4986 return NameInfo;
4987
4988 case UnqualifiedIdKind::IK_LiteralOperatorId:
4989 NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4990 Name.Identifier));
4991 NameInfo.setLoc(Name.StartLocation);
4992 NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4993 return NameInfo;
4994
4995 case UnqualifiedIdKind::IK_ConversionFunctionId: {
4996 TypeSourceInfo *TInfo;
4997 QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4998 if (Ty.isNull())
4999 return DeclarationNameInfo();
5000 NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5001 Context.getCanonicalType(Ty)));
5002 NameInfo.setLoc(Name.StartLocation);
5003 NameInfo.setNamedTypeInfo(TInfo);
5004 return NameInfo;
5005 }
5006
5007 case UnqualifiedIdKind::IK_ConstructorName: {
5008 TypeSourceInfo *TInfo;
5009 QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5010 if (Ty.isNull())
5011 return DeclarationNameInfo();
5012 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5013 Context.getCanonicalType(Ty)));
5014 NameInfo.setLoc(Name.StartLocation);
5015 NameInfo.setNamedTypeInfo(TInfo);
5016 return NameInfo;
5017 }
5018
5019 case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5020 // In well-formed code, we can only have a constructor
5021 // template-id that refers to the current context, so go there
5022 // to find the actual type being constructed.
5023 CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5024 if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5025 return DeclarationNameInfo();
5026
5027 // Determine the type of the class being constructed.
5028 QualType CurClassType = Context.getTypeDeclType(CurClass);
5029
5030 // FIXME: Check two things: that the template-id names the same type as
5031 // CurClassType, and that the template-id does not occur when the name
5032 // was qualified.
5033
5034 NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5035 Context.getCanonicalType(CurClassType)));
5036 NameInfo.setLoc(Name.StartLocation);
5037 // FIXME: should we retrieve TypeSourceInfo?
5038 NameInfo.setNamedTypeInfo(nullptr);
5039 return NameInfo;
5040 }
5041
5042 case UnqualifiedIdKind::IK_DestructorName: {
5043 TypeSourceInfo *TInfo;
5044 QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5045 if (Ty.isNull())
5046 return DeclarationNameInfo();
5047 NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5048 Context.getCanonicalType(Ty)));
5049 NameInfo.setLoc(Name.StartLocation);
5050 NameInfo.setNamedTypeInfo(TInfo);
5051 return NameInfo;
5052 }
5053
5054 case UnqualifiedIdKind::IK_TemplateId: {
5055 TemplateName TName = Name.TemplateId->Template.get();
5056 SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5057 return Context.getNameForTemplate(TName, TNameLoc);
5058 }
5059
5060 } // switch (Name.getKind())
5061
5062 llvm_unreachable("Unknown name kind")::llvm::llvm_unreachable_internal("Unknown name kind", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 5062)
;
5063}
5064
5065static QualType getCoreType(QualType Ty) {
5066 do {
5067 if (Ty->isPointerType() || Ty->isReferenceType())
5068 Ty = Ty->getPointeeType();
5069 else if (Ty->isArrayType())
5070 Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5071 else
5072 return Ty.withoutLocalFastQualifiers();
5073 } while (true);
5074}
5075
5076/// hasSimilarParameters - Determine whether the C++ functions Declaration
5077/// and Definition have "nearly" matching parameters. This heuristic is
5078/// used to improve diagnostics in the case where an out-of-line function
5079/// definition doesn't match any declaration within the class or namespace.
5080/// Also sets Params to the list of indices to the parameters that differ
5081/// between the declaration and the definition. If hasSimilarParameters
5082/// returns true and Params is empty, then all of the parameters match.
5083static bool hasSimilarParameters(ASTContext &Context,
5084 FunctionDecl *Declaration,
5085 FunctionDecl *Definition,
5086 SmallVectorImpl<unsigned> &Params) {
5087 Params.clear();
5088 if (Declaration->param_size() != Definition->param_size())
5089 return false;
5090 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5091 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5092 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5093
5094 // The parameter types are identical
5095 if (Context.hasSameType(DefParamTy, DeclParamTy))
5096 continue;
5097
5098 QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5099 QualType DefParamBaseTy = getCoreType(DefParamTy);
5100 const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5101 const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5102
5103 if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5104 (DeclTyName && DeclTyName == DefTyName))
5105 Params.push_back(Idx);
5106 else // The two parameters aren't even close
5107 return false;
5108 }
5109
5110 return true;
5111}
5112
5113/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5114/// declarator needs to be rebuilt in the current instantiation.
5115/// Any bits of declarator which appear before the name are valid for
5116/// consideration here. That's specifically the type in the decl spec
5117/// and the base type in any member-pointer chunks.
5118static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
5119 DeclarationName Name) {
5120 // The types we specifically need to rebuild are:
5121 // - typenames, typeofs, and decltypes
5122 // - types which will become injected class names
5123 // Of course, we also need to rebuild any type referencing such a
5124 // type. It's safest to just say "dependent", but we call out a
5125 // few cases here.
5126
5127 DeclSpec &DS = D.getMutableDeclSpec();
5128 switch (DS.getTypeSpecType()) {
5129 case DeclSpec::TST_typename:
5130 case DeclSpec::TST_typeofType:
5131 case DeclSpec::TST_underlyingType:
5132 case DeclSpec::TST_atomic: {
5133 // Grab the type from the parser.
5134 TypeSourceInfo *TSI = nullptr;
5135 QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5136 if (T.isNull() || !T->isDependentType()) break;
5137
5138 // Make sure there's a type source info. This isn't really much
5139 // of a waste; most dependent types should have type source info
5140 // attached already.
5141 if (!TSI)
5142 TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
5143
5144 // Rebuild the type in the current instantiation.
5145 TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5146 if (!TSI) return true;
5147
5148 // Store the new type back in the decl spec.
5149 ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5150 DS.UpdateTypeRep(LocType);
5151 break;
5152 }
5153
5154 case DeclSpec::TST_decltype:
5155 case DeclSpec::TST_typeofExpr: {
5156 Expr *E = DS.getRepAsExpr();
5157 ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5158 if (Result.isInvalid()) return true;
5159 DS.UpdateExprRep(Result.get());
5160 break;
5161 }
5162
5163 default:
5164 // Nothing to do for these decl specs.
5165 break;
5166 }
5167
5168 // It doesn't matter what order we do this in.
5169 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5170 DeclaratorChunk &Chunk = D.getTypeObject(I);
5171
5172 // The only type information in the declarator which can come
5173 // before the declaration name is the base type of a member
5174 // pointer.
5175 if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5176 continue;
5177
5178 // Rebuild the scope specifier in-place.
5179 CXXScopeSpec &SS = Chunk.Mem.Scope();
5180 if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5181 return true;
5182 }
5183
5184 return false;
5185}
5186
5187Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
5188 D.setFunctionDefinitionKind(FDK_Declaration);
5189 Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5190
5191 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5192 Dcl && Dcl->getDeclContext()->isFileContext())
5193 Dcl->setTopLevelDeclInObjCContainer();
5194
5195 if (getLangOpts().OpenCL)
5196 setCurrentOpenCLExtensionForDecl(Dcl);
5197
5198 return Dcl;
5199}
5200
5201/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5202/// If T is the name of a class, then each of the following shall have a
5203/// name different from T:
5204/// - every static data member of class T;
5205/// - every member function of class T
5206/// - every member of class T that is itself a type;
5207/// \returns true if the declaration name violates these rules.
5208bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5209 DeclarationNameInfo NameInfo) {
5210 DeclarationName Name = NameInfo.getName();
5211
5212 CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5213 while (Record && Record->isAnonymousStructOrUnion())
5214 Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5215 if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5216 Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5217 return true;
5218 }
5219
5220 return false;
5221}
5222
5223/// \brief Diagnose a declaration whose declarator-id has the given
5224/// nested-name-specifier.
5225///
5226/// \param SS The nested-name-specifier of the declarator-id.
5227///
5228/// \param DC The declaration context to which the nested-name-specifier
5229/// resolves.
5230///
5231/// \param Name The name of the entity being declared.
5232///
5233/// \param Loc The location of the name of the entity being declared.
5234///
5235/// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5236/// we're declaring an explicit / partial specialization / instantiation.
5237///
5238/// \returns true if we cannot safely recover from this error, false otherwise.
5239bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
5240 DeclarationName Name,
5241 SourceLocation Loc, bool IsTemplateId) {
5242 DeclContext *Cur = CurContext;
5243 while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5244 Cur = Cur->getParent();
5245
5246 // If the user provided a superfluous scope specifier that refers back to the
5247 // class in which the entity is already declared, diagnose and ignore it.
5248 //
5249 // class X {
5250 // void X::f();
5251 // };
5252 //
5253 // Note, it was once ill-formed to give redundant qualification in all
5254 // contexts, but that rule was removed by DR482.
5255 if (Cur->Equals(DC)) {
5256 if (Cur->isRecord()) {
5257 Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5258 : diag::err_member_extra_qualification)
5259 << Name << FixItHint::CreateRemoval(SS.getRange());
5260 SS.clear();
5261 } else {
5262 Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5263 }
5264 return false;
5265 }
5266
5267 // Check whether the qualifying scope encloses the scope of the original
5268 // declaration. For a template-id, we perform the checks in
5269 // CheckTemplateSpecializationScope.
5270 if (!Cur->Encloses(DC) && !IsTemplateId) {
5271 if (Cur->isRecord())
5272 Diag(Loc, diag::err_member_qualification)
5273 << Name << SS.getRange();
5274 else if (isa<TranslationUnitDecl>(DC))
5275 Diag(Loc, diag::err_invalid_declarator_global_scope)
5276 << Name << SS.getRange();
5277 else if (isa<FunctionDecl>(Cur))
5278 Diag(Loc, diag::err_invalid_declarator_in_function)
5279 << Name << SS.getRange();
5280 else if (isa<BlockDecl>(Cur))
5281 Diag(Loc, diag::err_invalid_declarator_in_block)
5282 << Name << SS.getRange();
5283 else
5284 Diag(Loc, diag::err_invalid_declarator_scope)
5285 << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5286
5287 return true;
5288 }
5289
5290 if (Cur->isRecord()) {
5291 // Cannot qualify members within a class.
5292 Diag(Loc, diag::err_member_qualification)
5293 << Name << SS.getRange();
5294 SS.clear();
5295
5296 // C++ constructors and destructors with incorrect scopes can break
5297 // our AST invariants by having the wrong underlying types. If
5298 // that's the case, then drop this declaration entirely.
5299 if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5300 Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5301 !Context.hasSameType(Name.getCXXNameType(),
5302 Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5303 return true;
5304
5305 return false;
5306 }
5307
5308 // C++11 [dcl.meaning]p1:
5309 // [...] "The nested-name-specifier of the qualified declarator-id shall
5310 // not begin with a decltype-specifer"
5311 NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5312 while (SpecLoc.getPrefix())
5313 SpecLoc = SpecLoc.getPrefix();
5314 if (dyn_cast_or_null<DecltypeType>(
5315 SpecLoc.getNestedNameSpecifier()->getAsType()))
5316 Diag(Loc, diag::err_decltype_in_declarator)
5317 << SpecLoc.getTypeLoc().getSourceRange();
5318
5319 return false;
5320}
5321
5322NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5323 MultiTemplateParamsArg TemplateParamLists) {
5324 // TODO: consider using NameInfo for diagnostic.
5325 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5326 DeclarationName Name = NameInfo.getName();
5327
5328 // All of these full declarators require an identifier. If it doesn't have
5329 // one, the ParsedFreeStandingDeclSpec action should be used.
5330 if (D.isDecompositionDeclarator()) {
5331 return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5332 } else if (!Name) {
5333 if (!D.isInvalidType()) // Reject this if we think it is valid.
5334 Diag(D.getDeclSpec().getLocStart(),
5335 diag::err_declarator_need_ident)
5336 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5337 return nullptr;
5338 } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5339 return nullptr;
5340
5341 // The scope passed in may not be a decl scope. Zip up the scope tree until
5342 // we find one that is.
5343 while ((S->getFlags() & Scope::DeclScope) == 0 ||
5344 (S->getFlags() & Scope::TemplateParamScope) != 0)
5345 S = S->getParent();
5346
5347 DeclContext *DC = CurContext;
5348 if (D.getCXXScopeSpec().isInvalid())
5349 D.setInvalidType();
5350 else if (D.getCXXScopeSpec().isSet()) {
5351 if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5352 UPPC_DeclarationQualifier))
5353 return nullptr;
5354
5355 bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5356 DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5357 if (!DC || isa<EnumDecl>(DC)) {
5358 // If we could not compute the declaration context, it's because the
5359 // declaration context is dependent but does not refer to a class,
5360 // class template, or class template partial specialization. Complain
5361 // and return early, to avoid the coming semantic disaster.
5362 Diag(D.getIdentifierLoc(),
5363 diag::err_template_qualified_declarator_no_match)
5364 << D.getCXXScopeSpec().getScopeRep()
5365 << D.getCXXScopeSpec().getRange();
5366 return nullptr;
5367 }
5368 bool IsDependentContext = DC->isDependentContext();
5369
5370 if (!IsDependentContext &&
5371 RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5372 return nullptr;
5373
5374 // If a class is incomplete, do not parse entities inside it.
5375 if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5376 Diag(D.getIdentifierLoc(),
5377 diag::err_member_def_undefined_record)
5378 << Name << DC << D.getCXXScopeSpec().getRange();
5379 return nullptr;
5380 }
5381 if (!D.getDeclSpec().isFriendSpecified()) {
5382 if (diagnoseQualifiedDeclaration(
5383 D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
5384 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5385 if (DC->isRecord())
5386 return nullptr;
5387
5388 D.setInvalidType();
5389 }
5390 }
5391
5392 // Check whether we need to rebuild the type of the given
5393 // declaration in the current instantiation.
5394 if (EnteringContext && IsDependentContext &&
5395 TemplateParamLists.size() != 0) {
5396 ContextRAII SavedContext(*this, DC);
5397 if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5398 D.setInvalidType();
5399 }
5400 }
5401
5402 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5403 QualType R = TInfo->getType();
5404
5405 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5406 UPPC_DeclarationType))
5407 D.setInvalidType();
5408
5409 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5410 forRedeclarationInCurContext());
5411
5412 // See if this is a redefinition of a variable in the same scope.
5413 if (!D.getCXXScopeSpec().isSet()) {
5414 bool IsLinkageLookup = false;
5415 bool CreateBuiltins = false;
5416
5417 // If the declaration we're planning to build will be a function
5418 // or object with linkage, then look for another declaration with
5419 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5420 //
5421 // If the declaration we're planning to build will be declared with
5422 // external linkage in the translation unit, create any builtin with
5423 // the same name.
5424 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5425 /* Do nothing*/;
5426 else if (CurContext->isFunctionOrMethod() &&
5427 (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5428 R->isFunctionType())) {
5429 IsLinkageLookup = true;
5430 CreateBuiltins =
5431 CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5432 } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5433 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5434 CreateBuiltins = true;
5435
5436 if (IsLinkageLookup) {
5437 Previous.clear(LookupRedeclarationWithLinkage);
5438 Previous.setRedeclarationKind(ForExternalRedeclaration);
5439 }
5440
5441 LookupName(Previous, S, CreateBuiltins);
5442 } else { // Something like "int foo::x;"
5443 LookupQualifiedName(Previous, DC);
5444
5445 // C++ [dcl.meaning]p1:
5446 // When the declarator-id is qualified, the declaration shall refer to a
5447 // previously declared member of the class or namespace to which the
5448 // qualifier refers (or, in the case of a namespace, of an element of the
5449 // inline namespace set of that namespace (7.3.1)) or to a specialization
5450 // thereof; [...]
5451 //
5452 // Note that we already checked the context above, and that we do not have
5453 // enough information to make sure that Previous contains the declaration
5454 // we want to match. For example, given:
5455 //
5456 // class X {
5457 // void f();
5458 // void f(float);
5459 // };
5460 //
5461 // void X::f(int) { } // ill-formed
5462 //
5463 // In this case, Previous will point to the overload set
5464 // containing the two f's declared in X, but neither of them
5465 // matches.
5466
5467 // C++ [dcl.meaning]p1:
5468 // [...] the member shall not merely have been introduced by a
5469 // using-declaration in the scope of the class or namespace nominated by
5470 // the nested-name-specifier of the declarator-id.
5471 RemoveUsingDecls(Previous);
5472 }
5473
5474 if (Previous.isSingleResult() &&
5475 Previous.getFoundDecl()->isTemplateParameter()) {
5476 // Maybe we will complain about the shadowed template parameter.
5477 if (!D.isInvalidType())
5478 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5479 Previous.getFoundDecl());
5480
5481 // Just pretend that we didn't see the previous declaration.
5482 Previous.clear();
5483 }
5484
5485 if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5486 // Forget that the previous declaration is the injected-class-name.
5487 Previous.clear();
5488
5489 // In C++, the previous declaration we find might be a tag type
5490 // (class or enum). In this case, the new declaration will hide the
5491 // tag type. Note that this applies to functions, function templates, and
5492 // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5493 if (Previous.isSingleTagDecl() &&
5494 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5495 (TemplateParamLists.size() == 0 || R->isFunctionType()))
5496 Previous.clear();
5497
5498 // Check that there are no default arguments other than in the parameters
5499 // of a function declaration (C++ only).
5500 if (getLangOpts().CPlusPlus)
5501 CheckExtraCXXDefaultArguments(D);
5502
5503 NamedDecl *New;
5504
5505 bool AddToScope = true;
5506 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5507 if (TemplateParamLists.size()) {
5508 Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5509 return nullptr;
5510 }
5511
5512 New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5513 } else if (R->isFunctionType()) {
5514 New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5515 TemplateParamLists,
5516 AddToScope);
5517 } else {
5518 New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5519 AddToScope);
5520 }
5521
5522 if (!New)
5523 return nullptr;
5524
5525 // If this has an identifier and is not a function template specialization,
5526 // add it to the scope stack.
5527 if (New->getDeclName() && AddToScope) {
5528 // Only make a locally-scoped extern declaration visible if it is the first
5529 // declaration of this entity. Qualified lookup for such an entity should
5530 // only find this declaration if there is no visible declaration of it.
5531 bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5532 PushOnScopeChains(New, S, AddToContext);
5533 if (!AddToContext)
5534 CurContext->addHiddenDecl(New);
5535 }
5536
5537 if (isInOpenMPDeclareTargetContext())
5538 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5539
5540 return New;
5541}
5542
5543/// Helper method to turn variable array types into constant array
5544/// types in certain situations which would otherwise be errors (for
5545/// GCC compatibility).
5546static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5547 ASTContext &Context,
5548 bool &SizeIsNegative,
5549 llvm::APSInt &Oversized) {
5550 // This method tries to turn a variable array into a constant
5551 // array even when the size isn't an ICE. This is necessary
5552 // for compatibility with code that depends on gcc's buggy
5553 // constant expression folding, like struct {char x[(int)(char*)2];}
5554 SizeIsNegative = false;
5555 Oversized = 0;
5556
5557 if (T->isDependentType())
5558 return QualType();
5559
5560 QualifierCollector Qs;
5561 const Type *Ty = Qs.strip(T);
5562
5563 if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5564 QualType Pointee = PTy->getPointeeType();
5565 QualType FixedType =
5566 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5567 Oversized);
5568 if (FixedType.isNull()) return FixedType;
5569 FixedType = Context.getPointerType(FixedType);
5570 return Qs.apply(Context, FixedType);
5571 }
5572 if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5573 QualType Inner = PTy->getInnerType();
5574 QualType FixedType =
5575 TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5576 Oversized);
5577 if (FixedType.isNull()) return FixedType;
5578 FixedType = Context.getParenType(FixedType);
5579 return Qs.apply(Context, FixedType);
5580 }
5581
5582 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5583 if (!VLATy)
5584 return QualType();
5585 // FIXME: We should probably handle this case
5586 if (VLATy->getElementType()->isVariablyModifiedType())
5587 return QualType();
5588
5589 llvm::APSInt Res;
5590 if (!VLATy->getSizeExpr() ||
5591 !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5592 return QualType();
5593
5594 // Check whether the array size is negative.
5595 if (Res.isSigned() && Res.isNegative()) {
5596 SizeIsNegative = true;
5597 return QualType();
5598 }
5599
5600 // Check whether the array is too large to be addressed.
5601 unsigned ActiveSizeBits
5602 = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5603 Res);
5604 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5605 Oversized = Res;
5606 return QualType();
5607 }
5608
5609 return Context.getConstantArrayType(VLATy->getElementType(),
5610 Res, ArrayType::Normal, 0);
5611}
5612
5613static void
5614FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5615 SrcTL = SrcTL.getUnqualifiedLoc();
5616 DstTL = DstTL.getUnqualifiedLoc();
5617 if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5618 PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5619 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5620 DstPTL.getPointeeLoc());
5621 DstPTL.setStarLoc(SrcPTL.getStarLoc());
5622 return;
5623 }
5624 if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5625 ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5626 FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5627 DstPTL.getInnerLoc());
5628 DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5629 DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5630 return;
5631 }
5632 ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5633 ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5634 TypeLoc SrcElemTL = SrcATL.getElementLoc();
5635 TypeLoc DstElemTL = DstATL.getElementLoc();
5636 DstElemTL.initializeFullCopy(SrcElemTL);
5637 DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5638 DstATL.setSizeExpr(SrcATL.getSizeExpr());
5639 DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5640}
5641
5642/// Helper method to turn variable array types into constant array
5643/// types in certain situations which would otherwise be errors (for
5644/// GCC compatibility).
5645static TypeSourceInfo*
5646TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5647 ASTContext &Context,
5648 bool &SizeIsNegative,
5649 llvm::APSInt &Oversized) {
5650 QualType FixedTy
5651 = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5652 SizeIsNegative, Oversized);
5653 if (FixedTy.isNull())
5654 return nullptr;
5655 TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5656 FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5657 FixedTInfo->getTypeLoc());
5658 return FixedTInfo;
5659}
5660
5661/// \brief Register the given locally-scoped extern "C" declaration so
5662/// that it can be found later for redeclarations. We include any extern "C"
5663/// declaration that is not visible in the translation unit here, not just
5664/// function-scope declarations.
5665void
5666Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5667 if (!getLangOpts().CPlusPlus &&
5668 ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5669 // Don't need to track declarations in the TU in C.
5670 return;
5671
5672 // Note that we have a locally-scoped external with this name.
5673 Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5674}
5675
5676NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5677 // FIXME: We can have multiple results via __attribute__((overloadable)).
5678 auto Result = Context.getExternCContextDecl()->lookup(Name);
5679 return Result.empty() ? nullptr : *Result.begin();
5680}
5681
5682/// \brief Diagnose function specifiers on a declaration of an identifier that
5683/// does not identify a function.
5684void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5685 // FIXME: We should probably indicate the identifier in question to avoid
5686 // confusion for constructs like "virtual int a(), b;"
5687 if (DS.isVirtualSpecified())
5688 Diag(DS.getVirtualSpecLoc(),
5689 diag::err_virtual_non_function);
5690
5691 if (DS.isExplicitSpecified())
5692 Diag(DS.getExplicitSpecLoc(),
5693 diag::err_explicit_non_function);
5694
5695 if (DS.isNoreturnSpecified())
5696 Diag(DS.getNoreturnSpecLoc(),
5697 diag::err_noreturn_non_function);
5698}
5699
5700NamedDecl*
5701Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5702 TypeSourceInfo *TInfo, LookupResult &Previous) {
5703 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5704 if (D.getCXXScopeSpec().isSet()) {
5705 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5706 << D.getCXXScopeSpec().getRange();
5707 D.setInvalidType();
5708 // Pretend we didn't see the scope specifier.
5709 DC = CurContext;
5710 Previous.clear();
5711 }
5712
5713 DiagnoseFunctionSpecifiers(D.getDeclSpec());
5714
5715 if (D.getDeclSpec().isInlineSpecified())
5716 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5717 << getLangOpts().CPlusPlus17;
5718 if (D.getDeclSpec().isConstexprSpecified())
5719 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5720 << 1;
5721
5722 if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5723 if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5724 Diag(D.getName().StartLocation,
5725 diag::err_deduction_guide_invalid_specifier)
5726 << "typedef";
5727 else
5728 Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5729 << D.getName().getSourceRange();
5730 return nullptr;
5731 }
5732
5733 TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5734 if (!NewTD) return nullptr;
5735
5736 // Handle attributes prior to checking for duplicates in MergeVarDecl
5737 ProcessDeclAttributes(S, NewTD, D);
5738
5739 CheckTypedefForVariablyModifiedType(S, NewTD);
5740
5741 bool Redeclaration = D.isRedeclaration();
5742 NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5743 D.setRedeclaration(Redeclaration);
5744 return ND;
5745}
5746
5747void
5748Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5749 // C99 6.7.7p2: If a typedef name specifies a variably modified type
5750 // then it shall have block scope.
5751 // Note that variably modified types must be fixed before merging the decl so
5752 // that redeclarations will match.
5753 TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5754 QualType T = TInfo->getType();
5755 if (T->isVariablyModifiedType()) {
5756 setFunctionHasBranchProtectedScope();
5757
5758 if (S->getFnParent() == nullptr) {
5759 bool SizeIsNegative;
5760 llvm::APSInt Oversized;
5761 TypeSourceInfo *FixedTInfo =
5762 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5763 SizeIsNegative,
5764 Oversized);
5765 if (FixedTInfo) {
5766 Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5767 NewTD->setTypeSourceInfo(FixedTInfo);
5768 } else {
5769 if (SizeIsNegative)
5770 Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5771 else if (T->isVariableArrayType())
5772 Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5773 else if (Oversized.getBoolValue())
5774 Diag(NewTD->getLocation(), diag::err_array_too_large)
5775 << Oversized.toString(10);
5776 else
5777 Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5778 NewTD->setInvalidDecl();
5779 }
5780 }
5781 }
5782}
5783
5784/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5785/// declares a typedef-name, either using the 'typedef' type specifier or via
5786/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5787NamedDecl*
5788Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5789 LookupResult &Previous, bool &Redeclaration) {
5790
5791 // Find the shadowed declaration before filtering for scope.
5792 NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
5793
5794 // Merge the decl with the existing one if appropriate. If the decl is
5795 // in an outer scope, it isn't the same thing.
5796 FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5797 /*AllowInlineNamespace*/false);
5798 filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5799 if (!Previous.empty()) {
5800 Redeclaration = true;
5801 MergeTypedefNameDecl(S, NewTD, Previous);
5802 }
5803
5804 if (ShadowedDecl && !Redeclaration)
5805 CheckShadow(NewTD, ShadowedDecl, Previous);
5806
5807 // If this is the C FILE type, notify the AST context.
5808 if (IdentifierInfo *II = NewTD->getIdentifier())
5809 if (!NewTD->isInvalidDecl() &&
5810 NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5811 if (II->isStr("FILE"))
5812 Context.setFILEDecl(NewTD);
5813 else if (II->isStr("jmp_buf"))
5814 Context.setjmp_bufDecl(NewTD);
5815 else if (II->isStr("sigjmp_buf"))
5816 Context.setsigjmp_bufDecl(NewTD);
5817 else if (II->isStr("ucontext_t"))
5818 Context.setucontext_tDecl(NewTD);
5819 }
5820
5821 return NewTD;
5822}
5823
5824/// \brief Determines whether the given declaration is an out-of-scope
5825/// previous declaration.
5826///
5827/// This routine should be invoked when name lookup has found a
5828/// previous declaration (PrevDecl) that is not in the scope where a
5829/// new declaration by the same name is being introduced. If the new
5830/// declaration occurs in a local scope, previous declarations with
5831/// linkage may still be considered previous declarations (C99
5832/// 6.2.2p4-5, C++ [basic.link]p6).
5833///
5834/// \param PrevDecl the previous declaration found by name
5835/// lookup
5836///
5837/// \param DC the context in which the new declaration is being
5838/// declared.
5839///
5840/// \returns true if PrevDecl is an out-of-scope previous declaration
5841/// for a new delcaration with the same name.
5842static bool
5843isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5844 ASTContext &Context) {
5845 if (!PrevDecl)
5846 return false;
5847
5848 if (!PrevDecl->hasLinkage())
5849 return false;
5850
5851 if (Context.getLangOpts().CPlusPlus) {
5852 // C++ [basic.link]p6:
5853 // If there is a visible declaration of an entity with linkage
5854 // having the same name and type, ignoring entities declared
5855 // outside the innermost enclosing namespace scope, the block
5856 // scope declaration declares that same entity and receives the
5857 // linkage of the previous declaration.
5858 DeclContext *OuterContext = DC->getRedeclContext();
5859 if (!OuterContext->isFunctionOrMethod())
5860 // This rule only applies to block-scope declarations.
5861 return false;
5862
5863 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5864 if (PrevOuterContext->isRecord())
5865 // We found a member function: ignore it.
5866 return false;
5867
5868 // Find the innermost enclosing namespace for the new and
5869 // previous declarations.
5870 OuterContext = OuterContext->getEnclosingNamespaceContext();
5871 PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5872
5873 // The previous declaration is in a different namespace, so it
5874 // isn't the same function.
5875 if (!OuterContext->Equals(PrevOuterContext))
5876 return false;
5877 }
5878
5879 return true;
5880}
5881
5882static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5883 CXXScopeSpec &SS = D.getCXXScopeSpec();
5884 if (!SS.isSet()) return;
5885 DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5886}
5887
5888bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5889 QualType type = decl->getType();
5890 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5891 if (lifetime == Qualifiers::OCL_Autoreleasing) {
5892 // Various kinds of declaration aren't allowed to be __autoreleasing.
5893 unsigned kind = -1U;
5894 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5895 if (var->hasAttr<BlocksAttr>())
5896 kind = 0; // __block
5897 else if (!var->hasLocalStorage())
5898 kind = 1; // global
5899 } else if (isa<ObjCIvarDecl>(decl)) {
5900 kind = 3; // ivar
5901 } else if (isa<FieldDecl>(decl)) {
5902 kind = 2; // field
5903 }
5904
5905 if (kind != -1U) {
5906 Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5907 << kind;
5908 }
5909 } else if (lifetime == Qualifiers::OCL_None) {
5910 // Try to infer lifetime.
5911 if (!type->isObjCLifetimeType())
5912 return false;
5913
5914 lifetime = type->getObjCARCImplicitLifetime();
5915 type = Context.getLifetimeQualifiedType(type, lifetime);
5916 decl->setType(type);
5917 }
5918
5919 if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5920 // Thread-local variables cannot have lifetime.
5921 if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5922 var->getTLSKind()) {
5923 Diag(var->getLocation(), diag::err_arc_thread_ownership)
5924 << var->getType();
5925 return true;
5926 }
5927 }
5928
5929 return false;
5930}
5931
5932static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5933 // Ensure that an auto decl is deduced otherwise the checks below might cache
5934 // the wrong linkage.
5935 assert(S.ParsingInitForAutoVars.count(&ND) == 0)(static_cast <bool> (S.ParsingInitForAutoVars.count(&
ND) == 0) ? void (0) : __assert_fail ("S.ParsingInitForAutoVars.count(&ND) == 0"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 5935, __extension__ __PRETTY_FUNCTION__))
;
5936
5937 // 'weak' only applies to declarations with external linkage.
5938 if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5939 if (!ND.isExternallyVisible()) {
5940 S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5941 ND.dropAttr<WeakAttr>();
5942 }
5943 }
5944 if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5945 if (ND.isExternallyVisible()) {
5946 S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5947 ND.dropAttr<WeakRefAttr>();
5948 ND.dropAttr<AliasAttr>();
5949 }
5950 }
5951
5952 if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5953 if (VD->hasInit()) {
5954 if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5955 assert(VD->isThisDeclarationADefinition() &&(static_cast <bool> (VD->isThisDeclarationADefinition
() && !VD->isExternallyVisible() && "Broken AliasAttr handled late!"
) ? void (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 5956, __extension__ __PRETTY_FUNCTION__))
5956 !VD->isExternallyVisible() && "Broken AliasAttr handled late!")(static_cast <bool> (VD->isThisDeclarationADefinition
() && !VD->isExternallyVisible() && "Broken AliasAttr handled late!"
) ? void (0) : __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 5956, __extension__ __PRETTY_FUNCTION__))
;
5957 S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5958 VD->dropAttr<AliasAttr>();
5959 }
5960 }
5961 }
5962
5963 // 'selectany' only applies to externally visible variable declarations.
5964 // It does not apply to functions.
5965 if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5966 if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5967 S.Diag(Attr->getLocation(),
5968 diag::err_attribute_selectany_non_extern_data);
5969 ND.dropAttr<SelectAnyAttr>();
5970 }
5971 }
5972
5973 if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5974 // dll attributes require external linkage. Static locals may have external
5975 // linkage but still cannot be explicitly imported or exported.
5976 auto *VD = dyn_cast<VarDecl>(&ND);
5977 if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5978 S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5979 << &ND << Attr;
5980 ND.setInvalidDecl();
5981 }
5982 }
5983
5984 // Virtual functions cannot be marked as 'notail'.
5985 if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5986 if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5987 if (MD->isVirtual()) {
5988 S.Diag(ND.getLocation(),
5989 diag::err_invalid_attribute_on_virtual_function)
5990 << Attr;
5991 ND.dropAttr<NotTailCalledAttr>();
5992 }
5993}
5994
5995static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5996 NamedDecl *NewDecl,
5997 bool IsSpecialization,
5998 bool IsDefinition) {
5999 if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6000 return;
6001
6002 bool IsTemplate = false;
6003 if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6004 OldDecl = OldTD->getTemplatedDecl();
6005 IsTemplate = true;
6006 if (!IsSpecialization)
6007 IsDefinition = false;
6008 }
6009 if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6010 NewDecl = NewTD->getTemplatedDecl();
6011 IsTemplate = true;
6012 }
6013
6014 if (!OldDecl || !NewDecl)
6015 return;
6016
6017 const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6018 const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6019 const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6020 const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6021
6022 // dllimport and dllexport are inheritable attributes so we have to exclude
6023 // inherited attribute instances.
6024 bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6025 (NewExportAttr && !NewExportAttr->isInherited());
6026
6027 // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6028 // the only exception being explicit specializations.
6029 // Implicitly generated declarations are also excluded for now because there
6030 // is no other way to switch these to use dllimport or dllexport.
6031 bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6032
6033 if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6034 // Allow with a warning for free functions and global variables.
6035 bool JustWarn = false;
6036 if (!OldDecl->isCXXClassMember()) {
6037 auto *VD = dyn_cast<VarDecl>(OldDecl);
6038 if (VD && !VD->getDescribedVarTemplate())
6039 JustWarn = true;
6040 auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6041 if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6042 JustWarn = true;
6043 }
6044
6045 // We cannot change a declaration that's been used because IR has already
6046 // been emitted. Dllimported functions will still work though (modulo
6047 // address equality) as they can use the thunk.
6048 if (OldDecl->isUsed())
6049 if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6050 JustWarn = false;
6051
6052 unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6053 : diag::err_attribute_dll_redeclaration;
6054 S.Diag(NewDecl->getLocation(), DiagID)
6055 << NewDecl
6056 << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6057 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6058 if (!JustWarn) {
6059 NewDecl->setInvalidDecl();
6060 return;
6061 }
6062 }
6063
6064 // A redeclaration is not allowed to drop a dllimport attribute, the only
6065 // exceptions being inline function definitions (except for function
6066 // templates), local extern declarations, qualified friend declarations or
6067 // special MSVC extension: in the last case, the declaration is treated as if
6068 // it were marked dllexport.
6069 bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6070 bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6071 if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6072 // Ignore static data because out-of-line definitions are diagnosed
6073 // separately.
6074 IsStaticDataMember = VD->isStaticDataMember();
6075 IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6076 VarDecl::DeclarationOnly;
6077 } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6078 IsInline = FD->isInlined();
6079 IsQualifiedFriend = FD->getQualifier() &&
6080 FD->getFriendObjectKind() == Decl::FOK_Declared;
6081 }
6082
6083 if (OldImportAttr && !HasNewAttr &&
6084 (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6085 !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6086 if (IsMicrosoft && IsDefinition) {
6087 S.Diag(NewDecl->getLocation(),
6088 diag::warn_redeclaration_without_import_attribute)
6089 << NewDecl;
6090 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6091 NewDecl->dropAttr<DLLImportAttr>();
6092 NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6093 NewImportAttr->getRange(), S.Context,
6094 NewImportAttr->getSpellingListIndex()));
6095 } else {
6096 S.Diag(NewDecl->getLocation(),
6097 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6098 << NewDecl << OldImportAttr;
6099 S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6100 S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6101 OldDecl->dropAttr<DLLImportAttr>();
6102 NewDecl->dropAttr<DLLImportAttr>();
6103 }
6104 } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6105 // In MinGW, seeing a function declared inline drops the dllimport
6106 // attribute.
6107 OldDecl->dropAttr<DLLImportAttr>();
6108 NewDecl->dropAttr<DLLImportAttr>();
6109 S.Diag(NewDecl->getLocation(),
6110 diag::warn_dllimport_dropped_from_inline_function)
6111 << NewDecl << OldImportAttr;
6112 }
6113
6114 // A specialization of a class template member function is processed here
6115 // since it's a redeclaration. If the parent class is dllexport, the
6116 // specialization inherits that attribute. This doesn't happen automatically
6117 // since the parent class isn't instantiated until later.
6118 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6119 if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6120 !NewImportAttr && !NewExportAttr) {
6121 if (const DLLExportAttr *ParentExportAttr =
6122 MD->getParent()->getAttr<DLLExportAttr>()) {
6123 DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6124 NewAttr->setInherited(true);
6125 NewDecl->addAttr(NewAttr);
6126 }
6127 }
6128 }
6129}
6130
6131/// Given that we are within the definition of the given function,
6132/// will that definition behave like C99's 'inline', where the
6133/// definition is discarded except for optimization purposes?
6134static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
6135 // Try to avoid calling GetGVALinkageForFunction.
6136
6137 // All cases of this require the 'inline' keyword.
6138 if (!FD->isInlined()) return false;
6139
6140 // This is only possible in C++ with the gnu_inline attribute.
6141 if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6142 return false;
6143
6144 // Okay, go ahead and call the relatively-more-expensive function.
6145 return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6146}
6147
6148/// Determine whether a variable is extern "C" prior to attaching
6149/// an initializer. We can't just call isExternC() here, because that
6150/// will also compute and cache whether the declaration is externally
6151/// visible, which might change when we attach the initializer.
6152///
6153/// This can only be used if the declaration is known to not be a
6154/// redeclaration of an internal linkage declaration.
6155///
6156/// For instance:
6157///
6158/// auto x = []{};
6159///
6160/// Attaching the initializer here makes this declaration not externally
6161/// visible, because its type has internal linkage.
6162///
6163/// FIXME: This is a hack.
6164template<typename T>
6165static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6166 if (S.getLangOpts().CPlusPlus) {
6167 // In C++, the overloadable attribute negates the effects of extern "C".
6168 if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6169 return false;
6170
6171 // So do CUDA's host/device attributes.
6172 if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6173 D->template hasAttr<CUDAHostAttr>()))
6174 return false;
6175 }
6176 return D->isExternC();
6177}
6178
6179static bool shouldConsiderLinkage(const VarDecl *VD) {
6180 const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6181 if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
6182 return VD->hasExternalStorage();
6183 if (DC->isFileContext())
6184 return true;
6185 if (DC->isRecord())
6186 return false;
6187 llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 6187)
;
6188}
6189
6190static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6191 const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6192 if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6193 isa<OMPDeclareReductionDecl>(DC))
6194 return true;
6195 if (DC->isRecord())
6196 return false;
6197 llvm_unreachable("Unexpected context")::llvm::llvm_unreachable_internal("Unexpected context", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 6197)
;
6198}
6199
6200static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
6201 AttributeList::Kind Kind) {
6202 for (const AttributeList *L = AttrList; L; L = L->getNext())
6203 if (L->getKind() == Kind)
6204 return true;
6205 return false;
6206}
6207
6208static bool hasParsedAttr(Scope *S, const Declarator &PD,
6209 AttributeList::Kind Kind) {
6210 // Check decl attributes on the DeclSpec.
6211 if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
6212 return true;
6213
6214 // Walk the declarator structure, checking decl attributes that were in a type
6215 // position to the decl itself.
6216 for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6217 if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
6218 return true;
6219 }
6220
6221 // Finally, check attributes on the decl itself.
6222 return hasParsedAttr(S, PD.getAttributes(), Kind);
6223}
6224
6225/// Adjust the \c DeclContext for a function or variable that might be a
6226/// function-local external declaration.
6227bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6228 if (!DC->isFunctionOrMethod())
6229 return false;
6230
6231 // If this is a local extern function or variable declared within a function
6232 // template, don't add it into the enclosing namespace scope until it is
6233 // instantiated; it might have a dependent type right now.
6234 if (DC->isDependentContext())
6235 return true;
6236
6237 // C++11 [basic.link]p7:
6238 // When a block scope declaration of an entity with linkage is not found to
6239 // refer to some other declaration, then that entity is a member of the
6240 // innermost enclosing namespace.
6241 //
6242 // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6243 // semantically-enclosing namespace, not a lexically-enclosing one.
6244 while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6245 DC = DC->getParent();
6246 return true;
6247}
6248
6249/// \brief Returns true if given declaration has external C language linkage.
6250static bool isDeclExternC(const Decl *D) {
6251 if (const auto *FD = dyn_cast<FunctionDecl>(D))
6252 return FD->isExternC();
6253 if (const auto *VD = dyn_cast<VarDecl>(D))
6254 return VD->isExternC();
6255
6256 llvm_unreachable("Unknown type of decl!")::llvm::llvm_unreachable_internal("Unknown type of decl!", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 6256)
;
6257}
6258
6259NamedDecl *Sema::ActOnVariableDeclarator(
6260 Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
6261 LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
6262 bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
6263 QualType R = TInfo->getType();
6264 DeclarationName Name = GetNameForDeclarator(D).getName();
6265
6266 IdentifierInfo *II = Name.getAsIdentifierInfo();
6267
6268 if (D.isDecompositionDeclarator()) {
6269 // Take the name of the first declarator as our name for diagnostic
6270 // purposes.
6271 auto &Decomp = D.getDecompositionDeclarator();
6272 if (!Decomp.bindings().empty()) {
6273 II = Decomp.bindings()[0].Name;
6274 Name = II;
6275 }
6276 } else if (!II) {
6277 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6278 return nullptr;
6279 }
6280
6281 if (getLangOpts().OpenCL) {
6282 // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6283 // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6284 // argument.
6285 if (R->isImageType() || R->isPipeType()) {
6286 Diag(D.getIdentifierLoc(),
6287 diag::err_opencl_type_can_only_be_used_as_function_parameter)
6288 << R;
6289 D.setInvalidType();
6290 return nullptr;
6291 }
6292
6293 // OpenCL v1.2 s6.9.r:
6294 // The event type cannot be used to declare a program scope variable.
6295 // OpenCL v2.0 s6.9.q:
6296 // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6297 if (NULL__null == S->getParent()) {
6298 if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6299 Diag(D.getIdentifierLoc(),
6300 diag::err_invalid_type_for_program_scope_var) << R;
6301 D.setInvalidType();
6302 return nullptr;
6303 }
6304 }
6305
6306 // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6307 QualType NR = R;
6308 while (NR->isPointerType()) {
6309 if (NR->isFunctionPointerType()) {
6310 Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6311 D.setInvalidType();
6312 break;
6313 }
6314 NR = NR->getPointeeType();
6315 }
6316
6317 if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6318 // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6319 // half array type (unless the cl_khr_fp16 extension is enabled).
6320 if (Context.getBaseElementType(R)->isHalfType()) {
6321 Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6322 D.setInvalidType();
6323 }
6324 }
6325
6326 if (R->isSamplerT()) {
6327 // OpenCL v1.2 s6.9.b p4:
6328 // The sampler type cannot be used with the __local and __global address
6329 // space qualifiers.
6330 if (R.getAddressSpace() == LangAS::opencl_local ||
6331 R.getAddressSpace() == LangAS::opencl_global) {
6332 Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6333 }
6334
6335 // OpenCL v1.2 s6.12.14.1:
6336 // A global sampler must be declared with either the constant address
6337 // space qualifier or with the const qualifier.
6338 if (DC->isTranslationUnit() &&
6339 !(R.getAddressSpace() == LangAS::opencl_constant ||
6340 R.isConstQualified())) {
6341 Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6342 D.setInvalidType();
6343 }
6344 }
6345
6346 // OpenCL v1.2 s6.9.r:
6347 // The event type cannot be used with the __local, __constant and __global
6348 // address space qualifiers.
6349 if (R->isEventT()) {
6350 if (R.getAddressSpace() != LangAS::opencl_private) {
6351 Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6352 D.setInvalidType();
6353 }
6354 }
6355 }
6356
6357 DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6358 StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6359
6360 // dllimport globals without explicit storage class are treated as extern. We
6361 // have to change the storage class this early to get the right DeclContext.
6362 if (SC == SC_None && !DC->isRecord() &&
6363 hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
6364 !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
6365 SC = SC_Extern;
6366
6367 DeclContext *OriginalDC = DC;
6368 bool IsLocalExternDecl = SC == SC_Extern &&
6369 adjustContextForLocalExternDecl(DC);
6370
6371 if (SCSpec == DeclSpec::SCS_mutable) {
6372 // mutable can only appear on non-static class members, so it's always
6373 // an error here
6374 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6375 D.setInvalidType();
6376 SC = SC_None;
6377 }
6378
6379 if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6380 !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6381 D.getDeclSpec().getStorageClassSpecLoc())) {
6382 // In C++11, the 'register' storage class specifier is deprecated.
6383 // Suppress the warning in system macros, it's used in macros in some
6384 // popular C system headers, such as in glibc's htonl() macro.
6385 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6386 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6387 : diag::warn_deprecated_register)
6388 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6389 }
6390
6391 DiagnoseFunctionSpecifiers(D.getDeclSpec());
6392
6393 if (!DC->isRecord() && S->getFnParent() == nullptr) {
6394 // C99 6.9p2: The storage-class specifiers auto and register shall not
6395 // appear in the declaration specifiers in an external declaration.
6396 // Global Register+Asm is a GNU extension we support.
6397 if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6398 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6399 D.setInvalidType();
6400 }
6401 }
6402
6403 bool IsMemberSpecialization = false;
6404 bool IsVariableTemplateSpecialization = false;
6405 bool IsPartialSpecialization = false;
6406 bool IsVariableTemplate = false;
6407 VarDecl *NewVD = nullptr;
6408 VarTemplateDecl *NewTemplate = nullptr;
6409 TemplateParameterList *TemplateParams = nullptr;
6410 if (!getLangOpts().CPlusPlus) {
6411 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6412 D.getIdentifierLoc(), II,
6413 R, TInfo, SC);
6414
6415 if (R->getContainedDeducedType())
6416 ParsingInitForAutoVars.insert(NewVD);
6417
6418 if (D.isInvalidType())
6419 NewVD->setInvalidDecl();
6420 } else {
6421 bool Invalid = false;
6422
6423 if (DC->isRecord() && !CurContext->isRecord()) {
6424 // This is an out-of-line definition of a static data member.
6425 switch (SC) {
6426 case SC_None:
6427 break;
6428 case SC_Static:
6429 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6430 diag::err_static_out_of_line)
6431 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6432 break;
6433 case SC_Auto:
6434 case SC_Register:
6435 case SC_Extern:
6436 // [dcl.stc] p2: The auto or register specifiers shall be applied only
6437 // to names of variables declared in a block or to function parameters.
6438 // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6439 // of class members
6440
6441 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6442 diag::err_storage_class_for_static_member)
6443 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6444 break;
6445 case SC_PrivateExtern:
6446 llvm_unreachable("C storage class in c++!")::llvm::llvm_unreachable_internal("C storage class in c++!", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 6446)
;
6447 }
6448 }
6449
6450 if (SC == SC_Static && CurContext->isRecord()) {
6451 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6452 if (RD->isLocalClass())
6453 Diag(D.getIdentifierLoc(),
6454 diag::err_static_data_member_not_allowed_in_local_class)
6455 << Name << RD->getDeclName();
6456
6457 // C++98 [class.union]p1: If a union contains a static data member,
6458 // the program is ill-formed. C++11 drops this restriction.
6459 if (RD->isUnion())
6460 Diag(D.getIdentifierLoc(),
6461 getLangOpts().CPlusPlus11
6462 ? diag::warn_cxx98_compat_static_data_member_in_union
6463 : diag::ext_static_data_member_in_union) << Name;
6464 // We conservatively disallow static data members in anonymous structs.
6465 else if (!RD->getDeclName())
6466 Diag(D.getIdentifierLoc(),
6467 diag::err_static_data_member_not_allowed_in_anon_struct)
6468 << Name << RD->isUnion();
6469 }
6470 }
6471
6472 // Match up the template parameter lists with the scope specifier, then
6473 // determine whether we have a template or a template specialization.
6474 TemplateParams = MatchTemplateParametersToScopeSpecifier(
6475 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6476 D.getCXXScopeSpec(),
6477 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6478 ? D.getName().TemplateId
6479 : nullptr,
6480 TemplateParamLists,
6481 /*never a friend*/ false, IsMemberSpecialization, Invalid);
6482
6483 if (TemplateParams) {
6484 if (!TemplateParams->size() &&
6485 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6486 // There is an extraneous 'template<>' for this variable. Complain
6487 // about it, but allow the declaration of the variable.
6488 Diag(TemplateParams->getTemplateLoc(),
6489 diag::err_template_variable_noparams)
6490 << II
6491 << SourceRange(TemplateParams->getTemplateLoc(),
6492 TemplateParams->getRAngleLoc());
6493 TemplateParams = nullptr;
6494 } else {
6495 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6496 // This is an explicit specialization or a partial specialization.
6497 // FIXME: Check that we can declare a specialization here.
6498 IsVariableTemplateSpecialization = true;
6499 IsPartialSpecialization = TemplateParams->size() > 0;
6500 } else { // if (TemplateParams->size() > 0)
6501 // This is a template declaration.
6502 IsVariableTemplate = true;
6503
6504 // Check that we can declare a template here.
6505 if (CheckTemplateDeclScope(S, TemplateParams))
6506 return nullptr;
6507
6508 // Only C++1y supports variable templates (N3651).
6509 Diag(D.getIdentifierLoc(),
6510 getLangOpts().CPlusPlus14
6511 ? diag::warn_cxx11_compat_variable_template
6512 : diag::ext_variable_template);
6513 }
6514 }
6515 } else {
6516 assert((Invalid ||(static_cast <bool> ((Invalid || D.getName().getKind() !=
UnqualifiedIdKind::IK_TemplateId) && "should have a 'template<>' for this decl"
) ? void (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 6518, __extension__ __PRETTY_FUNCTION__))
6517 D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&(static_cast <bool> ((Invalid || D.getName().getKind() !=
UnqualifiedIdKind::IK_TemplateId) && "should have a 'template<>' for this decl"
) ? void (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 6518, __extension__ __PRETTY_FUNCTION__))
6518 "should have a 'template<>' for this decl")(static_cast <bool> ((Invalid || D.getName().getKind() !=
UnqualifiedIdKind::IK_TemplateId) && "should have a 'template<>' for this decl"
) ? void (0) : __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 6518, __extension__ __PRETTY_FUNCTION__))
;
6519 }
6520
6521 if (IsVariableTemplateSpecialization) {
6522 SourceLocation TemplateKWLoc =
6523 TemplateParamLists.size() > 0
6524 ? TemplateParamLists[0]->getTemplateLoc()
6525 : SourceLocation();
6526 DeclResult Res = ActOnVarTemplateSpecialization(
6527 S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6528 IsPartialSpecialization);
6529 if (Res.isInvalid())
6530 return nullptr;
6531 NewVD = cast<VarDecl>(Res.get());
6532 AddToScope = false;
6533 } else if (D.isDecompositionDeclarator()) {
6534 NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6535 D.getIdentifierLoc(), R, TInfo, SC,
6536 Bindings);
6537 } else
6538 NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6539 D.getIdentifierLoc(), II, R, TInfo, SC);
6540
6541 // If this is supposed to be a variable template, create it as such.
6542 if (IsVariableTemplate) {
6543 NewTemplate =
6544 VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6545 TemplateParams, NewVD);
6546 NewVD->setDescribedVarTemplate(NewTemplate);
6547 }
6548
6549 // If this decl has an auto type in need of deduction, make a note of the
6550 // Decl so we can diagnose uses of it in its own initializer.
6551 if (R->getContainedDeducedType())
6552 ParsingInitForAutoVars.insert(NewVD);
6553
6554 if (D.isInvalidType() || Invalid) {
6555 NewVD->setInvalidDecl();
6556 if (NewTemplate)
6557 NewTemplate->setInvalidDecl();
6558 }
6559
6560 SetNestedNameSpecifier(NewVD, D);
6561
6562 // If we have any template parameter lists that don't directly belong to
6563 // the variable (matching the scope specifier), store them.
6564 unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6565 if (TemplateParamLists.size() > VDTemplateParamLists)
6566 NewVD->setTemplateParameterListsInfo(
6567 Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6568
6569 if (D.getDeclSpec().isConstexprSpecified()) {
6570 NewVD->setConstexpr(true);
6571 // C++1z [dcl.spec.constexpr]p1:
6572 // A static data member declared with the constexpr specifier is
6573 // implicitly an inline variable.
6574 if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
6575 NewVD->setImplicitlyInline();
6576 }
6577 }
6578
6579 if (D.getDeclSpec().isInlineSpecified()) {
6580 if (!getLangOpts().CPlusPlus) {
6581 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6582 << 0;
6583 } else if (CurContext->isFunctionOrMethod()) {
6584 // 'inline' is not allowed on block scope variable declaration.
6585 Diag(D.getDeclSpec().getInlineSpecLoc(),
6586 diag::err_inline_declaration_block_scope) << Name
6587 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6588 } else {
6589 Diag(D.getDeclSpec().getInlineSpecLoc(),
6590 getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6591 : diag::ext_inline_variable);
6592 NewVD->setInlineSpecified();
6593 }
6594 }
6595
6596 // Set the lexical context. If the declarator has a C++ scope specifier, the
6597 // lexical context will be different from the semantic context.
6598 NewVD->setLexicalDeclContext(CurContext);
6599 if (NewTemplate)
6600 NewTemplate->setLexicalDeclContext(CurContext);
6601
6602 if (IsLocalExternDecl) {
6603 if (D.isDecompositionDeclarator())
6604 for (auto *B : Bindings)
6605 B->setLocalExternDecl();
6606 else
6607 NewVD->setLocalExternDecl();
6608 }
6609
6610 bool EmitTLSUnsupportedError = false;
6611 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6612 // C++11 [dcl.stc]p4:
6613 // When thread_local is applied to a variable of block scope the
6614 // storage-class-specifier static is implied if it does not appear
6615 // explicitly.
6616 // Core issue: 'static' is not implied if the variable is declared
6617 // 'extern'.
6618 if (NewVD->hasLocalStorage() &&
6619 (SCSpec != DeclSpec::SCS_unspecified ||
6620 TSCS != DeclSpec::TSCS_thread_local ||
6621 !DC->isFunctionOrMethod()))
6622 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6623 diag::err_thread_non_global)
6624 << DeclSpec::getSpecifierName(TSCS);
6625 else if (!Context.getTargetInfo().isTLSSupported()) {
6626 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6627 // Postpone error emission until we've collected attributes required to
6628 // figure out whether it's a host or device variable and whether the
6629 // error should be ignored.
6630 EmitTLSUnsupportedError = true;
6631 // We still need to mark the variable as TLS so it shows up in AST with
6632 // proper storage class for other tools to use even if we're not going
6633 // to emit any code for it.
6634 NewVD->setTSCSpec(TSCS);
6635 } else
6636 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6637 diag::err_thread_unsupported);
6638 } else
6639 NewVD->setTSCSpec(TSCS);
6640 }
6641
6642 // C99 6.7.4p3
6643 // An inline definition of a function with external linkage shall
6644 // not contain a definition of a modifiable object with static or
6645 // thread storage duration...
6646 // We only apply this when the function is required to be defined
6647 // elsewhere, i.e. when the function is not 'extern inline'. Note
6648 // that a local variable with thread storage duration still has to
6649 // be marked 'static'. Also note that it's possible to get these
6650 // semantics in C++ using __attribute__((gnu_inline)).
6651 if (SC == SC_Static && S->getFnParent() != nullptr &&
6652 !NewVD->getType().isConstQualified()) {
6653 FunctionDecl *CurFD = getCurFunctionDecl();
6654 if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6655 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6656 diag::warn_static_local_in_extern_inline);
6657 MaybeSuggestAddingStaticToDecl(CurFD);
6658 }
6659 }
6660
6661 if (D.getDeclSpec().isModulePrivateSpecified()) {
6662 if (IsVariableTemplateSpecialization)
6663 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6664 << (IsPartialSpecialization ? 1 : 0)
6665 << FixItHint::CreateRemoval(
6666 D.getDeclSpec().getModulePrivateSpecLoc());
6667 else if (IsMemberSpecialization)
6668 Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6669 << 2
6670 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6671 else if (NewVD->hasLocalStorage())
6672 Diag(NewVD->getLocation(), diag::err_module_private_local)
6673 << 0 << NewVD->getDeclName()
6674 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6675 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6676 else {
6677 NewVD->setModulePrivate();
6678 if (NewTemplate)
6679 NewTemplate->setModulePrivate();
6680 for (auto *B : Bindings)
6681 B->setModulePrivate();
6682 }
6683 }
6684
6685 // Handle attributes prior to checking for duplicates in MergeVarDecl
6686 ProcessDeclAttributes(S, NewVD, D);
6687
6688 if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6689 if (EmitTLSUnsupportedError &&
6690 ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6691 (getLangOpts().OpenMPIsDevice &&
6692 NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6693 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6694 diag::err_thread_unsupported);
6695 // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6696 // storage [duration]."
6697 if (SC == SC_None && S->getFnParent() != nullptr &&
6698 (NewVD->hasAttr<CUDASharedAttr>() ||
6699 NewVD->hasAttr<CUDAConstantAttr>())) {
6700 NewVD->setStorageClass(SC_Static);
6701 }
6702 }
6703
6704 // Ensure that dllimport globals without explicit storage class are treated as
6705 // extern. The storage class is set above using parsed attributes. Now we can
6706 // check the VarDecl itself.
6707 assert(!NewVD->hasAttr<DLLImportAttr>() ||(static_cast <bool> (!NewVD->hasAttr<DLLImportAttr
>() || NewVD->getAttr<DLLImportAttr>()->isInherited
() || NewVD->isStaticDataMember() || NewVD->getStorageClass
() != SC_None) ? void (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 6709, __extension__ __PRETTY_FUNCTION__))
6708 NewVD->getAttr<DLLImportAttr>()->isInherited() ||(static_cast <bool> (!NewVD->hasAttr<DLLImportAttr
>() || NewVD->getAttr<DLLImportAttr>()->isInherited
() || NewVD->isStaticDataMember() || NewVD->getStorageClass
() != SC_None) ? void (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 6709, __extension__ __PRETTY_FUNCTION__))
6709 NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None)(static_cast <bool> (!NewVD->hasAttr<DLLImportAttr
>() || NewVD->getAttr<DLLImportAttr>()->isInherited
() || NewVD->isStaticDataMember() || NewVD->getStorageClass
() != SC_None) ? void (0) : __assert_fail ("!NewVD->hasAttr<DLLImportAttr>() || NewVD->getAttr<DLLImportAttr>()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 6709, __extension__ __PRETTY_FUNCTION__))
;
6710
6711 // In auto-retain/release, infer strong retension for variables of
6712 // retainable type.
6713 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6714 NewVD->setInvalidDecl();
6715
6716 // Handle GNU asm-label extension (encoded as an attribute).
6717 if (Expr *E = (Expr*)D.getAsmLabel()) {
6718 // The parser guarantees this is a string.
6719 StringLiteral *SE = cast<StringLiteral>(E);
6720 StringRef Label = SE->getString();
6721 if (S->getFnParent() != nullptr) {
6722 switch (SC) {
6723 case SC_None:
6724 case SC_Auto:
6725 Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6726 break;
6727 case SC_Register:
6728 // Local Named register
6729 if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6730 DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6731 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6732 break;
6733 case SC_Static:
6734 case SC_Extern:
6735 case SC_PrivateExtern:
6736 break;
6737 }
6738 } else if (SC == SC_Register) {
6739 // Global Named register
6740 if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6741 const auto &TI = Context.getTargetInfo();
6742 bool HasSizeMismatch;
6743
6744 if (!TI.isValidGCCRegisterName(Label))
6745 Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6746 else if (!TI.validateGlobalRegisterVariable(Label,
6747 Context.getTypeSize(R),
6748 HasSizeMismatch))
6749 Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6750 else if (HasSizeMismatch)
6751 Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6752 }
6753
6754 if (!R->isIntegralType(Context) && !R->isPointerType()) {
6755 Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6756 NewVD->setInvalidDecl(true);
6757 }
6758 }
6759
6760 NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6761 Context, Label, 0));
6762 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6763 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6764 ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6765 if (I != ExtnameUndeclaredIdentifiers.end()) {
6766 if (isDeclExternC(NewVD)) {
6767 NewVD->addAttr(I->second);
6768 ExtnameUndeclaredIdentifiers.erase(I);
6769 } else
6770 Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6771 << /*Variable*/1 << NewVD;
6772 }
6773 }
6774
6775 // Find the shadowed declaration before filtering for scope.
6776 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6777 ? getShadowedDeclaration(NewVD, Previous)
6778 : nullptr;
6779
6780 // Don't consider existing declarations that are in a different
6781 // scope and are out-of-semantic-context declarations (if the new
6782 // declaration has linkage).
6783 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6784 D.getCXXScopeSpec().isNotEmpty() ||
6785 IsMemberSpecialization ||
6786 IsVariableTemplateSpecialization);
6787
6788 // Check whether the previous declaration is in the same block scope. This
6789 // affects whether we merge types with it, per C++11 [dcl.array]p3.
6790 if (getLangOpts().CPlusPlus &&
6791 NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6792 NewVD->setPreviousDeclInSameBlockScope(
6793 Previous.isSingleResult() && !Previous.isShadowed() &&
6794 isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6795
6796 if (!getLangOpts().CPlusPlus) {
6797 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6798 } else {
6799 // If this is an explicit specialization of a static data member, check it.
6800 if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6801 CheckMemberSpecialization(NewVD, Previous))
6802 NewVD->setInvalidDecl();
6803
6804 // Merge the decl with the existing one if appropriate.
6805 if (!Previous.empty()) {
6806 if (Previous.isSingleResult() &&
6807 isa<FieldDecl>(Previous.getFoundDecl()) &&
6808 D.getCXXScopeSpec().isSet()) {
6809 // The user tried to define a non-static data member
6810 // out-of-line (C++ [dcl.meaning]p1).
6811 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6812 << D.getCXXScopeSpec().getRange();
6813 Previous.clear();
6814 NewVD->setInvalidDecl();
6815 }
6816 } else if (D.getCXXScopeSpec().isSet()) {
6817 // No previous declaration in the qualifying scope.
6818 Diag(D.getIdentifierLoc(), diag::err_no_member)
6819 << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6820 << D.getCXXScopeSpec().getRange();
6821 NewVD->setInvalidDecl();
6822 }
6823
6824 if (!IsVariableTemplateSpecialization)
6825 D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6826
6827 if (NewTemplate) {
6828 VarTemplateDecl *PrevVarTemplate =
6829 NewVD->getPreviousDecl()
6830 ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6831 : nullptr;
6832
6833 // Check the template parameter list of this declaration, possibly
6834 // merging in the template parameter list from the previous variable
6835 // template declaration.
6836 if (CheckTemplateParameterList(
6837 TemplateParams,
6838 PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6839 : nullptr,
6840 (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6841 DC->isDependentContext())
6842 ? TPC_ClassTemplateMember
6843 : TPC_VarTemplate))
6844 NewVD->setInvalidDecl();
6845
6846 // If we are providing an explicit specialization of a static variable
6847 // template, make a note of that.
6848 if (PrevVarTemplate &&
6849 PrevVarTemplate->getInstantiatedFromMemberTemplate())
6850 PrevVarTemplate->setMemberSpecialization();
6851 }
6852 }
6853
6854 // Diagnose shadowed variables iff this isn't a redeclaration.
6855 if (ShadowedDecl && !D.isRedeclaration())
6856 CheckShadow(NewVD, ShadowedDecl, Previous);
6857
6858 ProcessPragmaWeak(S, NewVD);
6859
6860 // If this is the first declaration of an extern C variable, update
6861 // the map of such variables.
6862 if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6863 isIncompleteDeclExternC(*this, NewVD))
6864 RegisterLocallyScopedExternCDecl(NewVD, S);
6865
6866 if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6867 Decl *ManglingContextDecl;
6868 if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6869 NewVD->getDeclContext(), ManglingContextDecl)) {
6870 Context.setManglingNumber(
6871 NewVD, MCtx->getManglingNumber(
6872 NewVD, getMSManglingNumber(getLangOpts(), S)));
6873 Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6874 }
6875 }
6876
6877 // Special handling of variable named 'main'.
6878 if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6879 NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6880 !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6881
6882 // C++ [basic.start.main]p3
6883 // A program that declares a variable main at global scope is ill-formed.
6884 if (getLangOpts().CPlusPlus)
6885 Diag(D.getLocStart(), diag::err_main_global_variable);
6886
6887 // In C, and external-linkage variable named main results in undefined
6888 // behavior.
6889 else if (NewVD->hasExternalFormalLinkage())
6890 Diag(D.getLocStart(), diag::warn_main_redefined);
6891 }
6892
6893 if (D.isRedeclaration() && !Previous.empty()) {
6894 NamedDecl *Prev = Previous.getRepresentativeDecl();
6895 checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
6896 D.isFunctionDefinition());
6897 }
6898
6899 if (NewTemplate) {
6900 if (NewVD->isInvalidDecl())
6901 NewTemplate->setInvalidDecl();
6902 ActOnDocumentableDecl(NewTemplate);
6903 return NewTemplate;
6904 }
6905
6906 if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6907 CompleteMemberSpecialization(NewVD, Previous);
6908
6909 return NewVD;
6910}
6911
6912/// Enum describing the %select options in diag::warn_decl_shadow.
6913enum ShadowedDeclKind {
6914 SDK_Local,
6915 SDK_Global,
6916 SDK_StaticMember,
6917 SDK_Field,
6918 SDK_Typedef,
6919 SDK_Using
6920};
6921
6922/// Determine what kind of declaration we're shadowing.
6923static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6924 const DeclContext *OldDC) {
6925 if (isa<TypeAliasDecl>(ShadowedDecl))
6926 return SDK_Using;
6927 else if (isa<TypedefDecl>(ShadowedDecl))
6928 return SDK_Typedef;
6929 else if (isa<RecordDecl>(OldDC))
6930 return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6931
6932 return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6933}
6934
6935/// Return the location of the capture if the given lambda captures the given
6936/// variable \p VD, or an invalid source location otherwise.
6937static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6938 const VarDecl *VD) {
6939 for (const Capture &Capture : LSI->Captures) {
6940 if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6941 return Capture.getLocation();
6942 }
6943 return SourceLocation();
6944}
6945
6946static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6947 const LookupResult &R) {
6948 // Only diagnose if we're shadowing an unambiguous field or variable.
6949 if (R.getResultKind() != LookupResult::Found)
6950 return false;
6951
6952 // Return false if warning is ignored.
6953 return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
6954}
6955
6956/// \brief Return the declaration shadowed by the given variable \p D, or null
6957/// if it doesn't shadow any declaration or shadowing warnings are disabled.
6958NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6959 const LookupResult &R) {
6960 if (!shouldWarnIfShadowedDecl(Diags, R))
6961 return nullptr;
6962
6963 // Don't diagnose declarations at file scope.
6964 if (D->hasGlobalStorage())
6965 return nullptr;
6966
6967 NamedDecl *ShadowedDecl = R.getFoundDecl();
6968 return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6969 ? ShadowedDecl
6970 : nullptr;
6971}
6972
6973/// \brief Return the declaration shadowed by the given typedef \p D, or null
6974/// if it doesn't shadow any declaration or shadowing warnings are disabled.
6975NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
6976 const LookupResult &R) {
6977 // Don't warn if typedef declaration is part of a class
6978 if (D->getDeclContext()->isRecord())
6979 return nullptr;
6980
6981 if (!shouldWarnIfShadowedDecl(Diags, R))
6982 return nullptr;
6983
6984 NamedDecl *ShadowedDecl = R.getFoundDecl();
6985 return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
6986}
6987
6988/// \brief Diagnose variable or built-in function shadowing. Implements
6989/// -Wshadow.
6990///
6991/// This method is called whenever a VarDecl is added to a "useful"
6992/// scope.
6993///
6994/// \param ShadowedDecl the declaration that is shadowed by the given variable
6995/// \param R the lookup of the name
6996///
6997void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
6998 const LookupResult &R) {
6999 DeclContext *NewDC = D->getDeclContext();
7000
7001 if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7002 // Fields are not shadowed by variables in C++ static methods.
7003 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7004 if (MD->isStatic())
7005 return;
7006
7007 // Fields shadowed by constructor parameters are a special case. Usually
7008 // the constructor initializes the field with the parameter.
7009 if (isa<CXXConstructorDecl>(NewDC))
7010 if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7011 // Remember that this was shadowed so we can either warn about its
7012 // modification or its existence depending on warning settings.
7013 ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7014 return;
7015 }
7016 }
7017
7018 if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7019 if (shadowedVar->isExternC()) {
7020 // For shadowing external vars, make sure that we point to the global
7021 // declaration, not a locally scoped extern declaration.
7022 for (auto I : shadowedVar->redecls())
7023 if (I->isFileVarDecl()) {
7024 ShadowedDecl = I;
7025 break;
7026 }
7027 }
7028
7029 DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7030
7031 unsigned WarningDiag = diag::warn_decl_shadow;
7032 SourceLocation CaptureLoc;
7033 if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7034 isa<CXXMethodDecl>(NewDC)) {
7035 if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7036 if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7037 if (RD->getLambdaCaptureDefault() == LCD_None) {
7038 // Try to avoid warnings for lambdas with an explicit capture list.
7039 const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7040 // Warn only when the lambda captures the shadowed decl explicitly.
7041 CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7042 if (CaptureLoc.isInvalid())
7043 WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7044 } else {
7045 // Remember that this was shadowed so we can avoid the warning if the
7046 // shadowed decl isn't captured and the warning settings allow it.
7047 cast<LambdaScopeInfo>(getCurFunction())
7048 ->ShadowingDecls.push_back(
7049 {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7050 return;
7051 }
7052 }
7053
7054 if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7055 // A variable can't shadow a local variable in an enclosing scope, if
7056 // they are separated by a non-capturing declaration context.
7057 for (DeclContext *ParentDC = NewDC;
7058 ParentDC && !ParentDC->Equals(OldDC);
7059 ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7060 // Only block literals, captured statements, and lambda expressions
7061 // can capture; other scopes don't.
7062 if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7063 !isLambdaCallOperator(ParentDC)) {
7064 return;
7065 }
7066 }
7067 }
7068 }
7069 }
7070
7071 // Only warn about certain kinds of shadowing for class members.
7072 if (NewDC && NewDC->isRecord()) {
7073 // In particular, don't warn about shadowing non-class members.
7074 if (!OldDC->isRecord())
7075 return;
7076
7077 // TODO: should we warn about static data members shadowing
7078 // static data members from base classes?
7079
7080 // TODO: don't diagnose for inaccessible shadowed members.
7081 // This is hard to do perfectly because we might friend the
7082 // shadowing context, but that's just a false negative.
7083 }
7084
7085
7086 DeclarationName Name = R.getLookupName();
7087
7088 // Emit warning and note.
7089 if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7090 return;
7091 ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7092 Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7093 if (!CaptureLoc.isInvalid())
7094 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7095 << Name << /*explicitly*/ 1;
7096 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7097}
7098
7099/// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7100/// when these variables are captured by the lambda.
7101void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7102 for (const auto &Shadow : LSI->ShadowingDecls) {
7103 const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7104 // Try to avoid the warning when the shadowed decl isn't captured.
7105 SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7106 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7107 Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7108 ? diag::warn_decl_shadow_uncaptured_local
7109 : diag::warn_decl_shadow)
7110 << Shadow.VD->getDeclName()
7111 << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7112 if (!CaptureLoc.isInvalid())
7113 Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7114 << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7115 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7116 }
7117}
7118
7119/// \brief Check -Wshadow without the advantage of a previous lookup.
7120void Sema::CheckShadow(Scope *S, VarDecl *D) {
7121 if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7122 return;
7123
7124 LookupResult R(*this, D->getDeclName(), D->getLocation(),
7125 Sema::LookupOrdinaryName, Sema::ForVisibleRedeclaration);
7126 LookupName(R, S);
7127 if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7128 CheckShadow(D, ShadowedDecl, R);
7129}
7130
7131/// Check if 'E', which is an expression that is about to be modified, refers
7132/// to a constructor parameter that shadows a field.
7133void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
7134 // Quickly ignore expressions that can't be shadowing ctor parameters.
7135 if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7136 return;
7137 E = E->IgnoreParenImpCasts();
7138 auto *DRE = dyn_cast<DeclRefExpr>(E);
7139 if (!DRE)
7140 return;
7141 const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7142 auto I = ShadowingDecls.find(D);
7143 if (I == ShadowingDecls.end())
7144 return;
7145 const NamedDecl *ShadowedDecl = I->second;
7146 const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7147 Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7148 Diag(D->getLocation(), diag::note_var_declared_here) << D;
7149 Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7150
7151 // Avoid issuing multiple warnings about the same decl.
7152 ShadowingDecls.erase(I);
7153}
7154
7155/// Check for conflict between this global or extern "C" declaration and
7156/// previous global or extern "C" declarations. This is only used in C++.
7157template<typename T>
7158static bool checkGlobalOrExternCConflict(
7159 Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
7160 assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"")(static_cast <bool> (S.getLangOpts().CPlusPlus &&
"only C++ has extern \"C\"") ? void (0) : __assert_fail ("S.getLangOpts().CPlusPlus && \"only C++ has extern \\\"C\\\"\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 7160, __extension__ __PRETTY_FUNCTION__))
;
7161 NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7162
7163 if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
7164 // The common case: this global doesn't conflict with any extern "C"
7165 // declaration.
7166 return false;
7167 }
7168
7169 if (Prev) {
7170 if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
7171 // Both the old and new declarations have C language linkage. This is a
7172 // redeclaration.
7173 Previous.clear();
7174 Previous.addDecl(Prev);
7175 return true;
7176 }
7177
7178 // This is a global, non-extern "C" declaration, and there is a previous
7179 // non-global extern "C" declaration. Diagnose if this is a variable
7180 // declaration.
7181 if (!isa<VarDecl>(ND))
7182 return false;
7183 } else {
7184 // The declaration is extern "C". Check for any declaration in the
7185 // translation unit which might conflict.
7186 if (IsGlobal) {
7187 // We have already performed the lookup into the translation unit.
7188 IsGlobal = false;
7189 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7190 I != E; ++I) {
7191 if (isa<VarDecl>(*I)) {
7192 Prev = *I;
7193 break;
7194 }
7195 }
7196 } else {
7197 DeclContext::lookup_result R =
7198 S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7199 for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7200 I != E; ++I) {
7201 if (isa<VarDecl>(*I)) {
7202 Prev = *I;
7203 break;
7204 }
7205 // FIXME: If we have any other entity with this name in global scope,
7206 // the declaration is ill-formed, but that is a defect: it breaks the
7207 // 'stat' hack, for instance. Only variables can have mangled name
7208 // clashes with extern "C" declarations, so only they deserve a
7209 // diagnostic.
7210 }
7211 }
7212
7213 if (!Prev)
7214 return false;
7215 }
7216
7217 // Use the first declaration's location to ensure we point at something which
7218 // is lexically inside an extern "C" linkage-spec.
7219 assert(Prev && "should have found a previous declaration to diagnose")(static_cast <bool> (Prev && "should have found a previous declaration to diagnose"
) ? void (0) : __assert_fail ("Prev && \"should have found a previous declaration to diagnose\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 7219, __extension__ __PRETTY_FUNCTION__))
;
7220 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7221 Prev = FD->getFirstDecl();
7222 else
7223 Prev = cast<VarDecl>(Prev)->getFirstDecl();
7224
7225 S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7226 << IsGlobal << ND;
7227 S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7228 << IsGlobal;
7229 return false;
7230}
7231
7232/// Apply special rules for handling extern "C" declarations. Returns \c true
7233/// if we have found that this is a redeclaration of some prior entity.
7234///
7235/// Per C++ [dcl.link]p6:
7236/// Two declarations [for a function or variable] with C language linkage
7237/// with the same name that appear in different scopes refer to the same
7238/// [entity]. An entity with C language linkage shall not be declared with
7239/// the same name as an entity in global scope.
7240template<typename T>
7241static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
7242 LookupResult &Previous) {
7243 if (!S.getLangOpts().CPlusPlus) {
7244 // In C, when declaring a global variable, look for a corresponding 'extern'
7245 // variable declared in function scope. We don't need this in C++, because
7246 // we find local extern decls in the surrounding file-scope DeclContext.
7247 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7248 if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7249 Previous.clear();
7250 Previous.addDecl(Prev);
7251 return true;
7252 }
7253 }
7254 return false;
7255 }
7256
7257 // A declaration in the translation unit can conflict with an extern "C"
7258 // declaration.
7259 if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7260 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
7261
7262 // An extern "C" declaration can conflict with a declaration in the
7263 // translation unit or can be a redeclaration of an extern "C" declaration
7264 // in another scope.
7265 if (isIncompleteDeclExternC(S,ND))
7266 return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
7267
7268 // Neither global nor extern "C": nothing to do.
7269 return false;
7270}
7271
7272void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7273 // If the decl is already known invalid, don't check it.
7274 if (NewVD->isInvalidDecl())
7275 return;
7276
7277 TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
7278 QualType T = TInfo->getType();
7279
7280 // Defer checking an 'auto' type until its initializer is attached.
7281 if (T->isUndeducedType())
7282 return;
7283
7284 if (NewVD->hasAttrs())
7285 CheckAlignasUnderalignment(NewVD);
7286
7287 if (T->isObjCObjectType()) {
7288 Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7289 << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7290 T = Context.getObjCObjectPointerType(T);
7291 NewVD->setType(T);
7292 }
7293
7294 // Emit an error if an address space was applied to decl with local storage.
7295 // This includes arrays of objects with address space qualifiers, but not
7296 // automatic variables that point to other address spaces.
7297 // ISO/IEC TR 18037 S5.1.2
7298 if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7299 T.getAddressSpace() != LangAS::Default) {
7300 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7301 NewVD->setInvalidDecl();
7302 return;
7303 }
7304
7305 // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7306 // scope.
7307 if (getLangOpts().OpenCLVersion == 120 &&
7308 !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7309 NewVD->isStaticLocal()) {
7310 Diag(NewVD->getLocation(), diag::err_static_function_scope);
7311 NewVD->setInvalidDecl();
7312 return;
7313 }
7314
7315 if (getLangOpts().OpenCL) {
7316 // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7317 if (NewVD->hasAttr<BlocksAttr>()) {
7318 Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7319 return;
7320 }
7321
7322 if (T->isBlockPointerType()) {
7323 // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7324 // can't use 'extern' storage class.
7325 if (!T.isConstQualified()) {
7326 Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7327 << 0 /*const*/;
7328 NewVD->setInvalidDecl();
7329 return;
7330 }
7331 if (NewVD->hasExternalStorage()) {
7332 Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7333 NewVD->setInvalidDecl();
7334 return;
7335 }
7336 }
7337 // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
7338 // __constant address space.
7339 // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
7340 // variables inside a function can also be declared in the global
7341 // address space.
7342 if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7343 NewVD->hasExternalStorage()) {
7344 if (!T->isSamplerT() &&
7345 !(T.getAddressSpace() == LangAS::opencl_constant ||
7346 (T.getAddressSpace() == LangAS::opencl_global &&
7347 getLangOpts().OpenCLVersion == 200))) {
7348 int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7349 if (getLangOpts().OpenCLVersion == 200)
7350 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7351 << Scope << "global or constant";
7352 else
7353 Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7354 << Scope << "constant";
7355 NewVD->setInvalidDecl();
7356 return;
7357 }
7358 } else {
7359 if (T.getAddressSpace() == LangAS::opencl_global) {
7360 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7361 << 1 /*is any function*/ << "global";
7362 NewVD->setInvalidDecl();
7363 return;
7364 }
7365 if (T.getAddressSpace() == LangAS::opencl_constant ||
7366 T.getAddressSpace() == LangAS::opencl_local) {
7367 FunctionDecl *FD = getCurFunctionDecl();
7368 // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7369 // in functions.
7370 if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7371 if (T.getAddressSpace() == LangAS::opencl_constant)
7372 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7373 << 0 /*non-kernel only*/ << "constant";
7374 else
7375 Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7376 << 0 /*non-kernel only*/ << "local";
7377 NewVD->setInvalidDecl();
7378 return;
7379 }
7380 // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7381 // in the outermost scope of a kernel function.
7382 if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7383 if (!getCurScope()->isFunctionScope()) {
7384 if (T.getAddressSpace() == LangAS::opencl_constant)
7385 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7386 << "constant";
7387 else
7388 Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7389 << "local";
7390 NewVD->setInvalidDecl();
7391 return;
7392 }
7393 }
7394 } else if (T.getAddressSpace() != LangAS::opencl_private) {
7395 // Do not allow other address spaces on automatic variable.
7396 Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7397 NewVD->setInvalidDecl();
7398 return;
7399 }
7400 }
7401 }
7402
7403 if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7404 && !NewVD->hasAttr<BlocksAttr>()) {
7405 if (getLangOpts().getGC() != LangOptions::NonGC)
7406 Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7407 else {
7408 assert(!getLangOpts().ObjCAutoRefCount)(static_cast <bool> (!getLangOpts().ObjCAutoRefCount) ?
void (0) : __assert_fail ("!getLangOpts().ObjCAutoRefCount",
"/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 7408, __extension__ __PRETTY_FUNCTION__))
;
7409 Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7410 }
7411 }
7412
7413 bool isVM = T->isVariablyModifiedType();
7414 if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7415 NewVD->hasAttr<BlocksAttr>())
7416 setFunctionHasBranchProtectedScope();
7417
7418 if ((isVM && NewVD->hasLinkage()) ||
7419 (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7420 bool SizeIsNegative;
7421 llvm::APSInt Oversized;
7422 TypeSourceInfo *FixedTInfo =
7423 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7424 SizeIsNegative, Oversized);
7425 if (!FixedTInfo && T->isVariableArrayType()) {
7426 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7427 // FIXME: This won't give the correct result for
7428 // int a[10][n];
7429 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7430
7431 if (NewVD->isFileVarDecl())
7432 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7433 << SizeRange;
7434 else if (NewVD->isStaticLocal())
7435 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7436 << SizeRange;
7437 else
7438 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7439 << SizeRange;
7440 NewVD->setInvalidDecl();
7441 return;
7442 }
7443
7444 if (!FixedTInfo) {
7445 if (NewVD->isFileVarDecl())
7446 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7447 else
7448 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7449 NewVD->setInvalidDecl();
7450 return;
7451 }
7452
7453 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7454 NewVD->setType(FixedTInfo->getType());
7455 NewVD->setTypeSourceInfo(FixedTInfo);
7456 }
7457
7458 if (T->isVoidType()) {
7459 // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7460 // of objects and functions.
7461 if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7462 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7463 << T;
7464 NewVD->setInvalidDecl();
7465 return;
7466 }
7467 }
7468
7469 if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7470 Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7471 NewVD->setInvalidDecl();
7472 return;
7473 }
7474
7475 if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7476 Diag(NewVD->getLocation(), diag::err_block_on_vm);
7477 NewVD->setInvalidDecl();
7478 return;
7479 }
7480
7481 if (NewVD->isConstexpr() && !T->isDependentType() &&
7482 RequireLiteralType(NewVD->getLocation(), T,
7483 diag::err_constexpr_var_non_literal)) {
7484 NewVD->setInvalidDecl();
7485 return;
7486 }
7487}
7488
7489/// \brief Perform semantic checking on a newly-created variable
7490/// declaration.
7491///
7492/// This routine performs all of the type-checking required for a
7493/// variable declaration once it has been built. It is used both to
7494/// check variables after they have been parsed and their declarators
7495/// have been translated into a declaration, and to check variables
7496/// that have been instantiated from a template.
7497///
7498/// Sets NewVD->isInvalidDecl() if an error was encountered.
7499///
7500/// Returns true if the variable declaration is a redeclaration.
7501bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7502 CheckVariableDeclarationType(NewVD);
7503
7504 // If the decl is already known invalid, don't check it.
7505 if (NewVD->isInvalidDecl())
7506 return false;
7507
7508 // If we did not find anything by this name, look for a non-visible
7509 // extern "C" declaration with the same name.
7510 if (Previous.empty() &&
7511 checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7512 Previous.setShadowed();
7513
7514 if (!Previous.empty()) {
7515 MergeVarDecl(NewVD, Previous);
7516 return true;
7517 }
7518 return false;
7519}
7520
7521namespace {
7522struct FindOverriddenMethod {
7523 Sema *S;
7524 CXXMethodDecl *Method;
7525
7526 /// Member lookup function that determines whether a given C++
7527 /// method overrides a method in a base class, to be used with
7528 /// CXXRecordDecl::lookupInBases().
7529 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7530 RecordDecl *BaseRecord =
7531 Specifier->getType()->getAs<RecordType>()->getDecl();
7532
7533 DeclarationName Name = Method->getDeclName();
7534
7535 // FIXME: Do we care about other names here too?
7536 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7537 // We really want to find the base class destructor here.
7538 QualType T = S->Context.getTypeDeclType(BaseRecord);
7539 CanQualType CT = S->Context.getCanonicalType(T);
7540
7541 Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7542 }
7543
7544 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7545 Path.Decls = Path.Decls.slice(1)) {
7546 NamedDecl *D = Path.Decls.front();
7547 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7548 if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7549 return true;
7550 }
7551 }
7552
7553 return false;
7554 }
7555};
7556
7557enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7558} // end anonymous namespace
7559
7560/// \brief Report an error regarding overriding, along with any relevant
7561/// overridden methods.
7562///
7563/// \param DiagID the primary error to report.
7564/// \param MD the overriding method.
7565/// \param OEK which overrides to include as notes.
7566static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7567 OverrideErrorKind OEK = OEK_All) {
7568 S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7569 for (const CXXMethodDecl *O : MD->overridden_methods()) {
7570 // This check (& the OEK parameter) could be replaced by a predicate, but
7571 // without lambdas that would be overkill. This is still nicer than writing
7572 // out the diag loop 3 times.
7573 if ((OEK == OEK_All) ||
7574 (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7575 (OEK == OEK_Deleted && O->isDeleted()))
7576 S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7577 }
7578}
7579
7580/// AddOverriddenMethods - See if a method overrides any in the base classes,
7581/// and if so, check that it's a valid override and remember it.
7582bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7583 // Look for methods in base classes that this method might override.
7584 CXXBasePaths Paths;
7585 FindOverriddenMethod FOM;
7586 FOM.Method = MD;
7587 FOM.S = this;
7588 bool hasDeletedOverridenMethods = false;
7589 bool hasNonDeletedOverridenMethods = false;
7590 bool AddedAny = false;
7591 if (DC->lookupInBases(FOM, Paths)) {
7592 for (auto *I : Paths.found_decls()) {
7593 if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7594 MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7595 if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7596 !CheckOverridingFunctionAttributes(MD, OldMD) &&
7597 !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7598 !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7599 hasDeletedOverridenMethods |= OldMD->isDeleted();
7600 hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7601 AddedAny = true;
7602 }
7603 }
7604 }
7605 }
7606
7607 if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7608 ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7609 }
7610 if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7611 ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7612 }
7613
7614 return AddedAny;
7615}
7616
7617namespace {
7618 // Struct for holding all of the extra arguments needed by
7619 // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7620 struct ActOnFDArgs {
7621 Scope *S;
7622 Declarator &D;
7623 MultiTemplateParamsArg TemplateParamLists;
7624 bool AddToScope;
7625 };
7626} // end anonymous namespace
7627
7628namespace {
7629
7630// Callback to only accept typo corrections that have a non-zero edit distance.
7631// Also only accept corrections that have the same parent decl.
7632class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7633 public:
7634 DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7635 CXXRecordDecl *Parent)
7636 : Context(Context), OriginalFD(TypoFD),
7637 ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7638
7639 bool ValidateCandidate(const TypoCorrection &candidate) override {
7640 if (candidate.getEditDistance() == 0)
7641 return false;
7642
7643 SmallVector<unsigned, 1> MismatchedParams;
7644 for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7645 CDeclEnd = candidate.end();
7646 CDecl != CDeclEnd; ++CDecl) {
7647 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7648
7649 if (FD && !FD->hasBody() &&
7650 hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7651 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7652 CXXRecordDecl *Parent = MD->getParent();
7653 if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7654 return true;
7655 } else if (!ExpectedParent) {
7656 return true;
7657 }
7658 }
7659 }
7660
7661 return false;
7662 }
7663
7664 private:
7665 ASTContext &Context;
7666 FunctionDecl *OriginalFD;
7667 CXXRecordDecl *ExpectedParent;
7668};
7669
7670} // end anonymous namespace
7671
7672void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7673 TypoCorrectedFunctionDefinitions.insert(F);
7674}
7675
7676/// \brief Generate diagnostics for an invalid function redeclaration.
7677///
7678/// This routine handles generating the diagnostic messages for an invalid
7679/// function redeclaration, including finding possible similar declarations
7680/// or performing typo correction if there are no previous declarations with
7681/// the same name.
7682///
7683/// Returns a NamedDecl iff typo correction was performed and substituting in
7684/// the new declaration name does not cause new errors.
7685static NamedDecl *DiagnoseInvalidRedeclaration(
7686 Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7687 ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7688 DeclarationName Name = NewFD->getDeclName();
7689 DeclContext *NewDC = NewFD->getDeclContext();
7690 SmallVector<unsigned, 1> MismatchedParams;
7691 SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7692 TypoCorrection Correction;
7693 bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7694 unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7695 : diag::err_member_decl_does_not_match;
7696 LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7697 IsLocalFriend ? Sema::LookupLocalFriendName
7698 : Sema::LookupOrdinaryName,
7699 Sema::ForVisibleRedeclaration);
7700
7701 NewFD->setInvalidDecl();
7702 if (IsLocalFriend)
7703 SemaRef.LookupName(Prev, S);
7704 else
7705 SemaRef.LookupQualifiedName(Prev, NewDC);
7706 assert(!Prev.isAmbiguous() &&(static_cast <bool> (!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup"
) ? void (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 7707, __extension__ __PRETTY_FUNCTION__))
7707 "Cannot have an ambiguity in previous-declaration lookup")(static_cast <bool> (!Prev.isAmbiguous() && "Cannot have an ambiguity in previous-declaration lookup"
) ? void (0) : __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 7707, __extension__ __PRETTY_FUNCTION__))
;
7708 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7709 if (!Prev.empty()) {
7710 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7711 Func != FuncEnd; ++Func) {
7712 FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7713 if (FD &&
7714 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7715 // Add 1 to the index so that 0 can mean the mismatch didn't
7716 // involve a parameter
7717 unsigned ParamNum =
7718 MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7719 NearMatches.push_back(std::make_pair(FD, ParamNum));
7720 }
7721 }
7722 // If the qualified name lookup yielded nothing, try typo correction
7723 } else if ((Correction = SemaRef.CorrectTypo(
7724 Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7725 &ExtraArgs.D.getCXXScopeSpec(),
7726 llvm::make_unique<DifferentNameValidatorCCC>(
7727 SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7728 Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7729 // Set up everything for the call to ActOnFunctionDeclarator
7730 ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7731 ExtraArgs.D.getIdentifierLoc());
7732 Previous.clear();
7733 Previous.setLookupName(Correction.getCorrection());
7734 for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7735 CDeclEnd = Correction.end();
7736 CDecl != CDeclEnd; ++CDecl) {
7737 FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7738 if (FD && !FD->hasBody() &&
7739 hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7740 Previous.addDecl(FD);
7741 }
7742 }
7743 bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7744
7745 NamedDecl *Result;
7746 // Retry building the function declaration with the new previous
7747 // declarations, and with errors suppressed.
7748 {
7749 // Trap errors.
7750 Sema::SFINAETrap Trap(SemaRef);
7751
7752 // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7753 // pieces need to verify the typo-corrected C++ declaration and hopefully
7754 // eliminate the need for the parameter pack ExtraArgs.
7755 Result = SemaRef.ActOnFunctionDeclarator(
7756 ExtraArgs.S, ExtraArgs.D,
7757 Correction.getCorrectionDecl()->getDeclContext(),
7758 NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7759 ExtraArgs.AddToScope);
7760
7761 if (Trap.hasErrorOccurred())
7762 Result = nullptr;
7763 }
7764
7765 if (Result) {
7766 // Determine which correction we picked.
7767 Decl *Canonical = Result->getCanonicalDecl();
7768 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7769 I != E; ++I)
7770 if ((*I)->getCanonicalDecl() == Canonical)
7771 Correction.setCorrectionDecl(*I);
7772
7773 // Let Sema know about the correction.
7774 SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7775 SemaRef.diagnoseTypo(
7776 Correction,
7777 SemaRef.PDiag(IsLocalFriend
7778 ? diag::err_no_matching_local_friend_suggest
7779 : diag::err_member_decl_does_not_match_suggest)
7780 << Name << NewDC << IsDefinition);
7781 return Result;
7782 }
7783
7784 // Pretend the typo correction never occurred
7785 ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7786 ExtraArgs.D.getIdentifierLoc());
7787 ExtraArgs.D.setRedeclaration(wasRedeclaration);
7788 Previous.clear();
7789 Previous.setLookupName(Name);
7790 }
7791
7792 SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7793 << Name << NewDC << IsDefinition << NewFD->getLocation();
7794
7795 bool NewFDisConst = false;
7796 if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7797 NewFDisConst = NewMD->isConst();
7798
7799 for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7800 NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7801 NearMatch != NearMatchEnd; ++NearMatch) {
7802 FunctionDecl *FD = NearMatch->first;
7803 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7804 bool FDisConst = MD && MD->isConst();
7805 bool IsMember = MD || !IsLocalFriend;
7806
7807 // FIXME: These notes are poorly worded for the local friend case.
7808 if (unsigned Idx = NearMatch->second) {
7809 ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7810 SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7811 if (Loc.isInvalid()) Loc = FD->getLocation();
7812 SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7813 : diag::note_local_decl_close_param_match)
7814 << Idx << FDParam->getType()
7815 << NewFD->getParamDecl(Idx - 1)->getType();
7816 } else if (FDisConst != NewFDisConst) {
7817 SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7818 << NewFDisConst << FD->getSourceRange().getEnd();
7819 } else
7820 SemaRef.Diag(FD->getLocation(),
7821 IsMember ? diag::note_member_def_close_match
7822 : diag::note_local_decl_close_match);
7823 }
7824 return nullptr;
7825}
7826
7827static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7828 switch (D.getDeclSpec().getStorageClassSpec()) {
7829 default: llvm_unreachable("Unknown storage class!")::llvm::llvm_unreachable_internal("Unknown storage class!", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 7829)
;
7830 case DeclSpec::SCS_auto:
7831 case DeclSpec::SCS_register:
7832 case DeclSpec::SCS_mutable:
7833 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7834 diag::err_typecheck_sclass_func);
7835 D.getMutableDeclSpec().ClearStorageClassSpecs();
7836 D.setInvalidType();
7837 break;
7838 case DeclSpec::SCS_unspecified: break;
7839 case DeclSpec::SCS_extern:
7840 if (D.getDeclSpec().isExternInLinkageSpec())
7841 return SC_None;
7842 return SC_Extern;
7843 case DeclSpec::SCS_static: {
7844 if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7845 // C99 6.7.1p5:
7846 // The declaration of an identifier for a function that has
7847 // block scope shall have no explicit storage-class specifier
7848 // other than extern
7849 // See also (C++ [dcl.stc]p4).
7850 SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7851 diag::err_static_block_func);
7852 break;
7853 } else
7854 return SC_Static;
7855 }
7856 case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7857 }
7858
7859 // No explicit storage class has already been returned
7860 return SC_None;
7861}
7862
7863static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7864 DeclContext *DC, QualType &R,
7865 TypeSourceInfo *TInfo,
7866 StorageClass SC,
7867 bool &IsVirtualOkay) {
7868 DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7869 DeclarationName Name = NameInfo.getName();
7870
7871 FunctionDecl *NewFD = nullptr;
7872 bool isInline = D.getDeclSpec().isInlineSpecified();
7873
7874 if (!SemaRef.getLangOpts().CPlusPlus) {
7875 // Determine whether the function was written with a
7876 // prototype. This true when:
7877 // - there is a prototype in the declarator, or
7878 // - the type R of the function is some kind of typedef or other non-
7879 // attributed reference to a type name (which eventually refers to a
7880 // function type).
7881 bool HasPrototype =
7882 (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7883 (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7884
7885 NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7886 D.getLocStart(), NameInfo, R,
7887 TInfo, SC, isInline,
7888 HasPrototype, false);
7889 if (D.isInvalidType())
7890 NewFD->setInvalidDecl();
7891
7892 return NewFD;
7893 }
7894
7895 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7896 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7897
7898 // Check that the return type is not an abstract class type.
7899 // For record types, this is done by the AbstractClassUsageDiagnoser once
7900 // the class has been completely parsed.
7901 if (!DC->isRecord() &&
7902 SemaRef.RequireNonAbstractType(
7903 D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7904 diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7905 D.setInvalidType();
7906
7907 if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7908 // This is a C++ constructor declaration.
7909 assert(DC->isRecord() &&(static_cast <bool> (DC->isRecord() && "Constructors can only be declared in a member context"
) ? void (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 7910, __extension__ __PRETTY_FUNCTION__))
7910 "Constructors can only be declared in a member context")(static_cast <bool> (DC->isRecord() && "Constructors can only be declared in a member context"
) ? void (0) : __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 7910, __extension__ __PRETTY_FUNCTION__))
;
7911
7912 R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7913 return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7914 D.getLocStart(), NameInfo,
7915 R, TInfo, isExplicit, isInline,
7916 /*isImplicitlyDeclared=*/false,
7917 isConstexpr);
7918
7919 } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7920 // This is a C++ destructor declaration.
7921 if (DC->isRecord()) {
7922 R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7923 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7924 CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7925 SemaRef.Context, Record,
7926 D.getLocStart(),
7927 NameInfo, R, TInfo, isInline,
7928 /*isImplicitlyDeclared=*/false);
7929
7930 // If the class is complete, then we now create the implicit exception
7931 // specification. If the class is incomplete or dependent, we can't do
7932 // it yet.
7933 if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7934 Record->getDefinition() && !Record->isBeingDefined() &&
7935 R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7936 SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7937 }
7938
7939 IsVirtualOkay = true;
7940 return NewDD;
7941
7942 } else {
7943 SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7944 D.setInvalidType();
7945
7946 // Create a FunctionDecl to satisfy the function definition parsing
7947 // code path.
7948 return FunctionDecl::Create(SemaRef.Context, DC,
7949 D.getLocStart(),
7950 D.getIdentifierLoc(), Name, R, TInfo,
7951 SC, isInline,
7952 /*hasPrototype=*/true, isConstexpr);
7953 }
7954
7955 } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7956 if (!DC->isRecord()) {
7957 SemaRef.Diag(D.getIdentifierLoc(),
7958 diag::err_conv_function_not_member);
7959 return nullptr;
7960 }
7961
7962 SemaRef.CheckConversionDeclarator(D, R, SC);
7963 IsVirtualOkay = true;
7964 return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7965 D.getLocStart(), NameInfo,
7966 R, TInfo, isInline, isExplicit,
7967 isConstexpr, SourceLocation());
7968
7969 } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
7970 SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
7971
7972 return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getLocStart(),
7973 isExplicit, NameInfo, R, TInfo,
7974 D.getLocEnd());
7975 } else if (DC->isRecord()) {
7976 // If the name of the function is the same as the name of the record,
7977 // then this must be an invalid constructor that has a return type.
7978 // (The parser checks for a return type and makes the declarator a
7979 // constructor if it has no return type).
7980 if (Name.getAsIdentifierInfo() &&
7981 Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7982 SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7983 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7984 << SourceRange(D.getIdentifierLoc());
7985 return nullptr;
7986 }
7987
7988 // This is a C++ method declaration.
7989 CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7990 cast<CXXRecordDecl>(DC),
7991 D.getLocStart(), NameInfo, R,
7992 TInfo, SC, isInline,
7993 isConstexpr, SourceLocation());
7994 IsVirtualOkay = !Ret->isStatic();
7995 return Ret;
7996 } else {
7997 bool isFriend =
7998 SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7999 if (!isFriend && SemaRef.CurContext->isRecord())
8000 return nullptr;
8001
8002 // Determine whether the function was written with a
8003 // prototype. This true when:
8004 // - we're in C++ (where every function has a prototype),
8005 return FunctionDecl::Create(SemaRef.Context, DC,
8006 D.getLocStart(),
8007 NameInfo, R, TInfo, SC, isInline,
8008 true/*HasPrototype*/, isConstexpr);
8009 }
8010}
8011
8012enum OpenCLParamType {
8013 ValidKernelParam,
8014 PtrPtrKernelParam,
8015 PtrKernelParam,
8016 InvalidAddrSpacePtrKernelParam,
8017 InvalidKernelParam,
8018 RecordKernelParam
8019};
8020
8021static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
8022 if (PT->isPointerType()) {
8023 QualType PointeeType = PT->getPointeeType();
8024 if (PointeeType->isPointerType())
8025 return PtrPtrKernelParam;
8026 if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8027 PointeeType.getAddressSpace() == LangAS::opencl_private ||
8028 PointeeType.getAddressSpace() == LangAS::Default)
8029 return InvalidAddrSpacePtrKernelParam;
8030 return PtrKernelParam;
8031 }
8032
8033 // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
8034 // be used as builtin types.
8035
8036 if (PT->isImageType())
8037 return PtrKernelParam;
8038
8039 if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8040 return InvalidKernelParam;
8041
8042 // OpenCL extension spec v1.2 s9.5:
8043 // This extension adds support for half scalar and vector types as built-in
8044 // types that can be used for arithmetic operations, conversions etc.
8045 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8046 return InvalidKernelParam;
8047
8048 if (PT->isRecordType())
8049 return RecordKernelParam;
8050
8051 return ValidKernelParam;
8052}
8053
8054static void checkIsValidOpenCLKernelParameter(
8055 Sema &S,
8056 Declarator &D,
8057 ParmVarDecl *Param,
8058 llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8059 QualType PT = Param->getType();
8060
8061 // Cache the valid types we encounter to avoid rechecking structs that are
8062 // used again
8063 if (ValidTypes.count(PT.getTypePtr()))
8064 return;
8065
8066 switch (getOpenCLKernelParameterType(S, PT)) {
8067 case PtrPtrKernelParam:
8068 // OpenCL v1.2 s6.9.a:
8069 // A kernel function argument cannot be declared as a
8070 // pointer to a pointer type.
8071 S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8072 D.setInvalidType();
8073 return;
8074
8075 case InvalidAddrSpacePtrKernelParam:
8076 // OpenCL v1.0 s6.5:
8077 // __kernel function arguments declared to be a pointer of a type can point
8078 // to one of the following address spaces only : __global, __local or
8079 // __constant.
8080 S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8081 D.setInvalidType();
8082 return;
8083
8084 // OpenCL v1.2 s6.9.k:
8085 // Arguments to kernel functions in a program cannot be declared with the
8086 // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8087 // uintptr_t or a struct and/or union that contain fields declared to be
8088 // one of these built-in scalar types.
8089
8090 case InvalidKernelParam:
8091 // OpenCL v1.2 s6.8 n:
8092 // A kernel function argument cannot be declared
8093 // of event_t type.
8094 // Do not diagnose half type since it is diagnosed as invalid argument
8095 // type for any function elsewhere.
8096 if (!PT->isHalfType())
8097 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8098 D.setInvalidType();
8099 return;
8100
8101 case PtrKernelParam:
8102 case ValidKernelParam:
8103 ValidTypes.insert(PT.getTypePtr());
8104 return;
8105
8106 case RecordKernelParam:
8107 break;
8108 }
8109
8110 // Track nested structs we will inspect
8111 SmallVector<const Decl *, 4> VisitStack;
8112
8113 // Track where we are in the nested structs. Items will migrate from
8114 // VisitStack to HistoryStack as we do the DFS for bad field.
8115 SmallVector<const FieldDecl *, 4> HistoryStack;
8116 HistoryStack.push_back(nullptr);
8117
8118 const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
8119 VisitStack.push_back(PD);
8120
8121 assert(VisitStack.back() && "First decl null?")(static_cast <bool> (VisitStack.back() && "First decl null?"
) ? void (0) : __assert_fail ("VisitStack.back() && \"First decl null?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 8121, __extension__ __PRETTY_FUNCTION__))
;
8122
8123 do {
8124 const Decl *Next = VisitStack.pop_back_val();
8125 if (!Next) {
8126 assert(!HistoryStack.empty())(static_cast <bool> (!HistoryStack.empty()) ? void (0) :
__assert_fail ("!HistoryStack.empty()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 8126, __extension__ __PRETTY_FUNCTION__))
;
8127 // Found a marker, we have gone up a level
8128 if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8129 ValidTypes.insert(Hist->getType().getTypePtr());
8130
8131 continue;
8132 }
8133
8134 // Adds everything except the original parameter declaration (which is not a
8135 // field itself) to the history stack.
8136 const RecordDecl *RD;
8137 if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8138 HistoryStack.push_back(Field);
8139 RD = Field->getType()->castAs<RecordType>()->getDecl();
8140 } else {
8141 RD = cast<RecordDecl>(Next);
8142 }
8143
8144 // Add a null marker so we know when we've gone back up a level
8145 VisitStack.push_back(nullptr);
8146
8147 for (const auto *FD : RD->fields()) {
8148 QualType QT = FD->getType();
8149
8150 if (ValidTypes.count(QT.getTypePtr()))
8151 continue;
8152
8153 OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8154 if (ParamType == ValidKernelParam)
8155 continue;
8156
8157 if (ParamType == RecordKernelParam) {
8158 VisitStack.push_back(FD);
8159 continue;
8160 }
8161
8162 // OpenCL v1.2 s6.9.p:
8163 // Arguments to kernel functions that are declared to be a struct or union
8164 // do not allow OpenCL objects to be passed as elements of the struct or
8165 // union.
8166 if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8167 ParamType == InvalidAddrSpacePtrKernelParam) {
8168 S.Diag(Param->getLocation(),
8169 diag::err_record_with_pointers_kernel_param)
8170 << PT->isUnionType()
8171 << PT;
8172 } else {
8173 S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8174 }
8175
8176 S.Diag(PD->getLocation(), diag::note_within_field_of_type)
8177 << PD->getDeclName();
8178
8179 // We have an error, now let's go back up through history and show where
8180 // the offending field came from
8181 for (ArrayRef<const FieldDecl *>::const_iterator
8182 I = HistoryStack.begin() + 1,
8183 E = HistoryStack.end();
8184 I != E; ++I) {
8185 const FieldDecl *OuterField = *I;
8186 S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8187 << OuterField->getType();
8188 }
8189
8190 S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8191 << QT->isPointerType()
8192 << QT;
8193 D.setInvalidType();
8194 return;
8195 }
8196 } while (!VisitStack.empty());
8197}
8198
8199/// Find the DeclContext in which a tag is implicitly declared if we see an
8200/// elaborated type specifier in the specified context, and lookup finds
8201/// nothing.
8202static DeclContext *getTagInjectionContext(DeclContext *DC) {
8203 while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8204 DC = DC->getParent();
8205 return DC;
8206}
8207
8208/// Find the Scope in which a tag is implicitly declared if we see an
8209/// elaborated type specifier in the specified context, and lookup finds
8210/// nothing.
8211static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
8212 while (S->isClassScope() ||
8213 (LangOpts.CPlusPlus &&
8214 S->isFunctionPrototypeScope()) ||
8215 ((S->getFlags() & Scope::DeclScope) == 0) ||
8216 (S->getEntity() && S->getEntity()->isTransparentContext()))
8217 S = S->getParent();
8218 return S;
8219}
8220
8221NamedDecl*
8222Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
8223 TypeSourceInfo *TInfo, LookupResult &Previous,
8224 MultiTemplateParamsArg TemplateParamLists,
8225 bool &AddToScope) {
8226 QualType R = TInfo->getType();
8227
8228 assert(R.getTypePtr()->isFunctionType())(static_cast <bool> (R.getTypePtr()->isFunctionType(
)) ? void (0) : __assert_fail ("R.getTypePtr()->isFunctionType()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 8228, __extension__ __PRETTY_FUNCTION__))
;
8229
8230 // TODO: consider using NameInfo for diagnostic.
8231 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8232 DeclarationName Name = NameInfo.getName();
8233 StorageClass SC = getFunctionStorageClass(*this, D);
8234
8235 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8236 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8237 diag::err_invalid_thread)
8238 << DeclSpec::getSpecifierName(TSCS);
8239
8240 if (D.isFirstDeclarationOfMember())
8241 adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
8242 D.getIdentifierLoc());
8243
8244 bool isFriend = false;
8245 FunctionTemplateDecl *FunctionTemplate = nullptr;
8246 bool isMemberSpecialization = false;
8247 bool isFunctionTemplateSpecialization = false;
8248
8249 bool isDependentClassScopeExplicitSpecialization = false;
8250 bool HasExplicitTemplateArgs = false;
8251 TemplateArgumentListInfo TemplateArgs;
8252
8253 bool isVirtualOkay = false;
8254
8255 DeclContext *OriginalDC = DC;
8256 bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8257
8258 FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
8259 isVirtualOkay);
8260 if (!NewFD) return nullptr;
8261
8262 if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8263 NewFD->setTopLevelDeclInObjCContainer();
8264
8265 // Set the lexical context. If this is a function-scope declaration, or has a
8266 // C++ scope specifier, or is the object of a friend declaration, the lexical
8267 // context will be different from the semantic context.
8268 NewFD->setLexicalDeclContext(CurContext);
8269
8270 if (IsLocalExternDecl)
8271 NewFD->setLocalExternDecl();
8272
8273 if (getLangOpts().CPlusPlus) {
8274 bool isInline = D.getDeclSpec().isInlineSpecified();
8275 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8276 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8277 bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8278 isFriend = D.getDeclSpec().isFriendSpecified();
8279 if (isFriend && !isInline && D.isFunctionDefinition()) {
8280 // C++ [class.friend]p5
8281 // A function can be defined in a friend declaration of a
8282 // class . . . . Such a function is implicitly inline.
8283 NewFD->setImplicitlyInline();
8284 }
8285
8286 // If this is a method defined in an __interface, and is not a constructor
8287 // or an overloaded operator, then set the pure flag (isVirtual will already
8288 // return true).
8289 if (const CXXRecordDecl *Parent =
8290 dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8291 if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8292 NewFD->setPure(true);
8293
8294 // C++ [class.union]p2
8295 // A union can have member functions, but not virtual functions.
8296 if (isVirtual && Parent->isUnion())
8297 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8298 }
8299
8300 SetNestedNameSpecifier(NewFD, D);
8301 isMemberSpecialization = false;
8302 isFunctionTemplateSpecialization = false;
8303 if (D.isInvalidType())
8304 NewFD->setInvalidDecl();
8305
8306 // Match up the template parameter lists with the scope specifier, then
8307 // determine whether we have a template or a template specialization.
8308 bool Invalid = false;
8309 if (TemplateParameterList *TemplateParams =
8310 MatchTemplateParametersToScopeSpecifier(
8311 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
8312 D.getCXXScopeSpec(),
8313 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8314 ? D.getName().TemplateId
8315 : nullptr,
8316 TemplateParamLists, isFriend, isMemberSpecialization,
8317 Invalid)) {
8318 if (TemplateParams->size() > 0) {
8319 // This is a function template
8320
8321 // Check that we can declare a template here.
8322 if (CheckTemplateDeclScope(S, TemplateParams))
8323 NewFD->setInvalidDecl();
8324
8325 // A destructor cannot be a template.
8326 if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8327 Diag(NewFD->getLocation(), diag::err_destructor_template);
8328 NewFD->setInvalidDecl();
8329 }
8330
8331 // If we're adding a template to a dependent context, we may need to
8332 // rebuilding some of the types used within the template parameter list,
8333 // now that we know what the current instantiation is.
8334 if (DC->isDependentContext()) {
8335 ContextRAII SavedContext(*this, DC);
8336 if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8337 Invalid = true;
8338 }
8339
8340 FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
8341 NewFD->getLocation(),
8342 Name, TemplateParams,
8343 NewFD);
8344 FunctionTemplate->setLexicalDeclContext(CurContext);
8345 NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8346
8347 // For source fidelity, store the other template param lists.
8348 if (TemplateParamLists.size() > 1) {
8349 NewFD->setTemplateParameterListsInfo(Context,
8350 TemplateParamLists.drop_back(1));
8351 }
8352 } else {
8353 // This is a function template specialization.
8354 isFunctionTemplateSpecialization = true;
8355 // For source fidelity, store all the template param lists.
8356 if (TemplateParamLists.size() > 0)
8357 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8358
8359 // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8360 if (isFriend) {
8361 // We want to remove the "template<>", found here.
8362 SourceRange RemoveRange = TemplateParams->getSourceRange();
8363
8364 // If we remove the template<> and the name is not a
8365 // template-id, we're actually silently creating a problem:
8366 // the friend declaration will refer to an untemplated decl,
8367 // and clearly the user wants a template specialization. So
8368 // we need to insert '<>' after the name.
8369 SourceLocation InsertLoc;
8370 if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8371 InsertLoc = D.getName().getSourceRange().getEnd();
8372 InsertLoc = getLocForEndOfToken(InsertLoc);
8373 }
8374
8375 Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8376 << Name << RemoveRange
8377 << FixItHint::CreateRemoval(RemoveRange)
8378 << FixItHint::CreateInsertion(InsertLoc, "<>");
8379 }
8380 }
8381 }
8382 else {
8383 // All template param lists were matched against the scope specifier:
8384 // this is NOT (an explicit specialization of) a template.
8385 if (TemplateParamLists.size() > 0)
8386 // For source fidelity, store all the template param lists.
8387 NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8388 }
8389
8390 if (Invalid) {
8391 NewFD->setInvalidDecl();
8392 if (FunctionTemplate)
8393 FunctionTemplate->setInvalidDecl();
8394 }
8395
8396 // C++ [dcl.fct.spec]p5:
8397 // The virtual specifier shall only be used in declarations of
8398 // nonstatic class member functions that appear within a
8399 // member-specification of a class declaration; see 10.3.
8400 //
8401 if (isVirtual && !NewFD->isInvalidDecl()) {
8402 if (!isVirtualOkay) {
8403 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8404 diag::err_virtual_non_function);
8405 } else if (!CurContext->isRecord()) {
8406 // 'virtual' was specified outside of the class.
8407 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8408 diag::err_virtual_out_of_class)
8409 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8410 } else if (NewFD->getDescribedFunctionTemplate()) {
8411 // C++ [temp.mem]p3:
8412 // A member function template shall not be virtual.
8413 Diag(D.getDeclSpec().getVirtualSpecLoc(),
8414 diag::err_virtual_member_function_template)
8415 << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8416 } else {
8417 // Okay: Add virtual to the method.
8418 NewFD->setVirtualAsWritten(true);
8419 }
8420
8421 if (getLangOpts().CPlusPlus14 &&
8422 NewFD->getReturnType()->isUndeducedType())
8423 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8424 }
8425
8426 if (getLangOpts().CPlusPlus14 &&
8427 (NewFD->isDependentContext() ||
8428 (isFriend && CurContext->isDependentContext())) &&
8429 NewFD->getReturnType()->isUndeducedType()) {
8430 // If the function template is referenced directly (for instance, as a
8431 // member of the current instantiation), pretend it has a dependent type.
8432 // This is not really justified by the standard, but is the only sane
8433 // thing to do.
8434 // FIXME: For a friend function, we have not marked the function as being
8435 // a friend yet, so 'isDependentContext' on the FD doesn't work.
8436 const FunctionProtoType *FPT =
8437 NewFD->getType()->castAs<FunctionProtoType>();
8438 QualType Result =
8439 SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8440 NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8441 FPT->getExtProtoInfo()));
8442 }
8443
8444 // C++ [dcl.fct.spec]p3:
8445 // The inline specifier shall not appear on a block scope function
8446 // declaration.
8447 if (isInline && !NewFD->isInvalidDecl()) {
8448 if (CurContext->isFunctionOrMethod()) {
8449 // 'inline' is not allowed on block scope function declaration.
8450 Diag(D.getDeclSpec().getInlineSpecLoc(),
8451 diag::err_inline_declaration_block_scope) << Name
8452 << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8453 }
8454 }
8455
8456 // C++ [dcl.fct.spec]p6:
8457 // The explicit specifier shall be used only in the declaration of a
8458 // constructor or conversion function within its class definition;
8459 // see 12.3.1 and 12.3.2.
8460 if (isExplicit && !NewFD->isInvalidDecl() &&
8461 !isa<CXXDeductionGuideDecl>(NewFD)) {
8462 if (!CurContext->isRecord()) {
8463 // 'explicit' was specified outside of the class.
8464 Diag(D.getDeclSpec().getExplicitSpecLoc(),
8465 diag::err_explicit_out_of_class)
8466 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8467 } else if (!isa<CXXConstructorDecl>(NewFD) &&
8468 !isa<CXXConversionDecl>(NewFD)) {
8469 // 'explicit' was specified on a function that wasn't a constructor
8470 // or conversion function.
8471 Diag(D.getDeclSpec().getExplicitSpecLoc(),
8472 diag::err_explicit_non_ctor_or_conv_function)
8473 << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8474 }
8475 }
8476
8477 if (isConstexpr) {
8478 // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8479 // are implicitly inline.
8480 NewFD->setImplicitlyInline();
8481
8482 // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8483 // be either constructors or to return a literal type. Therefore,
8484 // destructors cannot be declared constexpr.
8485 if (isa<CXXDestructorDecl>(NewFD))
8486 Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8487 }
8488
8489 // If __module_private__ was specified, mark the function accordingly.
8490 if (D.getDeclSpec().isModulePrivateSpecified()) {
8491 if (isFunctionTemplateSpecialization) {
8492 SourceLocation ModulePrivateLoc
8493 = D.getDeclSpec().getModulePrivateSpecLoc();
8494 Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8495 << 0
8496 << FixItHint::CreateRemoval(ModulePrivateLoc);
8497 } else {
8498 NewFD->setModulePrivate();
8499 if (FunctionTemplate)
8500 FunctionTemplate->setModulePrivate();
8501 }
8502 }
8503
8504 if (isFriend) {
8505 if (FunctionTemplate) {
8506 FunctionTemplate->setObjectOfFriendDecl();
8507 FunctionTemplate->setAccess(AS_public);
8508 }
8509 NewFD->setObjectOfFriendDecl();
8510 NewFD->setAccess(AS_public);
8511 }
8512
8513 // If a function is defined as defaulted or deleted, mark it as such now.
8514 // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8515 // definition kind to FDK_Definition.
8516 switch (D.getFunctionDefinitionKind()) {
8517 case FDK_Declaration:
8518 case FDK_Definition:
8519 break;
8520
8521 case FDK_Defaulted:
8522 NewFD->setDefaulted();
8523 break;
8524
8525 case FDK_Deleted:
8526 NewFD->setDeletedAsWritten();
8527 break;
8528 }
8529
8530 if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8531 D.isFunctionDefinition()) {
8532 // C++ [class.mfct]p2:
8533 // A member function may be defined (8.4) in its class definition, in
8534 // which case it is an inline member function (7.1.2)
8535 NewFD->setImplicitlyInline();
8536 }
8537
8538 if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8539 !CurContext->isRecord()) {
8540 // C++ [class.static]p1:
8541 // A data or function member of a class may be declared static
8542 // in a class definition, in which case it is a static member of
8543 // the class.
8544
8545 // Complain about the 'static' specifier if it's on an out-of-line
8546 // member function definition.
8547 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8548 diag::err_static_out_of_line)
8549 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8550 }
8551
8552 // C++11 [except.spec]p15:
8553 // A deallocation function with no exception-specification is treated
8554 // as if it were specified with noexcept(true).
8555 const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8556 if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8557 Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8558 getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8559 NewFD->setType(Context.getFunctionType(
8560 FPT->getReturnType(), FPT->getParamTypes(),
8561 FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8562 }
8563
8564 // Filter out previous declarations that don't match the scope.
8565 FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8566 D.getCXXScopeSpec().isNotEmpty() ||
8567 isMemberSpecialization ||
8568 isFunctionTemplateSpecialization);
8569
8570 // Handle GNU asm-label extension (encoded as an attribute).
8571 if (Expr *E = (Expr*) D.getAsmLabel()) {
8572 // The parser guarantees this is a string.
8573 StringLiteral *SE = cast<StringLiteral>(E);
8574 NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8575 SE->getString(), 0));
8576 } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8577 llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8578 ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8579 if (I != ExtnameUndeclaredIdentifiers.end()) {
8580 if (isDeclExternC(NewFD)) {
8581 NewFD->addAttr(I->second);
8582 ExtnameUndeclaredIdentifiers.erase(I);
8583 } else
8584 Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8585 << /*Variable*/0 << NewFD;
8586 }
8587 }
8588
8589 // Copy the parameter declarations from the declarator D to the function
8590 // declaration NewFD, if they are available. First scavenge them into Params.
8591 SmallVector<ParmVarDecl*, 16> Params;
8592 unsigned FTIIdx;
8593 if (D.isFunctionDeclarator(FTIIdx)) {
8594 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8595
8596 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8597 // function that takes no arguments, not a function that takes a
8598 // single void argument.
8599 // We let through "const void" here because Sema::GetTypeForDeclarator
8600 // already checks for that case.
8601 if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8602 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8603 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8604 assert(Param->getDeclContext() != NewFD && "Was set before ?")(static_cast <bool> (Param->getDeclContext() != NewFD
&& "Was set before ?") ? void (0) : __assert_fail ("Param->getDeclContext() != NewFD && \"Was set before ?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 8604, __extension__ __PRETTY_FUNCTION__))
;
8605 Param->setDeclContext(NewFD);
8606 Params.push_back(Param);
8607
8608 if (Param->isInvalidDecl())
8609 NewFD->setInvalidDecl();
8610 }
8611 }
8612
8613 if (!getLangOpts().CPlusPlus) {
8614 // In C, find all the tag declarations from the prototype and move them
8615 // into the function DeclContext. Remove them from the surrounding tag
8616 // injection context of the function, which is typically but not always
8617 // the TU.
8618 DeclContext *PrototypeTagContext =
8619 getTagInjectionContext(NewFD->getLexicalDeclContext());
8620 for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8621 auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8622
8623 // We don't want to reparent enumerators. Look at their parent enum
8624 // instead.
8625 if (!TD) {
8626 if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8627 TD = cast<EnumDecl>(ECD->getDeclContext());
8628 }
8629 if (!TD)
8630 continue;
8631 DeclContext *TagDC = TD->getLexicalDeclContext();
8632 if (!TagDC->containsDecl(TD))
8633 continue;
8634 TagDC->removeDecl(TD);
8635 TD->setDeclContext(NewFD);
8636 NewFD->addDecl(TD);
8637
8638 // Preserve the lexical DeclContext if it is not the surrounding tag
8639 // injection context of the FD. In this example, the semantic context of
8640 // E will be f and the lexical context will be S, while both the
8641 // semantic and lexical contexts of S will be f:
8642 // void f(struct S { enum E { a } f; } s);
8643 if (TagDC != PrototypeTagContext)
8644 TD->setLexicalDeclContext(TagDC);
8645 }
8646 }
8647 } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8648 // When we're declaring a function with a typedef, typeof, etc as in the
8649 // following example, we'll need to synthesize (unnamed)
8650 // parameters for use in the declaration.
8651 //
8652 // @code
8653 // typedef void fn(int);
8654 // fn f;
8655 // @endcode
8656
8657 // Synthesize a parameter for each argument type.
8658 for (const auto &AI : FT->param_types()) {
8659 ParmVarDecl *Param =
8660 BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8661 Param->setScopeInfo(0, Params.size());
8662 Params.push_back(Param);
8663 }
8664 } else {
8665 assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&(static_cast <bool> (R->isFunctionNoProtoType() &&
NewFD->getNumParams() == 0 && "Should not need args for typedef of non-prototype fn"
) ? void (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 8666, __extension__ __PRETTY_FUNCTION__))
8666 "Should not need args for typedef of non-prototype fn")(static_cast <bool> (R->isFunctionNoProtoType() &&
NewFD->getNumParams() == 0 && "Should not need args for typedef of non-prototype fn"
) ? void (0) : __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 8666, __extension__ __PRETTY_FUNCTION__))
;
8667 }
8668
8669 // Finally, we know we have the right number of parameters, install them.
8670 NewFD->setParams(Params);
8671
8672 if (D.getDeclSpec().isNoreturnSpecified())
8673 NewFD->addAttr(
8674 ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8675 Context, 0));
8676
8677 // Functions returning a variably modified type violate C99 6.7.5.2p2
8678 // because all functions have linkage.
8679 if (!NewFD->isInvalidDecl() &&
8680 NewFD->getReturnType()->isVariablyModifiedType()) {
8681 Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8682 NewFD->setInvalidDecl();
8683 }
8684
8685 // Apply an implicit SectionAttr if '#pragma clang section text' is active
8686 if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8687 !NewFD->hasAttr<SectionAttr>()) {
8688 NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8689 PragmaClangTextSection.SectionName,
8690 PragmaClangTextSection.PragmaLocation));
8691 }
8692
8693 // Apply an implicit SectionAttr if #pragma code_seg is active.
8694 if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8695 !NewFD->hasAttr<SectionAttr>()) {
8696 NewFD->addAttr(
8697 SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8698 CodeSegStack.CurrentValue->getString(),
8699 CodeSegStack.CurrentPragmaLocation));
8700 if (UnifySection(CodeSegStack.CurrentValue->getString(),
8701 ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8702 ASTContext::PSF_Read,
8703 NewFD))
8704 NewFD->dropAttr<SectionAttr>();
8705 }
8706
8707 // Handle attributes.
8708 ProcessDeclAttributes(S, NewFD, D);
8709
8710 if (getLangOpts().OpenCL) {
8711 // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8712 // type declaration will generate a compilation error.
8713 LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
8714 if (AddressSpace != LangAS::Default) {
8715 Diag(NewFD->getLocation(),
8716 diag::err_opencl_return_value_with_address_space);
8717 NewFD->setInvalidDecl();
8718 }
8719 }
8720
8721 if (!getLangOpts().CPlusPlus) {
8722 // Perform semantic checking on the function declaration.
8723 if (!NewFD->isInvalidDecl() && NewFD->isMain())
8724 CheckMain(NewFD, D.getDeclSpec());
8725
8726 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8727 CheckMSVCRTEntryPoint(NewFD);
8728
8729 if (!NewFD->isInvalidDecl())
8730 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8731 isMemberSpecialization));
8732 else if (!Previous.empty())
8733 // Recover gracefully from an invalid redeclaration.
8734 D.setRedeclaration(true);
8735 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration
() || Previous.getResultKind() != LookupResult::FoundOverloaded
) && "previous declaration set still overloaded") ? void
(0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 8737, __extension__ __PRETTY_FUNCTION__))
8736 Previous.getResultKind() != LookupResult::FoundOverloaded) &&(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration
() || Previous.getResultKind() != LookupResult::FoundOverloaded
) && "previous declaration set still overloaded") ? void
(0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 8737, __extension__ __PRETTY_FUNCTION__))
8737 "previous declaration set still overloaded")(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration
() || Previous.getResultKind() != LookupResult::FoundOverloaded
) && "previous declaration set still overloaded") ? void
(0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 8737, __extension__ __PRETTY_FUNCTION__))
;
8738
8739 // Diagnose no-prototype function declarations with calling conventions that
8740 // don't support variadic calls. Only do this in C and do it after merging
8741 // possibly prototyped redeclarations.
8742 const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8743 if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8744 CallingConv CC = FT->getExtInfo().getCC();
8745 if (!supportsVariadicCall(CC)) {
8746 // Windows system headers sometimes accidentally use stdcall without
8747 // (void) parameters, so we relax this to a warning.
8748 int DiagID =
8749 CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8750 Diag(NewFD->getLocation(), DiagID)
8751 << FunctionType::getNameForCallConv(CC);
8752 }
8753 }
8754 } else {
8755 // C++11 [replacement.functions]p3:
8756 // The program's definitions shall not be specified as inline.
8757 //
8758 // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8759 //
8760 // Suppress the diagnostic if the function is __attribute__((used)), since
8761 // that forces an external definition to be emitted.
8762 if (D.getDeclSpec().isInlineSpecified() &&
8763 NewFD->isReplaceableGlobalAllocationFunction() &&
8764 !NewFD->hasAttr<UsedAttr>())
8765 Diag(D.getDeclSpec().getInlineSpecLoc(),
8766 diag::ext_operator_new_delete_declared_inline)
8767 << NewFD->getDeclName();
8768
8769 // If the declarator is a template-id, translate the parser's template
8770 // argument list into our AST format.
8771 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
8772 TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8773 TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8774 TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8775 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8776 TemplateId->NumArgs);
8777 translateTemplateArguments(TemplateArgsPtr,
8778 TemplateArgs);
8779
8780 HasExplicitTemplateArgs = true;
8781
8782 if (NewFD->isInvalidDecl()) {
8783 HasExplicitTemplateArgs = false;
8784 } else if (FunctionTemplate) {
8785 // Function template with explicit template arguments.
8786 Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8787 << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8788
8789 HasExplicitTemplateArgs = false;
8790 } else {
8791 assert((isFunctionTemplateSpecialization ||(static_cast <bool> ((isFunctionTemplateSpecialization ||
D.getDeclSpec().isFriendSpecified()) && "should have a 'template<>' for this decl"
) ? void (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 8793, __extension__ __PRETTY_FUNCTION__))
8792 D.getDeclSpec().isFriendSpecified()) &&(static_cast <bool> ((isFunctionTemplateSpecialization ||
D.getDeclSpec().isFriendSpecified()) && "should have a 'template<>' for this decl"
) ? void (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 8793, __extension__ __PRETTY_FUNCTION__))
8793 "should have a 'template<>' for this decl")(static_cast <bool> ((isFunctionTemplateSpecialization ||
D.getDeclSpec().isFriendSpecified()) && "should have a 'template<>' for this decl"
) ? void (0) : __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 8793, __extension__ __PRETTY_FUNCTION__))
;
8794 // "friend void foo<>(int);" is an implicit specialization decl.
8795 isFunctionTemplateSpecialization = true;
8796 }
8797 } else if (isFriend && isFunctionTemplateSpecialization) {
8798 // This combination is only possible in a recovery case; the user
8799 // wrote something like:
8800 // template <> friend void foo(int);
8801 // which we're recovering from as if the user had written:
8802 // friend void foo<>(int);
8803 // Go ahead and fake up a template id.
8804 HasExplicitTemplateArgs = true;
8805 TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8806 TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8807 }
8808
8809 // We do not add HD attributes to specializations here because
8810 // they may have different constexpr-ness compared to their
8811 // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8812 // may end up with different effective targets. Instead, a
8813 // specialization inherits its target attributes from its template
8814 // in the CheckFunctionTemplateSpecialization() call below.
8815 if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8816 maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8817
8818 // If it's a friend (and only if it's a friend), it's possible
8819 // that either the specialized function type or the specialized
8820 // template is dependent, and therefore matching will fail. In
8821 // this case, don't check the specialization yet.
8822 bool InstantiationDependent = false;
8823 if (isFunctionTemplateSpecialization && isFriend &&
8824 (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8825 TemplateSpecializationType::anyDependentTemplateArguments(
8826 TemplateArgs,
8827 InstantiationDependent))) {
8828 assert(HasExplicitTemplateArgs &&(static_cast <bool> (HasExplicitTemplateArgs &&
"friend function specialization without template args") ? void
(0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 8829, __extension__ __PRETTY_FUNCTION__))
8829 "friend function specialization without template args")(static_cast <bool> (HasExplicitTemplateArgs &&
"friend function specialization without template args") ? void
(0) : __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 8829, __extension__ __PRETTY_FUNCTION__))
;
8830 if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8831 Previous))
8832 NewFD->setInvalidDecl();
8833 } else if (isFunctionTemplateSpecialization) {
8834 if (CurContext->isDependentContext() && CurContext->isRecord()
8835 && !isFriend) {
8836 isDependentClassScopeExplicitSpecialization = true;
8837 } else if (!NewFD->isInvalidDecl() &&
8838 CheckFunctionTemplateSpecialization(
8839 NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
8840 Previous))
8841 NewFD->setInvalidDecl();
8842
8843 // C++ [dcl.stc]p1:
8844 // A storage-class-specifier shall not be specified in an explicit
8845 // specialization (14.7.3)
8846 FunctionTemplateSpecializationInfo *Info =
8847 NewFD->getTemplateSpecializationInfo();
8848 if (Info && SC != SC_None) {
8849 if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8850 Diag(NewFD->getLocation(),
8851 diag::err_explicit_specialization_inconsistent_storage_class)
8852 << SC
8853 << FixItHint::CreateRemoval(
8854 D.getDeclSpec().getStorageClassSpecLoc());
8855
8856 else
8857 Diag(NewFD->getLocation(),
8858 diag::ext_explicit_specialization_storage_class)
8859 << FixItHint::CreateRemoval(
8860 D.getDeclSpec().getStorageClassSpecLoc());
8861 }
8862 } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8863 if (CheckMemberSpecialization(NewFD, Previous))
8864 NewFD->setInvalidDecl();
8865 }
8866
8867 // Perform semantic checking on the function declaration.
8868 if (!isDependentClassScopeExplicitSpecialization) {
8869 if (!NewFD->isInvalidDecl() && NewFD->isMain())
8870 CheckMain(NewFD, D.getDeclSpec());
8871
8872 if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8873 CheckMSVCRTEntryPoint(NewFD);
8874
8875 if (!NewFD->isInvalidDecl())
8876 D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8877 isMemberSpecialization));
8878 else if (!Previous.empty())
8879 // Recover gracefully from an invalid redeclaration.
8880 D.setRedeclaration(true);
8881 }
8882
8883 assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration
() || Previous.getResultKind() != LookupResult::FoundOverloaded
) && "previous declaration set still overloaded") ? void
(0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 8885, __extension__ __PRETTY_FUNCTION__))
8884 Previous.getResultKind() != LookupResult::FoundOverloaded) &&(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration
() || Previous.getResultKind() != LookupResult::FoundOverloaded
) && "previous declaration set still overloaded") ? void
(0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 8885, __extension__ __PRETTY_FUNCTION__))
8885 "previous declaration set still overloaded")(static_cast <bool> ((NewFD->isInvalidDecl() || !D.isRedeclaration
() || Previous.getResultKind() != LookupResult::FoundOverloaded
) && "previous declaration set still overloaded") ? void
(0) : __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult::FoundOverloaded) && \"previous declaration set still overloaded\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 8885, __extension__ __PRETTY_FUNCTION__))
;
8886
8887 NamedDecl *PrincipalDecl = (FunctionTemplate
8888 ? cast<NamedDecl>(FunctionTemplate)
8889 : NewFD);
8890
8891 if (isFriend && NewFD->getPreviousDecl()) {
8892 AccessSpecifier Access = AS_public;
8893 if (!NewFD->isInvalidDecl())
8894 Access = NewFD->getPreviousDecl()->getAccess();
8895
8896 NewFD->setAccess(Access);
8897 if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8898 }
8899
8900 if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8901 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8902 PrincipalDecl->setNonMemberOperator();
8903
8904 // If we have a function template, check the template parameter
8905 // list. This will check and merge default template arguments.
8906 if (FunctionTemplate) {
8907 FunctionTemplateDecl *PrevTemplate =
8908 FunctionTemplate->getPreviousDecl();
8909 CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8910 PrevTemplate ? PrevTemplate->getTemplateParameters()
8911 : nullptr,
8912 D.getDeclSpec().isFriendSpecified()
8913 ? (D.isFunctionDefinition()
8914 ? TPC_FriendFunctionTemplateDefinition
8915 : TPC_FriendFunctionTemplate)
8916 : (D.getCXXScopeSpec().isSet() &&
8917 DC && DC->isRecord() &&
8918 DC->isDependentContext())
8919 ? TPC_ClassTemplateMember
8920 : TPC_FunctionTemplate);
8921 }
8922
8923 if (NewFD->isInvalidDecl()) {
8924 // Ignore all the rest of this.
8925 } else if (!D.isRedeclaration()) {
8926 struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8927 AddToScope };
8928 // Fake up an access specifier if it's supposed to be a class member.
8929 if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8930 NewFD->setAccess(AS_public);
8931
8932 // Qualified decls generally require a previous declaration.
8933 if (D.getCXXScopeSpec().isSet()) {
8934 // ...with the major exception of templated-scope or
8935 // dependent-scope friend declarations.
8936
8937 // TODO: we currently also suppress this check in dependent
8938 // contexts because (1) the parameter depth will be off when
8939 // matching friend templates and (2) we might actually be
8940 // selecting a friend based on a dependent factor. But there
8941 // are situations where these conditions don't apply and we
8942 // can actually do this check immediately.
8943 if (isFriend &&
8944 (TemplateParamLists.size() ||
8945 D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8946 CurContext->isDependentContext())) {
8947 // ignore these
8948 } else {
8949 // The user tried to provide an out-of-line definition for a
8950 // function that is a member of a class or namespace, but there
8951 // was no such member function declared (C++ [class.mfct]p2,
8952 // C++ [namespace.memdef]p2). For example:
8953 //
8954 // class X {
8955 // void f() const;
8956 // };
8957 //
8958 // void X::f() { } // ill-formed
8959 //
8960 // Complain about this problem, and attempt to suggest close
8961 // matches (e.g., those that differ only in cv-qualifiers and
8962 // whether the parameter types are references).
8963
8964 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8965 *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8966 AddToScope = ExtraArgs.AddToScope;
8967 return Result;
8968 }
8969 }
8970
8971 // Unqualified local friend declarations are required to resolve
8972 // to something.
8973 } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8974 if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8975 *this, Previous, NewFD, ExtraArgs, true, S)) {
8976 AddToScope = ExtraArgs.AddToScope;
8977 return Result;
8978 }
8979 }
8980 } else if (!D.isFunctionDefinition() &&
8981 isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8982 !isFriend && !isFunctionTemplateSpecialization &&
8983 !isMemberSpecialization) {
8984 // An out-of-line member function declaration must also be a
8985 // definition (C++ [class.mfct]p2).
8986 // Note that this is not the case for explicit specializations of
8987 // function templates or member functions of class templates, per
8988 // C++ [temp.expl.spec]p2. We also allow these declarations as an
8989 // extension for compatibility with old SWIG code which likes to
8990 // generate them.
8991 Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8992 << D.getCXXScopeSpec().getRange();
8993 }
8994 }
8995
8996 ProcessPragmaWeak(S, NewFD);
8997 checkAttributesAfterMerging(*this, *NewFD);
8998
8999 AddKnownFunctionAttributes(NewFD);
9000
9001 if (NewFD->hasAttr<OverloadableAttr>() &&
9002 !NewFD->getType()->getAs<FunctionProtoType>()) {
9003 Diag(NewFD->getLocation(),
9004 diag::err_attribute_overloadable_no_prototype)
9005 << NewFD;
9006
9007 // Turn this into a variadic function with no parameters.
9008 const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9009 FunctionProtoType::ExtProtoInfo EPI(
9010 Context.getDefaultCallingConvention(true, false));
9011 EPI.Variadic = true;
9012 EPI.ExtInfo = FT->getExtInfo();
9013
9014 QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9015 NewFD->setType(R);
9016 }
9017
9018 // If there's a #pragma GCC visibility in scope, and this isn't a class
9019 // member, set the visibility of this function.
9020 if (!DC->isRecord() && NewFD->isExternallyVisible())
9021 AddPushedVisibilityAttribute(NewFD);
9022
9023 // If there's a #pragma clang arc_cf_code_audited in scope, consider
9024 // marking the function.
9025 AddCFAuditedAttribute(NewFD);
9026
9027 // If this is a function definition, check if we have to apply optnone due to
9028 // a pragma.
9029 if(D.isFunctionDefinition())
9030 AddRangeBasedOptnone(NewFD);
9031
9032 // If this is the first declaration of an extern C variable, update
9033 // the map of such variables.
9034 if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9035 isIncompleteDeclExternC(*this, NewFD))
9036 RegisterLocallyScopedExternCDecl(NewFD, S);
9037
9038 // Set this FunctionDecl's range up to the right paren.
9039 NewFD->setRangeEnd(D.getSourceRange().getEnd());
9040
9041 if (D.isRedeclaration() && !Previous.empty()) {
9042 NamedDecl *Prev = Previous.getRepresentativeDecl();
9043 checkDLLAttributeRedeclaration(*this, Prev, NewFD,
9044 isMemberSpecialization ||
9045 isFunctionTemplateSpecialization,
9046 D.isFunctionDefinition());
9047 }
9048
9049 if (getLangOpts().CUDA) {
9050 IdentifierInfo *II = NewFD->getIdentifier();
9051 if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
9052 NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9053 if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9054 Diag(NewFD->getLocation(), diag::err_config_scalar_return);
9055
9056 Context.setcudaConfigureCallDecl(NewFD);
9057 }
9058
9059 // Variadic functions, other than a *declaration* of printf, are not allowed
9060 // in device-side CUDA code, unless someone passed
9061 // -fcuda-allow-variadic-functions.
9062 if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9063 (NewFD->hasAttr<CUDADeviceAttr>() ||
9064 NewFD->hasAttr<CUDAGlobalAttr>()) &&
9065 !(II && II->isStr("printf") && NewFD->isExternC() &&
9066 !D.isFunctionDefinition())) {
9067 Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9068 }
9069 }
9070
9071 MarkUnusedFileScopedDecl(NewFD);
9072
9073 if (getLangOpts().CPlusPlus) {
9074 if (FunctionTemplate) {
9075 if (NewFD->isInvalidDecl())
9076 FunctionTemplate->setInvalidDecl();
9077 return FunctionTemplate;
9078 }
9079
9080 if (isMemberSpecialization && !NewFD->isInvalidDecl())
9081 CompleteMemberSpecialization(NewFD, Previous);
9082 }
9083
9084 if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9085 // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9086 if ((getLangOpts().OpenCLVersion >= 120)
9087 && (SC == SC_Static)) {
9088 Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9089 D.setInvalidType();
9090 }
9091
9092 // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9093 if (!NewFD->getReturnType()->isVoidType()) {
9094 SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9095 Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9096 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9097 : FixItHint());
9098 D.setInvalidType();
9099 }
9100
9101 llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9102 for (auto Param : NewFD->parameters())
9103 checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9104 }
9105 for (const ParmVarDecl *Param : NewFD->parameters()) {
9106 QualType PT = Param->getType();
9107
9108 // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9109 // types.
9110 if (getLangOpts().OpenCLVersion >= 200) {
9111 if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9112 QualType ElemTy = PipeTy->getElementType();
9113 if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9114 Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9115 D.setInvalidType();
9116 }
9117 }
9118 }
9119 }
9120
9121 // Here we have an function template explicit specialization at class scope.
9122 // The actual specialization will be postponed to template instatiation
9123 // time via the ClassScopeFunctionSpecializationDecl node.
9124 if (isDependentClassScopeExplicitSpecialization) {
9125 ClassScopeFunctionSpecializationDecl *NewSpec =
9126 ClassScopeFunctionSpecializationDecl::Create(
9127 Context, CurContext, NewFD->getLocation(),
9128 cast<CXXMethodDecl>(NewFD),
9129 HasExplicitTemplateArgs, TemplateArgs);
9130 CurContext->addDecl(NewSpec);
9131 AddToScope = false;
9132 }
9133
9134 return NewFD;
9135}
9136
9137/// \brief Checks if the new declaration declared in dependent context must be
9138/// put in the same redeclaration chain as the specified declaration.
9139///
9140/// \param D Declaration that is checked.
9141/// \param PrevDecl Previous declaration found with proper lookup method for the
9142/// same declaration name.
9143/// \returns True if D must be added to the redeclaration chain which PrevDecl
9144/// belongs to.
9145///
9146bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
9147 // Any declarations should be put into redeclaration chains except for
9148 // friend declaration in a dependent context that names a function in
9149 // namespace scope.
9150 //
9151 // This allows to compile code like:
9152 //
9153 // void func();
9154 // template<typename T> class C1 { friend void func() { } };
9155 // template<typename T> class C2 { friend void func() { } };
9156 //
9157 // This code snippet is a valid code unless both templates are instantiated.
9158 return !(D->getLexicalDeclContext()->isDependentContext() &&
9159 D->getDeclContext()->isFileContext() &&
9160 D->getFriendObjectKind() != Decl::FOK_None);
9161}
9162
9163/// \brief Check the target attribute of the function for MultiVersion
9164/// validity.
9165///
9166/// Returns true if there was an error, false otherwise.
9167static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
9168 const auto *TA = FD->getAttr<TargetAttr>();
9169 assert(TA && "MultiVersion Candidate requires a target attribute")(static_cast <bool> (TA && "MultiVersion Candidate requires a target attribute"
) ? void (0) : __assert_fail ("TA && \"MultiVersion Candidate requires a target attribute\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 9169, __extension__ __PRETTY_FUNCTION__))
;
9170 TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9171 const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9172 enum ErrType { Feature = 0, Architecture = 1 };
9173
9174 if (!ParseInfo.Architecture.empty() &&
9175 !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9176 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9177 << Architecture << ParseInfo.Architecture;
9178 return true;
9179 }
9180
9181 for (const auto &Feat : ParseInfo.Features) {
9182 auto BareFeat = StringRef{Feat}.substr(1);
9183 if (Feat[0] == '-') {
9184 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9185 << Feature << ("no-" + BareFeat).str();
9186 return true;
9187 }
9188
9189 if (!TargetInfo.validateCpuSupports(BareFeat) ||
9190 !TargetInfo.isValidFeatureName(BareFeat)) {
9191 S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9192 << Feature << BareFeat;
9193 return true;
9194 }
9195 }
9196 return false;
9197}
9198
9199static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD,
9200 const FunctionDecl *NewFD,
9201 bool CausesMV) {
9202 enum DoesntSupport {
9203 FuncTemplates = 0,
9204 VirtFuncs = 1,
9205 DeducedReturn = 2,
9206 Constructors = 3,
9207 Destructors = 4,
9208 DeletedFuncs = 5,
9209 DefaultedFuncs = 6
9210 };
9211 enum Different {
9212 CallingConv = 0,
9213 ReturnType = 1,
9214 ConstexprSpec = 2,
9215 InlineSpec = 3,
9216 StorageClass = 4,
9217 Linkage = 5
9218 };
9219
9220 // For now, disallow all other attributes. These should be opt-in, but
9221 // an analysis of all of them is a future FIXME.
9222 if (CausesMV && OldFD &&
9223 std::distance(OldFD->attr_begin(), OldFD->attr_end()) != 1) {
9224 S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs);
9225 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9226 return true;
9227 }
9228
9229 if (std::distance(NewFD->attr_begin(), NewFD->attr_end()) != 1)
9230 return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs);
9231
9232 if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9233 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9234 << FuncTemplates;
9235
9236 if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9237 if (NewCXXFD->isVirtual())
9238 return S.Diag(NewCXXFD->getLocation(),
9239 diag::err_multiversion_doesnt_support)
9240 << VirtFuncs;
9241
9242 if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
9243 return S.Diag(NewCXXCtor->getLocation(),
9244 diag::err_multiversion_doesnt_support)
9245 << Constructors;
9246
9247 if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
9248 return S.Diag(NewCXXDtor->getLocation(),
9249 diag::err_multiversion_doesnt_support)
9250 << Destructors;
9251 }
9252
9253 if (NewFD->isDeleted())
9254 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9255 << DeletedFuncs;
9256
9257 if (NewFD->isDefaulted())
9258 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9259 << DefaultedFuncs;
9260
9261 QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
9262 const auto *NewType = cast<FunctionType>(NewQType);
9263 QualType NewReturnType = NewType->getReturnType();
9264
9265 if (NewReturnType->isUndeducedType())
9266 return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9267 << DeducedReturn;
9268
9269 // Only allow transition to MultiVersion if it hasn't been used.
9270 if (OldFD && CausesMV && OldFD->isUsed(false))
9271 return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9272
9273 // Ensure the return type is identical.
9274 if (OldFD) {
9275 QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
9276 const auto *OldType = cast<FunctionType>(OldQType);
9277 FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9278 FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9279
9280 if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9281 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9282 << CallingConv;
9283
9284 QualType OldReturnType = OldType->getReturnType();
9285
9286 if (OldReturnType != NewReturnType)
9287 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9288 << ReturnType;
9289
9290 if (OldFD->isConstexpr() != NewFD->isConstexpr())
9291 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9292 << ConstexprSpec;
9293
9294 if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9295 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9296 << InlineSpec;
9297
9298 if (OldFD->getStorageClass() != NewFD->getStorageClass())
9299 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9300 << StorageClass;
9301
9302 if (OldFD->isExternC() != NewFD->isExternC())
9303 return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9304 << Linkage;
9305
9306 if (S.CheckEquivalentExceptionSpec(
9307 OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9308 NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9309 return true;
9310 }
9311 return false;
9312}
9313
9314/// \brief Check the validity of a mulitversion function declaration.
9315/// Also sets the multiversion'ness' of the function itself.
9316///
9317/// This sets NewFD->isInvalidDecl() to true if there was an error.
9318///
9319/// Returns true if there was an error, false otherwise.
9320static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD,
9321 bool &Redeclaration, NamedDecl *&OldDecl,
9322 bool &MergeTypeWithPrevious,
9323 LookupResult &Previous) {
9324 const auto *NewTA = NewFD->getAttr<TargetAttr>();
9325 if (NewFD->isMain()) {
9326 if (NewTA && NewTA->isDefaultVersion()) {
9327 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
9328 NewFD->setInvalidDecl();
9329 return true;
9330 }
9331 return false;
9332 }
9333
9334 // If there is no matching previous decl, only 'default' can
9335 // cause MultiVersioning.
9336 if (!OldDecl) {
9337 if (NewTA && NewTA->isDefaultVersion()) {
9338 if (!NewFD->getType()->getAs<FunctionProtoType>()) {
9339 S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
9340 NewFD->setInvalidDecl();
9341 return true;
9342 }
9343 if (CheckMultiVersionAdditionalRules(S, nullptr, NewFD, true)) {
9344 NewFD->setInvalidDecl();
9345 return true;
9346 }
9347 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9348 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9349 NewFD->setInvalidDecl();
9350 return true;
9351 }
9352
9353 NewFD->setIsMultiVersion();
9354 }
9355 return false;
9356 }
9357
9358 if (OldDecl->getDeclContext()->getRedeclContext() !=
9359 NewFD->getDeclContext()->getRedeclContext())
9360 return false;
9361
9362 FunctionDecl *OldFD = OldDecl->getAsFunction();
9363 // Unresolved 'using' statements (the other way OldDecl can be not a function)
9364 // likely cannot cause a problem here.
9365 if (!OldFD)
9366 return false;
9367
9368 if (!OldFD->isMultiVersion() && !NewTA)
9369 return false;
9370
9371 if (OldFD->isMultiVersion() && !NewTA) {
9372 S.Diag(NewFD->getLocation(), diag::err_target_required_in_redecl);
9373 NewFD->setInvalidDecl();
9374 return true;
9375 }
9376
9377 TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9378 // Sort order doesn't matter, it just needs to be consistent.
9379 llvm::sort(NewParsed.Features.begin(), NewParsed.Features.end());
9380
9381 const auto *OldTA = OldFD->getAttr<TargetAttr>();
9382 if (!OldFD->isMultiVersion()) {
9383 // If the old decl is NOT MultiVersioned yet, and we don't cause that
9384 // to change, this is a simple redeclaration.
9385 if (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr())
9386 return false;
9387
9388 // Otherwise, this decl causes MultiVersioning.
9389 if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9390 S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9391 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9392 NewFD->setInvalidDecl();
9393 return true;
9394 }
9395
9396 if (!OldFD->getType()->getAs<FunctionProtoType>()) {
9397 S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
9398 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9399 NewFD->setInvalidDecl();
9400 return true;
9401 }
9402
9403 if (CheckMultiVersionValue(S, NewFD)) {
9404 NewFD->setInvalidDecl();
9405 return true;
9406 }
9407
9408 if (CheckMultiVersionValue(S, OldFD)) {
9409 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9410 NewFD->setInvalidDecl();
9411 return true;
9412 }
9413
9414 TargetAttr::ParsedTargetAttr OldParsed =
9415 OldTA->parse(std::less<std::string>());
9416
9417 if (OldParsed == NewParsed) {
9418 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9419 S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9420 NewFD->setInvalidDecl();
9421 return true;
9422 }
9423
9424 for (const auto *FD : OldFD->redecls()) {
9425 const auto *CurTA = FD->getAttr<TargetAttr>();
9426 if (!CurTA || CurTA->isInherited()) {
9427 S.Diag(FD->getLocation(), diag::err_target_required_in_redecl);
9428 S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9429 NewFD->setInvalidDecl();
9430 return true;
9431 }
9432 }
9433
9434 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true)) {
9435 NewFD->setInvalidDecl();
9436 return true;
9437 }
9438
9439 OldFD->setIsMultiVersion();
9440 NewFD->setIsMultiVersion();
9441 Redeclaration = false;
9442 MergeTypeWithPrevious = false;
9443 OldDecl = nullptr;
9444 Previous.clear();
9445 return false;
9446 }
9447
9448 bool UseMemberUsingDeclRules =
9449 S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
9450
9451 // Next, check ALL non-overloads to see if this is a redeclaration of a
9452 // previous member of the MultiVersion set.
9453 for (NamedDecl *ND : Previous) {
9454 FunctionDecl *CurFD = ND->getAsFunction();
9455 if (!CurFD)
9456 continue;
9457 if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
9458 continue;
9459
9460 const auto *CurTA = CurFD->getAttr<TargetAttr>();
9461 if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
9462 NewFD->setIsMultiVersion();
9463 Redeclaration = true;
9464 OldDecl = ND;
9465 return false;
9466 }
9467
9468 TargetAttr::ParsedTargetAttr CurParsed =
9469 CurTA->parse(std::less<std::string>());
9470
9471 if (CurParsed == NewParsed) {
9472 S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9473 S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9474 NewFD->setInvalidDecl();
9475 return true;
9476 }
9477 }
9478
9479 // Else, this is simply a non-redecl case.
9480 if (CheckMultiVersionValue(S, NewFD)) {
9481 NewFD->setInvalidDecl();
9482 return true;
9483 }
9484
9485 if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, false)) {
9486 NewFD->setInvalidDecl();
9487 return true;
9488 }
9489
9490 NewFD->setIsMultiVersion();
9491 Redeclaration = false;
9492 MergeTypeWithPrevious = false;
9493 OldDecl = nullptr;
9494 Previous.clear();
9495 return false;
9496}
9497
9498/// \brief Perform semantic checking of a new function declaration.
9499///
9500/// Performs semantic analysis of the new function declaration
9501/// NewFD. This routine performs all semantic checking that does not
9502/// require the actual declarator involved in the declaration, and is
9503/// used both for the declaration of functions as they are parsed
9504/// (called via ActOnDeclarator) and for the declaration of functions
9505/// that have been instantiated via C++ template instantiation (called
9506/// via InstantiateDecl).
9507///
9508/// \param IsMemberSpecialization whether this new function declaration is
9509/// a member specialization (that replaces any definition provided by the
9510/// previous declaration).
9511///
9512/// This sets NewFD->isInvalidDecl() to true if there was an error.
9513///
9514/// \returns true if the function declaration is a redeclaration.
9515bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
9516 LookupResult &Previous,
9517 bool IsMemberSpecialization) {
9518 assert(!NewFD->getReturnType()->isVariablyModifiedType() &&(static_cast <bool> (!NewFD->getReturnType()->isVariablyModifiedType
() && "Variably modified return types are not handled here"
) ? void (0) : __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 9519, __extension__ __PRETTY_FUNCTION__))
9519 "Variably modified return types are not handled here")(static_cast <bool> (!NewFD->getReturnType()->isVariablyModifiedType
() && "Variably modified return types are not handled here"
) ? void (0) : __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 9519, __extension__ __PRETTY_FUNCTION__))
;
9520
9521 // Determine whether the type of this function should be merged with
9522 // a previous visible declaration. This never happens for functions in C++,
9523 // and always happens in C if the previous declaration was visible.
9524 bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9525 !Previous.isShadowed();
9526
9527 bool Redeclaration = false;
9528 NamedDecl *OldDecl = nullptr;
9529 bool MayNeedOverloadableChecks = false;
9530
9531 // Merge or overload the declaration with an existing declaration of
9532 // the same name, if appropriate.
9533 if (!Previous.empty()) {
9534 // Determine whether NewFD is an overload of PrevDecl or
9535 // a declaration that requires merging. If it's an overload,
9536 // there's no more work to do here; we'll just add the new
9537 // function to the scope.
9538 if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
9539 NamedDecl *Candidate = Previous.getRepresentativeDecl();
9540 if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
9541 Redeclaration = true;
9542 OldDecl = Candidate;
9543 }
9544 } else {
9545 MayNeedOverloadableChecks = true;
9546 switch (CheckOverload(S, NewFD, Previous, OldDecl,
9547 /*NewIsUsingDecl*/ false)) {
9548 case Ovl_Match:
9549 Redeclaration = true;
9550 break;
9551
9552 case Ovl_NonFunction:
9553 Redeclaration = true;
9554 break;
9555
9556 case Ovl_Overload:
9557 Redeclaration = false;
9558 break;
9559 }
9560 }
9561 }
9562
9563 // Check for a previous extern "C" declaration with this name.
9564 if (!Redeclaration &&
9565 checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
9566 if (!Previous.empty()) {
9567 // This is an extern "C" declaration with the same name as a previous
9568 // declaration, and thus redeclares that entity...
9569 Redeclaration = true;
9570 OldDecl = Previous.getFoundDecl();
9571 MergeTypeWithPrevious = false;
9572
9573 // ... except in the presence of __attribute__((overloadable)).
9574 if (OldDecl->hasAttr<OverloadableAttr>() ||
9575 NewFD->hasAttr<OverloadableAttr>()) {
9576 if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
9577 MayNeedOverloadableChecks = true;
9578 Redeclaration = false;
9579 OldDecl = nullptr;
9580 }
9581 }
9582 }
9583 }
9584
9585 if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl,
9586 MergeTypeWithPrevious, Previous))
9587 return Redeclaration;
9588
9589 // C++11 [dcl.constexpr]p8:
9590 // A constexpr specifier for a non-static member function that is not
9591 // a constructor declares that member function to be const.
9592 //
9593 // This needs to be delayed until we know whether this is an out-of-line
9594 // definition of a static member function.
9595 //
9596 // This rule is not present in C++1y, so we produce a backwards
9597 // compatibility warning whenever it happens in C++11.
9598 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
9599 if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
9600 !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
9601 (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
9602 CXXMethodDecl *OldMD = nullptr;
9603 if (OldDecl)
9604 OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
9605 if (!OldMD || !OldMD->isStatic()) {
9606 const FunctionProtoType *FPT =
9607 MD->getType()->castAs<FunctionProtoType>();
9608 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9609 EPI.TypeQuals |= Qualifiers::Const;
9610 MD->setType(Context.getFunctionType(FPT->getReturnType(),
9611 FPT->getParamTypes(), EPI));
9612
9613 // Warn that we did this, if we're not performing template instantiation.
9614 // In that case, we'll have warned already when the template was defined.
9615 if (!inTemplateInstantiation()) {
9616 SourceLocation AddConstLoc;
9617 if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
9618 .IgnoreParens().getAs<FunctionTypeLoc>())
9619 AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
9620
9621 Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
9622 << FixItHint::CreateInsertion(AddConstLoc, " const");
9623 }
9624 }
9625 }
9626
9627 if (Redeclaration) {
9628 // NewFD and OldDecl represent declarations that need to be
9629 // merged.
9630 if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
9631 NewFD->setInvalidDecl();
9632 return Redeclaration;
9633 }
9634
9635 Previous.clear();
9636 Previous.addDecl(OldDecl);
9637
9638 if (FunctionTemplateDecl *OldTemplateDecl =
9639 dyn_cast<FunctionTemplateDecl>(OldDecl)) {
9640 auto *OldFD = OldTemplateDecl->getTemplatedDecl();
9641 NewFD->setPreviousDeclaration(OldFD);
9642 adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
9643 FunctionTemplateDecl *NewTemplateDecl
9644 = NewFD->getDescribedFunctionTemplate();
9645 assert(NewTemplateDecl && "Template/non-template mismatch")(static_cast <bool> (NewTemplateDecl && "Template/non-template mismatch"
) ? void (0) : __assert_fail ("NewTemplateDecl && \"Template/non-template mismatch\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 9645, __extension__ __PRETTY_FUNCTION__))
;
9646 if (NewFD->isCXXClassMember()) {
9647 NewFD->setAccess(OldTemplateDecl->getAccess());
9648 NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
9649 }
9650
9651 // If this is an explicit specialization of a member that is a function
9652 // template, mark it as a member specialization.
9653 if (IsMemberSpecialization &&
9654 NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
9655 NewTemplateDecl->setMemberSpecialization();
9656 assert(OldTemplateDecl->isMemberSpecialization())(static_cast <bool> (OldTemplateDecl->isMemberSpecialization
()) ? void (0) : __assert_fail ("OldTemplateDecl->isMemberSpecialization()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 9656, __extension__ __PRETTY_FUNCTION__))
;
9657 // Explicit specializations of a member template do not inherit deleted
9658 // status from the parent member template that they are specializing.
9659 if (OldFD->isDeleted()) {
9660 // FIXME: This assert will not hold in the presence of modules.
9661 assert(OldFD->getCanonicalDecl() == OldFD)(static_cast <bool> (OldFD->getCanonicalDecl() == OldFD
) ? void (0) : __assert_fail ("OldFD->getCanonicalDecl() == OldFD"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 9661, __extension__ __PRETTY_FUNCTION__))
;
9662 // FIXME: We need an update record for this AST mutation.
9663 OldFD->setDeletedAsWritten(false);
9664 }
9665 }
9666
9667 } else {
9668 if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9669 auto *OldFD = cast<FunctionDecl>(OldDecl);
9670 // This needs to happen first so that 'inline' propagates.
9671 NewFD->setPreviousDeclaration(OldFD);
9672 adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
9673 if (NewFD->isCXXClassMember())
9674 NewFD->setAccess(OldFD->getAccess());
9675 }
9676 }
9677 } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
9678 !NewFD->getAttr<OverloadableAttr>()) {
9679 assert((Previous.empty() ||(static_cast <bool> ((Previous.empty() || llvm::any_of(
Previous, [](const NamedDecl *ND) { return ND->hasAttr<
OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present"
) ? void (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 9684, __extension__ __PRETTY_FUNCTION__))
9680 llvm::any_of(Previous,(static_cast <bool> ((Previous.empty() || llvm::any_of(
Previous, [](const NamedDecl *ND) { return ND->hasAttr<
OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present"
) ? void (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 9684, __extension__ __PRETTY_FUNCTION__))
9681 [](const NamedDecl *ND) {(static_cast <bool> ((Previous.empty() || llvm::any_of(
Previous, [](const NamedDecl *ND) { return ND->hasAttr<
OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present"
) ? void (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 9684, __extension__ __PRETTY_FUNCTION__))
9682 return ND->hasAttr<OverloadableAttr>();(static_cast <bool> ((Previous.empty() || llvm::any_of(
Previous, [](const NamedDecl *ND) { return ND->hasAttr<
OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present"
) ? void (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 9684, __extension__ __PRETTY_FUNCTION__))
9683 })) &&(static_cast <bool> ((Previous.empty() || llvm::any_of(
Previous, [](const NamedDecl *ND) { return ND->hasAttr<
OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present"
) ? void (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 9684, __extension__ __PRETTY_FUNCTION__))
9684 "Non-redecls shouldn't happen without overloadable present")(static_cast <bool> ((Previous.empty() || llvm::any_of(
Previous, [](const NamedDecl *ND) { return ND->hasAttr<
OverloadableAttr>(); })) && "Non-redecls shouldn't happen without overloadable present"
) ? void (0) : __assert_fail ("(Previous.empty() || llvm::any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr<OverloadableAttr>(); })) && \"Non-redecls shouldn't happen without overloadable present\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 9684, __extension__ __PRETTY_FUNCTION__))
;
9685
9686 auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
9687 const auto *FD = dyn_cast<FunctionDecl>(ND);
9688 return FD && !FD->hasAttr<OverloadableAttr>();
9689 });
9690
9691 if (OtherUnmarkedIter != Previous.end()) {
9692 Diag(NewFD->getLocation(),
9693 diag::err_attribute_overloadable_multiple_unmarked_overloads);
9694 Diag((*OtherUnmarkedIter)->getLocation(),
9695 diag::note_attribute_overloadable_prev_overload)
9696 << false;
9697
9698 NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
9699 }
9700 }
9701
9702 // Semantic checking for this function declaration (in isolation).
9703
9704 if (getLangOpts().CPlusPlus) {
9705 // C++-specific checks.
9706 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9707 CheckConstructor(Constructor);
9708 } else if (CXXDestructorDecl *Destructor =
9709 dyn_cast<CXXDestructorDecl>(NewFD)) {
9710 CXXRecordDecl *Record = Destructor->getParent();
9711 QualType ClassType = Context.getTypeDeclType(Record);
9712
9713 // FIXME: Shouldn't we be able to perform this check even when the class
9714 // type is dependent? Both gcc and edg can handle that.
9715 if (!ClassType->isDependentType()) {
9716 DeclarationName Name
9717 = Context.DeclarationNames.getCXXDestructorName(
9718 Context.getCanonicalType(ClassType));
9719 if (NewFD->getDeclName() != Name) {
9720 Diag(NewFD->getLocation(), diag::err_destructor_name);
9721 NewFD->setInvalidDecl();
9722 return Redeclaration;
9723 }
9724 }
9725 } else if (CXXConversionDecl *Conversion
9726 = dyn_cast<CXXConversionDecl>(NewFD)) {
9727 ActOnConversionDeclarator(Conversion);
9728 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
9729 if (auto *TD = Guide->getDescribedFunctionTemplate())
9730 CheckDeductionGuideTemplate(TD);
9731
9732 // A deduction guide is not on the list of entities that can be
9733 // explicitly specialized.
9734 if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
9735 Diag(Guide->getLocStart(), diag::err_deduction_guide_specialized)
9736 << /*explicit specialization*/ 1;
9737 }
9738
9739 // Find any virtual functions that this function overrides.
9740 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9741 if (!Method->isFunctionTemplateSpecialization() &&
9742 !Method->getDescribedFunctionTemplate() &&
9743 Method->isCanonicalDecl()) {
9744 if (AddOverriddenMethods(Method->getParent(), Method)) {
9745 // If the function was marked as "static", we have a problem.
9746 if (NewFD->getStorageClass() == SC_Static) {
9747 ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
9748 }
9749 }
9750 }
9751
9752 if (Method->isStatic())
9753 checkThisInStaticMemberFunctionType(Method);
9754 }
9755
9756 // Extra checking for C++ overloaded operators (C++ [over.oper]).
9757 if (NewFD->isOverloadedOperator() &&
9758 CheckOverloadedOperatorDeclaration(NewFD)) {
9759 NewFD->setInvalidDecl();
9760 return Redeclaration;
9761 }
9762
9763 // Extra checking for C++0x literal operators (C++0x [over.literal]).
9764 if (NewFD->getLiteralIdentifier() &&
9765 CheckLiteralOperatorDeclaration(NewFD)) {
9766 NewFD->setInvalidDecl();
9767 return Redeclaration;
9768 }
9769
9770 // In C++, check default arguments now that we have merged decls. Unless
9771 // the lexical context is the class, because in this case this is done
9772 // during delayed parsing anyway.
9773 if (!CurContext->isRecord())
9774 CheckCXXDefaultArguments(NewFD);
9775
9776 // If this function declares a builtin function, check the type of this
9777 // declaration against the expected type for the builtin.
9778 if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9779 ASTContext::GetBuiltinTypeError Error;
9780 LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9781 QualType T = Context.GetBuiltinType(BuiltinID, Error);
9782 // If the type of the builtin differs only in its exception
9783 // specification, that's OK.
9784 // FIXME: If the types do differ in this way, it would be better to
9785 // retain the 'noexcept' form of the type.
9786 if (!T.isNull() &&
9787 !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
9788 NewFD->getType()))
9789 // The type of this function differs from the type of the builtin,
9790 // so forget about the builtin entirely.
9791 Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9792 }
9793
9794 // If this function is declared as being extern "C", then check to see if
9795 // the function returns a UDT (class, struct, or union type) that is not C
9796 // compatible, and if it does, warn the user.
9797 // But, issue any diagnostic on the first declaration only.
9798 if (Previous.empty() && NewFD->isExternC()) {
9799 QualType R = NewFD->getReturnType();
9800 if (R->isIncompleteType() && !R->isVoidType())
9801 Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9802 << NewFD << R;
9803 else if (!R.isPODType(Context) && !R->isVoidType() &&
9804 !R->isObjCObjectPointerType())
9805 Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9806 }
9807
9808 // C++1z [dcl.fct]p6:
9809 // [...] whether the function has a non-throwing exception-specification
9810 // [is] part of the function type
9811 //
9812 // This results in an ABI break between C++14 and C++17 for functions whose
9813 // declared type includes an exception-specification in a parameter or
9814 // return type. (Exception specifications on the function itself are OK in
9815 // most cases, and exception specifications are not permitted in most other
9816 // contexts where they could make it into a mangling.)
9817 if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
9818 auto HasNoexcept = [&](QualType T) -> bool {
9819 // Strip off declarator chunks that could be between us and a function
9820 // type. We don't need to look far, exception specifications are very
9821 // restricted prior to C++17.
9822 if (auto *RT = T->getAs<ReferenceType>())
9823 T = RT->getPointeeType();
9824 else if (T->isAnyPointerType())
9825 T = T->getPointeeType();
9826 else if (auto *MPT = T->getAs<MemberPointerType>())
9827 T = MPT->getPointeeType();
9828 if (auto *FPT = T->getAs<FunctionProtoType>())
9829 if (FPT->isNothrow(Context))
9830 return true;
9831 return false;
9832 };
9833
9834 auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9835 bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9836 for (QualType T : FPT->param_types())
9837 AnyNoexcept |= HasNoexcept(T);
9838 if (AnyNoexcept)
9839 Diag(NewFD->getLocation(),
9840 diag::warn_cxx17_compat_exception_spec_in_signature)
9841 << NewFD;
9842 }
9843
9844 if (!Redeclaration && LangOpts.CUDA)
9845 checkCUDATargetOverload(NewFD, Previous);
9846 }
9847 return Redeclaration;
9848}
9849
9850void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9851 // C++11 [basic.start.main]p3:
9852 // A program that [...] declares main to be inline, static or
9853 // constexpr is ill-formed.
9854 // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
9855 // appear in a declaration of main.
9856 // static main is not an error under C99, but we should warn about it.
9857 // We accept _Noreturn main as an extension.
9858 if (FD->getStorageClass() == SC_Static)
9859 Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9860 ? diag::err_static_main : diag::warn_static_main)
9861 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9862 if (FD->isInlineSpecified())
9863 Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9864 << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9865 if (DS.isNoreturnSpecified()) {
9866 SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9867 SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9868 Diag(NoreturnLoc, diag::ext_noreturn_main);
9869 Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9870 << FixItHint::CreateRemoval(NoreturnRange);
9871 }
9872 if (FD->isConstexpr()) {
9873 Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9874 << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9875 FD->setConstexpr(false);
9876 }
9877
9878 if (getLangOpts().OpenCL) {
9879 Diag(FD->getLocation(), diag::err_opencl_no_main)
9880 << FD->hasAttr<OpenCLKernelAttr>();
9881 FD->setInvalidDecl();
9882 return;
9883 }
9884
9885 QualType T = FD->getType();
9886 assert(T->isFunctionType() && "function decl is not of function type")(static_cast <bool> (T->isFunctionType() && "function decl is not of function type"
) ? void (0) : __assert_fail ("T->isFunctionType() && \"function decl is not of function type\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 9886, __extension__ __PRETTY_FUNCTION__))
;
9887 const FunctionType* FT = T->castAs<FunctionType>();
9888
9889 // Set default calling convention for main()
9890 if (FT->getCallConv() != CC_C) {
9891 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
9892 FD->setType(QualType(FT, 0));
9893 T = Context.getCanonicalType(FD->getType());
9894 }
9895
9896 if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9897 // In C with GNU extensions we allow main() to have non-integer return
9898 // type, but we should warn about the extension, and we disable the
9899 // implicit-return-zero rule.
9900
9901 // GCC in C mode accepts qualified 'int'.
9902 if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9903 FD->setHasImplicitReturnZero(true);
9904 else {
9905 Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9906 SourceRange RTRange = FD->getReturnTypeSourceRange();
9907 if (RTRange.isValid())
9908 Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9909 << FixItHint::CreateReplacement(RTRange, "int");
9910 }
9911 } else {
9912 // In C and C++, main magically returns 0 if you fall off the end;
9913 // set the flag which tells us that.
9914 // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9915
9916 // All the standards say that main() should return 'int'.
9917 if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9918 FD->setHasImplicitReturnZero(true);
9919 else {
9920 // Otherwise, this is just a flat-out error.
9921 SourceRange RTRange = FD->getReturnTypeSourceRange();
9922 Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9923 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9924 : FixItHint());
9925 FD->setInvalidDecl(true);
9926 }
9927 }
9928
9929 // Treat protoless main() as nullary.
9930 if (isa<FunctionNoProtoType>(FT)) return;
9931
9932 const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9933 unsigned nparams = FTP->getNumParams();
9934 assert(FD->getNumParams() == nparams)(static_cast <bool> (FD->getNumParams() == nparams) ?
void (0) : __assert_fail ("FD->getNumParams() == nparams"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 9934, __extension__ __PRETTY_FUNCTION__))
;
9935
9936 bool HasExtraParameters = (nparams > 3);
9937
9938 if (FTP->isVariadic()) {
9939 Diag(FD->getLocation(), diag::ext_variadic_main);
9940 // FIXME: if we had information about the location of the ellipsis, we
9941 // could add a FixIt hint to remove it as a parameter.
9942 }
9943
9944 // Darwin passes an undocumented fourth argument of type char**. If
9945 // other platforms start sprouting these, the logic below will start
9946 // getting shifty.
9947 if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9948 HasExtraParameters = false;
9949
9950 if (HasExtraParameters) {
9951 Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9952 FD->setInvalidDecl(true);
9953 nparams = 3;
9954 }
9955
9956 // FIXME: a lot of the following diagnostics would be improved
9957 // if we had some location information about types.
9958
9959 QualType CharPP =
9960 Context.getPointerType(Context.getPointerType(Context.CharTy));
9961 QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9962
9963 for (unsigned i = 0; i < nparams; ++i) {
9964 QualType AT = FTP->getParamType(i);
9965
9966 bool mismatch = true;
9967
9968 if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9969 mismatch = false;
9970 else if (Expected[i] == CharPP) {
9971 // As an extension, the following forms are okay:
9972 // char const **
9973 // char const * const *
9974 // char * const *
9975
9976 QualifierCollector qs;
9977 const PointerType* PT;
9978 if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9979 (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9980 Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9981 Context.CharTy)) {
9982 qs.removeConst();
9983 mismatch = !qs.empty();
9984 }
9985 }
9986
9987 if (mismatch) {
9988 Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9989 // TODO: suggest replacing given type with expected type
9990 FD->setInvalidDecl(true);
9991 }
9992 }
9993
9994 if (nparams == 1 && !FD->isInvalidDecl()) {
9995 Diag(FD->getLocation(), diag::warn_main_one_arg);
9996 }
9997
9998 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9999 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10000 FD->setInvalidDecl();
10001 }
10002}
10003
10004void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10005 QualType T = FD->getType();
10006 assert(T->isFunctionType() && "function decl is not of function type")(static_cast <bool> (T->isFunctionType() && "function decl is not of function type"
) ? void (0) : __assert_fail ("T->isFunctionType() && \"function decl is not of function type\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 10006, __extension__ __PRETTY_FUNCTION__))
;
10007 const FunctionType *FT = T->castAs<FunctionType>();
10008
10009 // Set an implicit return of 'zero' if the function can return some integral,
10010 // enumeration, pointer or nullptr type.
10011 if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10012 FT->getReturnType()->isAnyPointerType() ||
10013 FT->getReturnType()->isNullPtrType())
10014 // DllMain is exempt because a return value of zero means it failed.
10015 if (FD->getName() != "DllMain")
10016 FD->setHasImplicitReturnZero(true);
10017
10018 if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10019 Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10020 FD->setInvalidDecl();
10021 }
10022}
10023
10024bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
10025 // FIXME: Need strict checking. In C89, we need to check for
10026 // any assignment, increment, decrement, function-calls, or
10027 // commas outside of a sizeof. In C99, it's the same list,
10028 // except that the aforementioned are allowed in unevaluated
10029 // expressions. Everything else falls under the
10030 // "may accept other forms of constant expressions" exception.
10031 // (We never end up here for C++, so the constant expression
10032 // rules there don't matter.)
10033 const Expr *Culprit;
10034 if (Init->isConstantInitializer(Context, false, &Culprit))
10035 return false;
10036 Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10037 << Culprit->getSourceRange();
10038 return true;
10039}
10040
10041namespace {
10042 // Visits an initialization expression to see if OrigDecl is evaluated in
10043 // its own initialization and throws a warning if it does.
10044 class SelfReferenceChecker
10045 : public EvaluatedExprVisitor<SelfReferenceChecker> {
10046 Sema &S;
10047 Decl *OrigDecl;
10048 bool isRecordType;
10049 bool isPODType;
10050 bool isReferenceType;
10051
10052 bool isInitList;
10053 llvm::SmallVector<unsigned, 4> InitFieldIndex;
10054
10055 public:
10056 typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
10057
10058 SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
10059 S(S), OrigDecl(OrigDecl) {
10060 isPODType = false;
10061 isRecordType = false;
10062 isReferenceType = false;
10063 isInitList = false;
10064 if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10065 isPODType = VD->getType().isPODType(S.Context);
10066 isRecordType = VD->getType()->isRecordType();
10067 isReferenceType = VD->getType()->isReferenceType();
10068 }
10069 }
10070
10071 // For most expressions, just call the visitor. For initializer lists,
10072 // track the index of the field being initialized since fields are
10073 // initialized in order allowing use of previously initialized fields.
10074 void CheckExpr(Expr *E) {
10075 InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10076 if (!InitList) {
10077 Visit(E);
10078 return;
10079 }
10080
10081 // Track and increment the index here.
10082 isInitList = true;
10083 InitFieldIndex.push_back(0);
10084 for (auto Child : InitList->children()) {
10085 CheckExpr(cast<Expr>(Child));
10086 ++InitFieldIndex.back();
10087 }
10088 InitFieldIndex.pop_back();
10089 }
10090
10091 // Returns true if MemberExpr is checked and no further checking is needed.
10092 // Returns false if additional checking is required.
10093 bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
10094 llvm::SmallVector<FieldDecl*, 4> Fields;
10095 Expr *Base = E;
10096 bool ReferenceField = false;
10097
10098 // Get the field memebers used.
10099 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10100 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10101 if (!FD)
10102 return false;
10103 Fields.push_back(FD);
10104 if (FD->getType()->isReferenceType())
10105 ReferenceField = true;
10106 Base = ME->getBase()->IgnoreParenImpCasts();
10107 }
10108
10109 // Keep checking only if the base Decl is the same.
10110 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10111 if (!DRE || DRE->getDecl() != OrigDecl)
10112 return false;
10113
10114 // A reference field can be bound to an unininitialized field.
10115 if (CheckReference && !ReferenceField)
10116 return true;
10117
10118 // Convert FieldDecls to their index number.
10119 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
10120 for (const FieldDecl *I : llvm::reverse(Fields))
10121 UsedFieldIndex.push_back(I->getFieldIndex());
10122
10123 // See if a warning is needed by checking the first difference in index
10124 // numbers. If field being used has index less than the field being
10125 // initialized, then the use is safe.
10126 for (auto UsedIter = UsedFieldIndex.begin(),
10127 UsedEnd = UsedFieldIndex.end(),
10128 OrigIter = InitFieldIndex.begin(),
10129 OrigEnd = InitFieldIndex.end();
10130 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10131 if (*UsedIter < *OrigIter)
10132 return true;
10133 if (*UsedIter > *OrigIter)
10134 break;
10135 }
10136
10137 // TODO: Add a different warning which will print the field names.
10138 HandleDeclRefExpr(DRE);
10139 return true;
10140 }
10141
10142 // For most expressions, the cast is directly above the DeclRefExpr.
10143 // For conditional operators, the cast can be outside the conditional
10144 // operator if both expressions are DeclRefExpr's.
10145 void HandleValue(Expr *E) {
10146 E = E->IgnoreParens();
10147 if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
10148 HandleDeclRefExpr(DRE);
10149 return;
10150 }
10151
10152 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10153 Visit(CO->getCond());
10154 HandleValue(CO->getTrueExpr());
10155 HandleValue(CO->getFalseExpr());
10156 return;
10157 }
10158
10159 if (BinaryConditionalOperator *BCO =
10160 dyn_cast<BinaryConditionalOperator>(E)) {
10161 Visit(BCO->getCond());
10162 HandleValue(BCO->getFalseExpr());
10163 return;
10164 }
10165
10166 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10167 HandleValue(OVE->getSourceExpr());
10168 return;
10169 }
10170
10171 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10172 if (BO->getOpcode() == BO_Comma) {
10173 Visit(BO->getLHS());
10174 HandleValue(BO->getRHS());
10175 return;
10176 }
10177 }
10178
10179 if (isa<MemberExpr>(E)) {
10180 if (isInitList) {
10181 if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10182 false /*CheckReference*/))
10183 return;
10184 }
10185
10186 Expr *Base = E->IgnoreParenImpCasts();
10187 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10188 // Check for static member variables and don't warn on them.
10189 if (!isa<FieldDecl>(ME->getMemberDecl()))
10190 return;
10191 Base = ME->getBase()->IgnoreParenImpCasts();
10192 }
10193 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10194 HandleDeclRefExpr(DRE);
10195 return;
10196 }
10197
10198 Visit(E);
10199 }
10200
10201 // Reference types not handled in HandleValue are handled here since all
10202 // uses of references are bad, not just r-value uses.
10203 void VisitDeclRefExpr(DeclRefExpr *E) {
10204 if (isReferenceType)
10205 HandleDeclRefExpr(E);
10206 }
10207
10208 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10209 if (E->getCastKind() == CK_LValueToRValue) {
10210 HandleValue(E->getSubExpr());
10211 return;
10212 }
10213
10214 Inherited::VisitImplicitCastExpr(E);
10215 }
10216
10217 void VisitMemberExpr(MemberExpr *E) {
10218 if (isInitList) {
10219 if (CheckInitListMemberExpr(E, true /*CheckReference*/))
10220 return;
10221 }
10222
10223 // Don't warn on arrays since they can be treated as pointers.
10224 if (E->getType()->canDecayToPointerType()) return;
10225
10226 // Warn when a non-static method call is followed by non-static member
10227 // field accesses, which is followed by a DeclRefExpr.
10228 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10229 bool Warn = (MD && !MD->isStatic());
10230 Expr *Base = E->getBase()->IgnoreParenImpCasts();
10231 while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10232 if (!isa<FieldDecl>(ME->getMemberDecl()))
10233 Warn = false;
10234 Base = ME->getBase()->IgnoreParenImpCasts();
10235 }
10236
10237 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10238 if (Warn)
10239 HandleDeclRefExpr(DRE);
10240 return;
10241 }
10242
10243 // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10244 // Visit that expression.
10245 Visit(Base);
10246 }
10247
10248 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10249 Expr *Callee = E->getCallee();
10250
10251 if (isa<UnresolvedLookupExpr>(Callee))
10252 return Inherited::VisitCXXOperatorCallExpr(E);
10253
10254 Visit(Callee);
10255 for (auto Arg: E->arguments())
10256 HandleValue(Arg->IgnoreParenImpCasts());
10257 }
10258
10259 void VisitUnaryOperator(UnaryOperator *E) {
10260 // For POD record types, addresses of its own members are well-defined.
10261 if (E->getOpcode() == UO_AddrOf && isRecordType &&
10262 isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
10263 if (!isPODType)
10264 HandleValue(E->getSubExpr());
10265 return;
10266 }
10267
10268 if (E->isIncrementDecrementOp()) {
10269 HandleValue(E->getSubExpr());
10270 return;
10271 }
10272
10273 Inherited::VisitUnaryOperator(E);
10274 }
10275
10276 void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
10277
10278 void VisitCXXConstructExpr(CXXConstructExpr *E) {
10279 if (E->getConstructor()->isCopyConstructor()) {
10280 Expr *ArgExpr = E->getArg(0);
10281 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
10282 if (ILE->getNumInits() == 1)
10283 ArgExpr = ILE->getInit(0);
10284 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
10285 if (ICE->getCastKind() == CK_NoOp)
10286 ArgExpr = ICE->getSubExpr();
10287 HandleValue(ArgExpr);
10288 return;
10289 }
10290 Inherited::VisitCXXConstructExpr(E);
10291 }
10292
10293 void VisitCallExpr(CallExpr *E) {
10294 // Treat std::move as a use.
10295 if (E->isCallToStdMove()) {
10296 HandleValue(E->getArg(0));
10297 return;
10298 }
10299
10300 Inherited::VisitCallExpr(E);
10301 }
10302
10303 void VisitBinaryOperator(BinaryOperator *E) {
10304 if (E->isCompoundAssignmentOp()) {
10305 HandleValue(E->getLHS());
10306 Visit(E->getRHS());
10307 return;
10308 }
10309
10310 Inherited::VisitBinaryOperator(E);
10311 }
10312
10313 // A custom visitor for BinaryConditionalOperator is needed because the
10314 // regular visitor would check the condition and true expression separately
10315 // but both point to the same place giving duplicate diagnostics.
10316 void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10317 Visit(E->getCond());
10318 Visit(E->getFalseExpr());
10319 }
10320
10321 void HandleDeclRefExpr(DeclRefExpr *DRE) {
10322 Decl* ReferenceDecl = DRE->getDecl();
10323 if (OrigDecl != ReferenceDecl) return;
10324 unsigned diag;
10325 if (isReferenceType) {
10326 diag = diag::warn_uninit_self_reference_in_reference_init;
10327 } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10328 diag = diag::warn_static_self_reference_in_init;
10329 } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10330 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10331 DRE->getDecl()->getType()->isRecordType()) {
10332 diag = diag::warn_uninit_self_reference_in_init;
10333 } else {
10334 // Local variables will be handled by the CFG analysis.
10335 return;
10336 }
10337
10338 S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
10339 S.PDiag(diag)
10340 << DRE->getDecl()
10341 << OrigDecl->getLocation()
10342 << DRE->getSourceRange());
10343 }
10344 };
10345
10346 /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10347 static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
10348 bool DirectInit) {
10349 // Parameters arguments are occassionially constructed with itself,
10350 // for instance, in recursive functions. Skip them.
10351 if (isa<ParmVarDecl>(OrigDecl))
10352 return;
10353
10354 E = E->IgnoreParens();
10355
10356 // Skip checking T a = a where T is not a record or reference type.
10357 // Doing so is a way to silence uninitialized warnings.
10358 if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10359 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10360 if (ICE->getCastKind() == CK_LValueToRValue)
10361 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10362 if (DRE->getDecl() == OrigDecl)
10363 return;
10364
10365 SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
10366 }
10367} // end anonymous namespace
10368
10369namespace {
10370 // Simple wrapper to add the name of a variable or (if no variable is
10371 // available) a DeclarationName into a diagnostic.
10372 struct VarDeclOrName {
10373 VarDecl *VDecl;
10374 DeclarationName Name;
10375
10376 friend const Sema::SemaDiagnosticBuilder &
10377 operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
10378 return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10379 }
10380 };
10381} // end anonymous namespace
10382
10383QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10384 DeclarationName Name, QualType Type,
10385 TypeSourceInfo *TSI,
10386 SourceRange Range, bool DirectInit,
10387 Expr *Init) {
10388 bool IsInitCapture = !VDecl;
10389 assert((!VDecl || !VDecl->isInitCapture()) &&(static_cast <bool> ((!VDecl || !VDecl->isInitCapture
()) && "init captures are expected to be deduced prior to initialization"
) ? void (0) : __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 10390, __extension__ __PRETTY_FUNCTION__))
10390 "init captures are expected to be deduced prior to initialization")(static_cast <bool> ((!VDecl || !VDecl->isInitCapture
()) && "init captures are expected to be deduced prior to initialization"
) ? void (0) : __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 10390, __extension__ __PRETTY_FUNCTION__))
;
10391
10392 VarDeclOrName VN{VDecl, Name};
10393
10394 DeducedType *Deduced = Type->getContainedDeducedType();
10395 assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type")(static_cast <bool> (Deduced && "deduceVarTypeFromInitializer for non-deduced type"
) ? void (0) : __assert_fail ("Deduced && \"deduceVarTypeFromInitializer for non-deduced type\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 10395, __extension__ __PRETTY_FUNCTION__))
;
10396
10397 // C++11 [dcl.spec.auto]p3
10398 if (!Init) {
10399 assert(VDecl && "no init for init capture deduction?")(static_cast <bool> (VDecl && "no init for init capture deduction?"
) ? void (0) : __assert_fail ("VDecl && \"no init for init capture deduction?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 10399, __extension__ __PRETTY_FUNCTION__))
;
10400
10401 // Except for class argument deduction, and then for an initializing
10402 // declaration only, i.e. no static at class scope or extern.
10403 if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
10404 VDecl->hasExternalStorage() ||
10405 VDecl->isStaticDataMember()) {
10406 Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10407 << VDecl->getDeclName() << Type;
10408 return QualType();
10409 }
10410 }
10411
10412 ArrayRef<Expr*> DeduceInits;
10413 if (Init)
10414 DeduceInits = Init;
10415
10416 if (DirectInit) {
10417 if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10418 DeduceInits = PL->exprs();
10419 }
10420
10421 if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10422 assert(VDecl && "non-auto type for init capture deduction?")(static_cast <bool> (VDecl && "non-auto type for init capture deduction?"
) ? void (0) : __assert_fail ("VDecl && \"non-auto type for init capture deduction?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 10422, __extension__ __PRETTY_FUNCTION__))
;
10423 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10424 InitializationKind Kind = InitializationKind::CreateForInit(
10425 VDecl->getLocation(), DirectInit, Init);
10426 // FIXME: Initialization should not be taking a mutable list of inits.
10427 SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
10428 return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10429 InitsCopy);
10430 }
10431
10432 if (DirectInit) {
10433 if (auto *IL = dyn_cast<InitListExpr>(Init))
10434 DeduceInits = IL->inits();
10435 }
10436
10437 // Deduction only works if we have exactly one source expression.
10438 if (DeduceInits.empty()) {
10439 // It isn't possible to write this directly, but it is possible to
10440 // end up in this situation with "auto x(some_pack...);"
10441 Diag(Init->getLocStart(), IsInitCapture
10442 ? diag::err_init_capture_no_expression
10443 : diag::err_auto_var_init_no_expression)
10444 << VN << Type << Range;
10445 return QualType();
10446 }
10447
10448 if (DeduceInits.size() > 1) {
10449 Diag(DeduceInits[1]->getLocStart(),
10450 IsInitCapture ? diag::err_init_capture_multiple_expressions
10451 : diag::err_auto_var_init_multiple_expressions)
10452 << VN << Type << Range;
10453 return QualType();
10454 }
10455
10456 Expr *DeduceInit = DeduceInits[0];
10457 if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10458 Diag(Init->getLocStart(), IsInitCapture
10459 ? diag::err_init_capture_paren_braces
10460 : diag::err_auto_var_init_paren_braces)
10461 << isa<InitListExpr>(Init) << VN << Type << Range;
10462 return QualType();
10463 }
10464
10465 // Expressions default to 'id' when we're in a debugger.
10466 bool DefaultedAnyToId = false;
10467 if (getLangOpts().DebuggerCastResultToId &&
10468 Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10469 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10470 if (Result.isInvalid()) {
10471 return QualType();
10472 }
10473 Init = Result.get();
10474 DefaultedAnyToId = true;
10475 }
10476
10477 // C++ [dcl.decomp]p1:
10478 // If the assignment-expression [...] has array type A and no ref-qualifier
10479 // is present, e has type cv A
10480 if (VDecl && isa<DecompositionDecl>(VDecl) &&
10481 Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10482 DeduceInit->getType()->isConstantArrayType())
10483 return Context.getQualifiedType(DeduceInit->getType(),
10484 Type.getQualifiers());
10485
10486 QualType DeducedType;
10487 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
10488 if (!IsInitCapture)
10489 DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
10490 else if (isa<InitListExpr>(Init))
10491 Diag(Range.getBegin(),
10492 diag::err_init_capture_deduction_failure_from_init_list)
10493 << VN
10494 << (DeduceInit->getType().isNull() ? TSI->getType()
10495 : DeduceInit->getType())
10496 << DeduceInit->getSourceRange();
10497 else
10498 Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10499 << VN << TSI->getType()
10500 << (DeduceInit->getType().isNull() ? TSI->getType()
10501 : DeduceInit->getType())
10502 << DeduceInit->getSourceRange();
10503 }
10504
10505 // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10506 // 'id' instead of a specific object type prevents most of our usual
10507 // checks.
10508 // We only want to warn outside of template instantiations, though:
10509 // inside a template, the 'id' could have come from a parameter.
10510 if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10511 !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10512 SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10513 Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10514 }
10515
10516 return DeducedType;
10517}
10518
10519bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
10520 Expr *Init) {
10521 QualType DeducedType = deduceVarTypeFromInitializer(
10522 VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10523 VDecl->getSourceRange(), DirectInit, Init);
10524 if (DeducedType.isNull()) {
10525 VDecl->setInvalidDecl();
10526 return true;
10527 }
10528
10529 VDecl->setType(DeducedType);
10530 assert(VDecl->isLinkageValid())(static_cast <bool> (VDecl->isLinkageValid()) ? void
(0) : __assert_fail ("VDecl->isLinkageValid()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 10530, __extension__ __PRETTY_FUNCTION__))
;
10531
10532 // In ARC, infer lifetime.
10533 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
10534 VDecl->setInvalidDecl();
10535
10536 // If this is a redeclaration, check that the type we just deduced matches
10537 // the previously declared type.
10538 if (VarDecl *Old = VDecl->getPreviousDecl()) {
10539 // We never need to merge the type, because we cannot form an incomplete
10540 // array of auto, nor deduce such a type.
10541 MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
10542 }
10543
10544 // Check the deduced type is valid for a variable declaration.
10545 CheckVariableDeclarationType(VDecl);
10546 return VDecl->isInvalidDecl();
10547}
10548
10549/// AddInitializerToDecl - Adds the initializer Init to the
10550/// declaration dcl. If DirectInit is true, this is C++ direct
10551/// initialization rather than copy initialization.
10552void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
10553 // If there is no declaration, there was an error parsing it. Just ignore
10554 // the initializer.
10555 if (!RealDecl || RealDecl->isInvalidDecl()) {
10556 CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
10557 return;
10558 }
10559
10560 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
10561 // Pure-specifiers are handled in ActOnPureSpecifier.
10562 Diag(Method->getLocation(), diag::err_member_function_initialization)
10563 << Method->getDeclName() << Init->getSourceRange();
10564 Method->setInvalidDecl();
10565 return;
10566 }
10567
10568 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
10569 if (!VDecl) {
10570 assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here")(static_cast <bool> (!isa<FieldDecl>(RealDecl) &&
"field init shouldn't get here") ? void (0) : __assert_fail (
"!isa<FieldDecl>(RealDecl) && \"field init shouldn't get here\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 10570, __extension__ __PRETTY_FUNCTION__))
;
10571 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
10572 RealDecl->setInvalidDecl();
10573 return;
10574 }
10575
10576 // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
10577 if (VDecl->getType()->isUndeducedType()) {
10578 // Attempt typo correction early so that the type of the init expression can
10579 // be deduced based on the chosen correction if the original init contains a
10580 // TypoExpr.
10581 ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
10582 if (!Res.isUsable()) {
10583 RealDecl->setInvalidDecl();
10584 return;
10585 }
10586 Init = Res.get();
10587
10588 if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
10589 return;
10590 }
10591
10592 // dllimport cannot be used on variable definitions.
10593 if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
10594 Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
10595 VDecl->setInvalidDecl();
10596 return;
10597 }
10598
10599 if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
10600 // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
10601 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
10602 VDecl->setInvalidDecl();
10603 return;
10604 }
10605
10606 if (!VDecl->getType()->isDependentType()) {
10607 // A definition must end up with a complete type, which means it must be
10608 // complete with the restriction that an array type might be completed by
10609 // the initializer; note that later code assumes this restriction.
10610 QualType BaseDeclType = VDecl->getType();
10611 if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
10612 BaseDeclType = Array->getElementType();
10613 if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
10614 diag::err_typecheck_decl_incomplete_type)) {
10615 RealDecl->setInvalidDecl();
10616 return;
10617 }
10618
10619 // The variable can not have an abstract class type.
10620 if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
10621 diag::err_abstract_type_in_decl,
10622 AbstractVariableType))
10623 VDecl->setInvalidDecl();
10624 }
10625
10626 // If adding the initializer will turn this declaration into a definition,
10627 // and we already have a definition for this variable, diagnose or otherwise
10628 // handle the situation.
10629 VarDecl *Def;
10630 if ((Def = VDecl->getDefinition()) && Def != VDecl &&
10631 (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
10632 !VDecl->isThisDeclarationADemotedDefinition() &&
10633 checkVarDeclRedefinition(Def, VDecl))
10634 return;
10635
10636 if (getLangOpts().CPlusPlus) {
10637 // C++ [class.static.data]p4
10638 // If a static data member is of const integral or const
10639 // enumeration type, its declaration in the class definition can
10640 // specify a constant-initializer which shall be an integral
10641 // constant expression (5.19). In that case, the member can appear
10642 // in integral constant expressions. The member shall still be
10643 // defined in a namespace scope if it is used in the program and the
10644 // namespace scope definition shall not contain an initializer.
10645 //
10646 // We already performed a redefinition check above, but for static
10647 // data members we also need to check whether there was an in-class
10648 // declaration with an initializer.
10649 if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
10650 Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
10651 << VDecl->getDeclName();
10652 Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
10653 diag::note_previous_initializer)
10654 << 0;
10655 return;
10656 }
10657
10658 if (VDecl->hasLocalStorage())
10659 setFunctionHasBranchProtectedScope();
10660
10661 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
10662 VDecl->setInvalidDecl();
10663 return;
10664 }
10665 }
10666
10667 // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
10668 // a kernel function cannot be initialized."
10669 if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
10670 Diag(VDecl->getLocation(), diag::err_local_cant_init);
10671 VDecl->setInvalidDecl();
10672 return;
10673 }
10674
10675 // Get the decls type and save a reference for later, since
10676 // CheckInitializerTypes may change it.
10677 QualType DclT = VDecl->getType(), SavT = DclT;
10678
10679 // Expressions default to 'id' when we're in a debugger
10680 // and we are assigning it to a variable of Objective-C pointer type.
10681 if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
10682 Init->getType() == Context.UnknownAnyTy) {
10683 ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
10684 if (Result.isInvalid()) {
10685 VDecl->setInvalidDecl();
10686 return;
10687 }
10688 Init = Result.get();
10689 }
10690
10691 // Perform the initialization.
10692 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
10693 if (!VDecl->isInvalidDecl()) {
10694 InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10695 InitializationKind Kind = InitializationKind::CreateForInit(
10696 VDecl->getLocation(), DirectInit, Init);
10697
10698 MultiExprArg Args = Init;
10699 if (CXXDirectInit)
10700 Args = MultiExprArg(CXXDirectInit->getExprs(),
10701 CXXDirectInit->getNumExprs());
10702
10703 // Try to correct any TypoExprs in the initialization arguments.
10704 for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
10705 ExprResult Res = CorrectDelayedTyposInExpr(
10706 Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
10707 InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
10708 return Init.Failed() ? ExprError() : E;
10709 });
10710 if (Res.isInvalid()) {
10711 VDecl->setInvalidDecl();
10712 } else if (Res.get() != Args[Idx]) {
10713 Args[Idx] = Res.get();
10714 }
10715 }
10716 if (VDecl->isInvalidDecl())
10717 return;
10718
10719 InitializationSequence InitSeq(*this, Entity, Kind, Args,
10720 /*TopLevelOfInitList=*/false,
10721 /*TreatUnavailableAsInvalid=*/false);
10722 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
10723 if (Result.isInvalid()) {
10724 VDecl->setInvalidDecl();
10725 return;
10726 }
10727
10728 Init = Result.getAs<Expr>();
10729 }
10730
10731 // Check for self-references within variable initializers.
10732 // Variables declared within a function/method body (except for references)
10733 // are handled by a dataflow analysis.
10734 if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
10735 VDecl->getType()->isReferenceType()) {
10736 CheckSelfReference(*this, RealDecl, Init, DirectInit);
10737 }
10738
10739 // If the type changed, it means we had an incomplete type that was
10740 // completed by the initializer. For example:
10741 // int ary[] = { 1, 3, 5 };
10742 // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
10743 if (!VDecl->isInvalidDecl() && (DclT != SavT))
10744 VDecl->setType(DclT);
10745
10746 if (!VDecl->isInvalidDecl()) {
10747 checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
10748
10749 if (VDecl->hasAttr<BlocksAttr>())
10750 checkRetainCycles(VDecl, Init);
10751
10752 // It is safe to assign a weak reference into a strong variable.
10753 // Although this code can still have problems:
10754 // id x = self.weakProp;
10755 // id y = self.weakProp;
10756 // we do not warn to warn spuriously when 'x' and 'y' are on separate
10757 // paths through the function. This should be revisited if
10758 // -Wrepeated-use-of-weak is made flow-sensitive.
10759 if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
10760 VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
10761 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10762 Init->getLocStart()))
10763 getCurFunction()->markSafeWeakUse(Init);
10764 }
10765
10766 // The initialization is usually a full-expression.
10767 //
10768 // FIXME: If this is a braced initialization of an aggregate, it is not
10769 // an expression, and each individual field initializer is a separate
10770 // full-expression. For instance, in:
10771 //
10772 // struct Temp { ~Temp(); };
10773 // struct S { S(Temp); };
10774 // struct T { S a, b; } t = { Temp(), Temp() }
10775 //
10776 // we should destroy the first Temp before constructing the second.
10777 ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10778 false,
10779 VDecl->isConstexpr());
10780 if (Result.isInvalid()) {
10781 VDecl->setInvalidDecl();
10782 return;
10783 }
10784 Init = Result.get();
10785
10786 // Attach the initializer to the decl.
10787 VDecl->setInit(Init);
10788
10789 if (VDecl->isLocalVarDecl()) {
10790 // Don't check the initializer if the declaration is malformed.
10791 if (VDecl->isInvalidDecl()) {
10792 // do nothing
10793
10794 // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
10795 // This is true even in OpenCL C++.
10796 } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
10797 CheckForConstantInitializer(Init, DclT);
10798
10799 // Otherwise, C++ does not restrict the initializer.
10800 } else if (getLangOpts().CPlusPlus) {
10801 // do nothing
10802
10803 // C99 6.7.8p4: All the expressions in an initializer for an object that has
10804 // static storage duration shall be constant expressions or string literals.
10805 } else if (VDecl->getStorageClass() == SC_Static) {
10806 CheckForConstantInitializer(Init, DclT);
10807
10808 // C89 is stricter than C99 for aggregate initializers.
10809 // C89 6.5.7p3: All the expressions [...] in an initializer list
10810 // for an object that has aggregate or union type shall be
10811 // constant expressions.
10812 } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10813 isa<InitListExpr>(Init)) {
10814 const Expr *Culprit;
10815 if (!Init->isConstantInitializer(Context, false, &Culprit)) {
10816 Diag(Culprit->getExprLoc(),
10817 diag::ext_aggregate_init_not_constant)
10818 << Culprit->getSourceRange();
10819 }
10820 }
10821 } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10822 VDecl->getLexicalDeclContext()->isRecord()) {
10823 // This is an in-class initialization for a static data member, e.g.,
10824 //
10825 // struct S {
10826 // static const int value = 17;
10827 // };
10828
10829 // C++ [class.mem]p4:
10830 // A member-declarator can contain a constant-initializer only
10831 // if it declares a static member (9.4) of const integral or
10832 // const enumeration type, see 9.4.2.
10833 //
10834 // C++11 [class.static.data]p3:
10835 // If a non-volatile non-inline const static data member is of integral
10836 // or enumeration type, its declaration in the class definition can
10837 // specify a brace-or-equal-initializer in which every initializer-clause
10838 // that is an assignment-expression is a constant expression. A static
10839 // data member of literal type can be declared in the class definition
10840 // with the constexpr specifier; if so, its declaration shall specify a
10841 // brace-or-equal-initializer in which every initializer-clause that is
10842 // an assignment-expression is a constant expression.
10843
10844 // Do nothing on dependent types.
10845 if (DclT->isDependentType()) {
10846
10847 // Allow any 'static constexpr' members, whether or not they are of literal
10848 // type. We separately check that every constexpr variable is of literal
10849 // type.
10850 } else if (VDecl->isConstexpr()) {
10851
10852 // Require constness.
10853 } else if (!DclT.isConstQualified()) {
10854 Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10855 << Init->getSourceRange();
10856 VDecl->setInvalidDecl();
10857
10858 // We allow integer constant expressions in all cases.
10859 } else if (DclT->isIntegralOrEnumerationType()) {
10860 // Check whether the expression is a constant expression.
10861 SourceLocation Loc;
10862 if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10863 // In C++11, a non-constexpr const static data member with an
10864 // in-class initializer cannot be volatile.
10865 Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10866 else if (Init->isValueDependent())
10867 ; // Nothing to check.
10868 else if (Init->isIntegerConstantExpr(Context, &Loc))
10869 ; // Ok, it's an ICE!
10870 else if (Init->isEvaluatable(Context)) {
10871 // If we can constant fold the initializer through heroics, accept it,
10872 // but report this as a use of an extension for -pedantic.
10873 Diag(Loc, diag::ext_in_class_initializer_non_constant)
10874 << Init->getSourceRange();
10875 } else {
10876 // Otherwise, this is some crazy unknown case. Report the issue at the
10877 // location provided by the isIntegerConstantExpr failed check.
10878 Diag(Loc, diag::err_in_class_initializer_non_constant)
10879 << Init->getSourceRange();
10880 VDecl->setInvalidDecl();
10881 }
10882
10883 // We allow foldable floating-point constants as an extension.
10884 } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10885 // In C++98, this is a GNU extension. In C++11, it is not, but we support
10886 // it anyway and provide a fixit to add the 'constexpr'.
10887 if (getLangOpts().CPlusPlus11) {
10888 Diag(VDecl->getLocation(),
10889 diag::ext_in_class_initializer_float_type_cxx11)
10890 << DclT << Init->getSourceRange();
10891 Diag(VDecl->getLocStart(),
10892 diag::note_in_class_initializer_float_type_cxx11)
10893 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10894 } else {
10895 Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10896 << DclT << Init->getSourceRange();
10897
10898 if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10899 Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10900 << Init->getSourceRange();
10901 VDecl->setInvalidDecl();
10902 }
10903 }
10904
10905 // Suggest adding 'constexpr' in C++11 for literal types.
10906 } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10907 Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10908 << DclT << Init->getSourceRange()
10909 << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10910 VDecl->setConstexpr(true);
10911
10912 } else {
10913 Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10914 << DclT << Init->getSourceRange();
10915 VDecl->setInvalidDecl();
10916 }
10917 } else if (VDecl->isFileVarDecl()) {
10918 // In C, extern is typically used to avoid tentative definitions when
10919 // declaring variables in headers, but adding an intializer makes it a
10920 // definition. This is somewhat confusing, so GCC and Clang both warn on it.
10921 // In C++, extern is often used to give implictly static const variables
10922 // external linkage, so don't warn in that case. If selectany is present,
10923 // this might be header code intended for C and C++ inclusion, so apply the
10924 // C++ rules.
10925 if (VDecl->getStorageClass() == SC_Extern &&
10926 ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10927 !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10928 !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10929 !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10930 Diag(VDecl->getLocation(), diag::warn_extern_init);
10931
10932 // C99 6.7.8p4. All file scoped initializers need to be constant.
10933 if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10934 CheckForConstantInitializer(Init, DclT);
10935 }
10936
10937 // We will represent direct-initialization similarly to copy-initialization:
10938 // int x(1); -as-> int x = 1;
10939 // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10940 //
10941 // Clients that want to distinguish between the two forms, can check for
10942 // direct initializer using VarDecl::getInitStyle().
10943 // A major benefit is that clients that don't particularly care about which
10944 // exactly form was it (like the CodeGen) can handle both cases without
10945 // special case code.
10946
10947 // C++ 8.5p11:
10948 // The form of initialization (using parentheses or '=') is generally
10949 // insignificant, but does matter when the entity being initialized has a
10950 // class type.
10951 if (CXXDirectInit) {
10952 assert(DirectInit && "Call-style initializer must be direct init.")(static_cast <bool> (DirectInit && "Call-style initializer must be direct init."
) ? void (0) : __assert_fail ("DirectInit && \"Call-style initializer must be direct init.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 10952, __extension__ __PRETTY_FUNCTION__))
;
10953 VDecl->setInitStyle(VarDecl::CallInit);
10954 } else if (DirectInit) {
10955 // This must be list-initialization. No other way is direct-initialization.
10956 VDecl->setInitStyle(VarDecl::ListInit);
10957 }
10958
10959 CheckCompleteVariableDeclaration(VDecl);
10960}
10961
10962/// ActOnInitializerError - Given that there was an error parsing an
10963/// initializer for the given declaration, try to return to some form
10964/// of sanity.
10965void Sema::ActOnInitializerError(Decl *D) {
10966 // Our main concern here is re-establishing invariants like "a
10967 // variable's type is either dependent or complete".
10968 if (!D || D->isInvalidDecl()) return;
10969
10970 VarDecl *VD = dyn_cast<VarDecl>(D);
10971 if (!VD) return;
10972
10973 // Bindings are not usable if we can't make sense of the initializer.
10974 if (auto *DD = dyn_cast<DecompositionDecl>(D))
10975 for (auto *BD : DD->bindings())
10976 BD->setInvalidDecl();
10977
10978 // Auto types are meaningless if we can't make sense of the initializer.
10979 if (ParsingInitForAutoVars.count(D)) {
10980 D->setInvalidDecl();
10981 return;
10982 }
10983
10984 QualType Ty = VD->getType();
10985 if (Ty->isDependentType()) return;
10986
10987 // Require a complete type.
10988 if (RequireCompleteType(VD->getLocation(),
10989 Context.getBaseElementType(Ty),
10990 diag::err_typecheck_decl_incomplete_type)) {
10991 VD->setInvalidDecl();
10992 return;
10993 }
10994
10995 // Require a non-abstract type.
10996 if (RequireNonAbstractType(VD->getLocation(), Ty,
10997 diag::err_abstract_type_in_decl,
10998 AbstractVariableType)) {
10999 VD->setInvalidDecl();
11000 return;
11001 }
11002
11003 // Don't bother complaining about constructors or destructors,
11004 // though.
11005}
11006
11007void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
11008 // If there is no declaration, there was an error parsing it. Just ignore it.
11009 if (!RealDecl)
11010 return;
11011
11012 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
11013 QualType Type = Var->getType();
11014
11015 // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
11016 if (isa<DecompositionDecl>(RealDecl)) {
11017 Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
11018 Var->setInvalidDecl();
11019 return;
11020 }
11021
11022 if (Type->isUndeducedType() &&
11023 DeduceVariableDeclarationType(Var, false, nullptr))
11024 return;
11025
11026 // C++11 [class.static.data]p3: A static data member can be declared with
11027 // the constexpr specifier; if so, its declaration shall specify
11028 // a brace-or-equal-initializer.
11029 // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
11030 // the definition of a variable [...] or the declaration of a static data
11031 // member.
11032 if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
11033 !Var->isThisDeclarationADemotedDefinition()) {
11034 if (Var->isStaticDataMember()) {
11035 // C++1z removes the relevant rule; the in-class declaration is always
11036 // a definition there.
11037 if (!getLangOpts().CPlusPlus17) {
11038 Diag(Var->getLocation(),
11039 diag::err_constexpr_static_mem_var_requires_init)
11040 << Var->getDeclName();
11041 Var->setInvalidDecl();
11042 return;
11043 }
11044 } else {
11045 Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
11046 Var->setInvalidDecl();
11047 return;
11048 }
11049 }
11050
11051 // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
11052 // be initialized.
11053 if (!Var->isInvalidDecl() &&
11054 Var->getType().getAddressSpace() == LangAS::opencl_constant &&
11055 Var->getStorageClass() != SC_Extern && !Var->getInit()) {
11056 Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
11057 Var->setInvalidDecl();
11058 return;
11059 }
11060
11061 switch (Var->isThisDeclarationADefinition()) {
11062 case VarDecl::Definition:
11063 if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
11064 break;
11065
11066 // We have an out-of-line definition of a static data member
11067 // that has an in-class initializer, so we type-check this like
11068 // a declaration.
11069 //
11070 LLVM_FALLTHROUGH[[clang::fallthrough]];
11071
11072 case VarDecl::DeclarationOnly:
11073 // It's only a declaration.
11074
11075 // Block scope. C99 6.7p7: If an identifier for an object is
11076 // declared with no linkage (C99 6.2.2p6), the type for the
11077 // object shall be complete.
11078 if (!Type->isDependentType() && Var->isLocalVarDecl() &&
11079 !Var->hasLinkage() && !Var->isInvalidDecl() &&
11080 RequireCompleteType(Var->getLocation(), Type,
11081 diag::err_typecheck_decl_incomplete_type))
11082 Var->setInvalidDecl();
11083
11084 // Make sure that the type is not abstract.
11085 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11086 RequireNonAbstractType(Var->getLocation(), Type,
11087 diag::err_abstract_type_in_decl,
11088 AbstractVariableType))
11089 Var->setInvalidDecl();
11090 if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11091 Var->getStorageClass() == SC_PrivateExtern) {
11092 Diag(Var->getLocation(), diag::warn_private_extern);
11093 Diag(Var->getLocation(), diag::note_private_extern);
11094 }
11095
11096 return;
11097
11098 case VarDecl::TentativeDefinition:
11099 // File scope. C99 6.9.2p2: A declaration of an identifier for an
11100 // object that has file scope without an initializer, and without a
11101 // storage-class specifier or with the storage-class specifier "static",
11102 // constitutes a tentative definition. Note: A tentative definition with
11103 // external linkage is valid (C99 6.2.2p5).
11104 if (!Var->isInvalidDecl()) {
11105 if (const IncompleteArrayType *ArrayT
11106 = Context.getAsIncompleteArrayType(Type)) {
11107 if (RequireCompleteType(Var->getLocation(),
11108 ArrayT->getElementType(),
11109 diag::err_illegal_decl_array_incomplete_type))
11110 Var->setInvalidDecl();
11111 } else if (Var->getStorageClass() == SC_Static) {
11112 // C99 6.9.2p3: If the declaration of an identifier for an object is
11113 // a tentative definition and has internal linkage (C99 6.2.2p3), the
11114 // declared type shall not be an incomplete type.
11115 // NOTE: code such as the following
11116 // static struct s;
11117 // struct s { int a; };
11118 // is accepted by gcc. Hence here we issue a warning instead of
11119 // an error and we do not invalidate the static declaration.
11120 // NOTE: to avoid multiple warnings, only check the first declaration.
11121 if (Var->isFirstDecl())
11122 RequireCompleteType(Var->getLocation(), Type,
11123 diag::ext_typecheck_decl_incomplete_type);
11124 }
11125 }
11126
11127 // Record the tentative definition; we're done.
11128 if (!Var->isInvalidDecl())
11129 TentativeDefinitions.push_back(Var);
11130 return;
11131 }
11132
11133 // Provide a specific diagnostic for uninitialized variable
11134 // definitions with incomplete array type.
11135 if (Type->isIncompleteArrayType()) {
11136 Diag(Var->getLocation(),
11137 diag::err_typecheck_incomplete_array_needs_initializer);
11138 Var->setInvalidDecl();
11139 return;
11140 }
11141
11142 // Provide a specific diagnostic for uninitialized variable
11143 // definitions with reference type.
11144 if (Type->isReferenceType()) {
11145 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
11146 << Var->getDeclName()
11147 << SourceRange(Var->getLocation(), Var->getLocation());
11148 Var->setInvalidDecl();
11149 return;
11150 }
11151
11152 // Do not attempt to type-check the default initializer for a
11153 // variable with dependent type.
11154 if (Type->isDependentType())
11155 return;
11156
11157 if (Var->isInvalidDecl())
11158 return;
11159
11160 if (!Var->hasAttr<AliasAttr>()) {
11161 if (RequireCompleteType(Var->getLocation(),
11162 Context.getBaseElementType(Type),
11163 diag::err_typecheck_decl_incomplete_type)) {
11164 Var->setInvalidDecl();
11165 return;
11166 }
11167 } else {
11168 return;
11169 }
11170
11171 // The variable can not have an abstract class type.
11172 if (RequireNonAbstractType(Var->getLocation(), Type,
11173 diag::err_abstract_type_in_decl,
11174 AbstractVariableType)) {
11175 Var->setInvalidDecl();
11176 return;
11177 }
11178
11179 // Check for jumps past the implicit initializer. C++0x
11180 // clarifies that this applies to a "variable with automatic
11181 // storage duration", not a "local variable".
11182 // C++11 [stmt.dcl]p3
11183 // A program that jumps from a point where a variable with automatic
11184 // storage duration is not in scope to a point where it is in scope is
11185 // ill-formed unless the variable has scalar type, class type with a
11186 // trivial default constructor and a trivial destructor, a cv-qualified
11187 // version of one of these types, or an array of one of the preceding
11188 // types and is declared without an initializer.
11189 if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
11190 if (const RecordType *Record
11191 = Context.getBaseElementType(Type)->getAs<RecordType>()) {
11192 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
11193 // Mark the function (if we're in one) for further checking even if the
11194 // looser rules of C++11 do not require such checks, so that we can
11195 // diagnose incompatibilities with C++98.
11196 if (!CXXRecord->isPOD())
11197 setFunctionHasBranchProtectedScope();
11198 }
11199 }
11200
11201 // C++03 [dcl.init]p9:
11202 // If no initializer is specified for an object, and the
11203 // object is of (possibly cv-qualified) non-POD class type (or
11204 // array thereof), the object shall be default-initialized; if
11205 // the object is of const-qualified type, the underlying class
11206 // type shall have a user-declared default
11207 // constructor. Otherwise, if no initializer is specified for
11208 // a non- static object, the object and its subobjects, if
11209 // any, have an indeterminate initial value); if the object
11210 // or any of its subobjects are of const-qualified type, the
11211 // program is ill-formed.
11212 // C++0x [dcl.init]p11:
11213 // If no initializer is specified for an object, the object is
11214 // default-initialized; [...].
11215 InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
11216 InitializationKind Kind
11217 = InitializationKind::CreateDefault(Var->getLocation());
11218
11219 InitializationSequence InitSeq(*this, Entity, Kind, None);
11220 ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
11221 if (Init.isInvalid())
11222 Var->setInvalidDecl();
11223 else if (Init.get()) {
11224 Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
11225 // This is important for template substitution.
11226 Var->setInitStyle(VarDecl::CallInit);
11227 }
11228
11229 CheckCompleteVariableDeclaration(Var);
11230 }
11231}
11232
11233void Sema::ActOnCXXForRangeDecl(Decl *D) {
11234 // If there is no declaration, there was an error parsing it. Ignore it.
11235 if (!D)
11236 return;
11237
11238 VarDecl *VD = dyn_cast<VarDecl>(D);
11239 if (!VD) {
11240 Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
11241 D->setInvalidDecl();
11242 return;
11243 }
11244
11245 VD->setCXXForRangeDecl(true);
11246
11247 // for-range-declaration cannot be given a storage class specifier.
11248 int Error = -1;
11249 switch (VD->getStorageClass()) {
11250 case SC_None:
11251 break;
11252 case SC_Extern:
11253 Error = 0;
11254 break;
11255 case SC_Static:
11256 Error = 1;
11257 break;
11258 case SC_PrivateExtern:
11259 Error = 2;
11260 break;
11261 case SC_Auto:
11262 Error = 3;
11263 break;
11264 case SC_Register:
11265 Error = 4;
11266 break;
11267 }
11268 if (Error != -1) {
11269 Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
11270 << VD->getDeclName() << Error;
11271 D->setInvalidDecl();
11272 }
11273}
11274
11275StmtResult
11276Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
11277 IdentifierInfo *Ident,
11278 ParsedAttributes &Attrs,
11279 SourceLocation AttrEnd) {
11280 // C++1y [stmt.iter]p1:
11281 // A range-based for statement of the form
11282 // for ( for-range-identifier : for-range-initializer ) statement
11283 // is equivalent to
11284 // for ( auto&& for-range-identifier : for-range-initializer ) statement
11285 DeclSpec DS(Attrs.getPool().getFactory());
11286
11287 const char *PrevSpec;
11288 unsigned DiagID;
11289 DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
11290 getPrintingPolicy());
11291
11292 Declarator D(DS, DeclaratorContext::ForContext);
11293 D.SetIdentifier(Ident, IdentLoc);
11294 D.takeAttributes(Attrs, AttrEnd);
11295
11296 ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
11297 D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
11298 EmptyAttrs, IdentLoc);
11299 Decl *Var = ActOnDeclarator(S, D);
11300 cast<VarDecl>(Var)->setCXXForRangeDecl(true);
11301 FinalizeDeclaration(Var);
11302 return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
11303 AttrEnd.isValid() ? AttrEnd : IdentLoc);
11304}
11305
11306void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
11307 if (var->isInvalidDecl()) return;
11308
11309 if (getLangOpts().OpenCL) {
11310 // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
11311 // initialiser
11312 if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
11313 !var->hasInit()) {
11314 Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
11315 << 1 /*Init*/;
11316 var->setInvalidDecl();
11317 return;
11318 }
11319 }
11320
11321 // In Objective-C, don't allow jumps past the implicit initialization of a
11322 // local retaining variable.
11323 if (getLangOpts().ObjC1 &&
11324 var->hasLocalStorage()) {
11325 switch (var->getType().getObjCLifetime()) {
11326 case Qualifiers::OCL_None:
11327 case Qualifiers::OCL_ExplicitNone:
11328 case Qualifiers::OCL_Autoreleasing:
11329 break;
11330
11331 case Qualifiers::OCL_Weak:
11332 case Qualifiers::OCL_Strong:
11333 setFunctionHasBranchProtectedScope();
11334 break;
11335 }
11336 }
11337
11338 if (var->hasLocalStorage() &&
11339 var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
11340 setFunctionHasBranchProtectedScope();
11341
11342 // Warn about externally-visible variables being defined without a
11343 // prior declaration. We only want to do this for global
11344 // declarations, but we also specifically need to avoid doing it for
11345 // class members because the linkage of an anonymous class can
11346 // change if it's later given a typedef name.
11347 if (var->isThisDeclarationADefinition() &&
11348 var->getDeclContext()->getRedeclContext()->isFileContext() &&
11349 var->isExternallyVisible() && var->hasLinkage() &&
11350 !var->isInline() && !var->getDescribedVarTemplate() &&
11351 !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
11352 !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11353 var->getLocation())) {
11354 // Find a previous declaration that's not a definition.
11355 VarDecl *prev = var->getPreviousDecl();
11356 while (prev && prev->isThisDeclarationADefinition())
11357 prev = prev->getPreviousDecl();
11358
11359 if (!prev)
11360 Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11361 }
11362
11363 // Cache the result of checking for constant initialization.
11364 Optional<bool> CacheHasConstInit;
11365 const Expr *CacheCulprit;
11366 auto checkConstInit = [&]() mutable {
11367 if (!CacheHasConstInit)
11368 CacheHasConstInit = var->getInit()->isConstantInitializer(
11369 Context, var->getType()->isReferenceType(), &CacheCulprit);
11370 return *CacheHasConstInit;
11371 };
11372
11373 if (var->getTLSKind() == VarDecl::TLS_Static) {
11374 if (var->getType().isDestructedType()) {
11375 // GNU C++98 edits for __thread, [basic.start.term]p3:
11376 // The type of an object with thread storage duration shall not
11377 // have a non-trivial destructor.
11378 Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11379 if (getLangOpts().CPlusPlus11)
11380 Diag(var->getLocation(), diag::note_use_thread_local);
11381 } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11382 if (!checkConstInit()) {
11383 // GNU C++98 edits for __thread, [basic.start.init]p4:
11384 // An object of thread storage duration shall not require dynamic
11385 // initialization.
11386 // FIXME: Need strict checking here.
11387 Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11388 << CacheCulprit->getSourceRange();
11389 if (getLangOpts().CPlusPlus11)
11390 Diag(var->getLocation(), diag::note_use_thread_local);
11391 }
11392 }
11393 }
11394
11395 // Apply section attributes and pragmas to global variables.
11396 bool GlobalStorage = var->hasGlobalStorage();
11397 if (GlobalStorage && var->isThisDeclarationADefinition() &&
11398 !inTemplateInstantiation()) {
11399 PragmaStack<StringLiteral *> *Stack = nullptr;
11400 int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11401 if (var->getType().isConstQualified())
11402 Stack = &ConstSegStack;
11403 else if (!var->getInit()) {
11404 Stack = &BSSSegStack;
11405 SectionFlags |= ASTContext::PSF_Write;
11406 } else {
11407 Stack = &DataSegStack;
11408 SectionFlags |= ASTContext::PSF_Write;
11409 }
11410 if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11411 var->addAttr(SectionAttr::CreateImplicit(
11412 Context, SectionAttr::Declspec_allocate,
11413 Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11414 }
11415 if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11416 if (UnifySection(SA->getName(), SectionFlags, var))
11417 var->dropAttr<SectionAttr>();
11418
11419 // Apply the init_seg attribute if this has an initializer. If the
11420 // initializer turns out to not be dynamic, we'll end up ignoring this
11421 // attribute.
11422 if (CurInitSeg && var->getInit())
11423 var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11424 CurInitSegLoc));
11425 }
11426
11427 // All the following checks are C++ only.
11428 if (!getLangOpts().CPlusPlus) {
11429 // If this variable must be emitted, add it as an initializer for the
11430 // current module.
11431 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11432 Context.addModuleInitializer(ModuleScopes.back().Module, var);
11433 return;
11434 }
11435
11436 if (auto *DD = dyn_cast<DecompositionDecl>(var))
11437 CheckCompleteDecompositionDeclaration(DD);
11438
11439 QualType type = var->getType();
11440 if (type->isDependentType()) return;
11441
11442 // __block variables might require us to capture a copy-initializer.
11443 if (var->hasAttr<BlocksAttr>()) {
11444 // It's currently invalid to ever have a __block variable with an
11445 // array type; should we diagnose that here?
11446
11447 // Regardless, we don't want to ignore array nesting when
11448 // constructing this copy.
11449 if (type->isStructureOrClassType()) {
11450 EnterExpressionEvaluationContext scope(
11451 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
11452 SourceLocation poi = var->getLocation();
11453 Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
11454 ExprResult result
11455 = PerformMoveOrCopyInitialization(
11456 InitializedEntity::InitializeBlock(poi, type, false),
11457 var, var->getType(), varRef, /*AllowNRVO=*/true);
11458 if (!result.isInvalid()) {
11459 result = MaybeCreateExprWithCleanups(result);
11460 Expr *init = result.getAs<Expr>();
11461 Context.setBlockVarCopyInits(var, init);
11462 }
11463 }
11464 }
11465
11466 Expr *Init = var->getInit();
11467 bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11468 QualType baseType = Context.getBaseElementType(type);
11469
11470 if (Init && !Init->isValueDependent()) {
11471 if (var->isConstexpr()) {
11472 SmallVector<PartialDiagnosticAt, 8> Notes;
11473 if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11474 SourceLocation DiagLoc = var->getLocation();
11475 // If the note doesn't add any useful information other than a source
11476 // location, fold it into the primary diagnostic.
11477 if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11478 diag::note_invalid_subexpr_in_const_expr) {
11479 DiagLoc = Notes[0].first;
11480 Notes.clear();
11481 }
11482 Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11483 << var << Init->getSourceRange();
11484 for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11485 Diag(Notes[I].first, Notes[I].second);
11486 }
11487 } else if (var->isUsableInConstantExpressions(Context)) {
11488 // Check whether the initializer of a const variable of integral or
11489 // enumeration type is an ICE now, since we can't tell whether it was
11490 // initialized by a constant expression if we check later.
11491 var->checkInitIsICE();
11492 }
11493
11494 // Don't emit further diagnostics about constexpr globals since they
11495 // were just diagnosed.
11496 if (!var->isConstexpr() && GlobalStorage &&
11497 var->hasAttr<RequireConstantInitAttr>()) {
11498 // FIXME: Need strict checking in C++03 here.
11499 bool DiagErr = getLangOpts().CPlusPlus11
11500 ? !var->checkInitIsICE() : !checkConstInit();
11501 if (DiagErr) {
11502 auto attr = var->getAttr<RequireConstantInitAttr>();
11503 Diag(var->getLocation(), diag::err_require_constant_init_failed)
11504 << Init->getSourceRange();
11505 Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11506 << attr->getRange();
11507 if (getLangOpts().CPlusPlus11) {
11508 APValue Value;
11509 SmallVector<PartialDiagnosticAt, 8> Notes;
11510 Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11511 for (auto &it : Notes)
11512 Diag(it.first, it.second);
11513 } else {
11514 Diag(CacheCulprit->getExprLoc(),
11515 diag::note_invalid_subexpr_in_const_expr)
11516 << CacheCulprit->getSourceRange();
11517 }
11518 }
11519 }
11520 else if (!var->isConstexpr() && IsGlobal &&
11521 !getDiagnostics().isIgnored(diag::warn_global_constructor,
11522 var->getLocation())) {
11523 // Warn about globals which don't have a constant initializer. Don't
11524 // warn about globals with a non-trivial destructor because we already
11525 // warned about them.
11526 CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11527 if (!(RD && !RD->hasTrivialDestructor())) {
11528 if (!checkConstInit())
11529 Diag(var->getLocation(), diag::warn_global_constructor)
11530 << Init->getSourceRange();
11531 }
11532 }
11533 }
11534
11535 // Require the destructor.
11536 if (const RecordType *recordType = baseType->getAs<RecordType>())
11537 FinalizeVarWithDestructor(var, recordType);
11538
11539 // If this variable must be emitted, add it as an initializer for the current
11540 // module.
11541 if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11542 Context.addModuleInitializer(ModuleScopes.back().Module, var);
11543}
11544
11545/// \brief Determines if a variable's alignment is dependent.
11546static bool hasDependentAlignment(VarDecl *VD) {
11547 if (VD->getType()->isDependentType())
11548 return true;
11549 for (auto *I : VD->specific_attrs<AlignedAttr>())
11550 if (I->isAlignmentDependent())
11551 return true;
11552 return false;
11553}
11554
11555/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
11556/// any semantic actions necessary after any initializer has been attached.
11557void Sema::FinalizeDeclaration(Decl *ThisDecl) {
11558 // Note that we are no longer parsing the initializer for this declaration.
11559 ParsingInitForAutoVars.erase(ThisDecl);
11560
11561 VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
11562 if (!VD)
1
Assuming 'VD' is non-null
2
Taking false branch
11563 return;
11564
11565 // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
11566 if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
3
Assuming the condition is true
4
Taking true branch
11567 !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
11568 if (PragmaClangBSSSection.Valid)
5
Assuming the condition is false
6
Taking false branch
11569 VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
11570 PragmaClangBSSSection.SectionName,
11571 PragmaClangBSSSection.PragmaLocation));
11572 if (PragmaClangDataSection.Valid)
7
Assuming the condition is true
8
Taking true branch
11573 VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
9
Calling 'PragmaClangDataSectionAttr::CreateImplicit'
11574 PragmaClangDataSection.SectionName,
11575 PragmaClangDataSection.PragmaLocation));
11576 if (PragmaClangRodataSection.Valid)
11577 VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
11578 PragmaClangRodataSection.SectionName,
11579 PragmaClangRodataSection.PragmaLocation));
11580 }
11581
11582 if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
11583 for (auto *BD : DD->bindings()) {
11584 FinalizeDeclaration(BD);
11585 }
11586 }
11587
11588 checkAttributesAfterMerging(*this, *VD);
11589
11590 // Perform TLS alignment check here after attributes attached to the variable
11591 // which may affect the alignment have been processed. Only perform the check
11592 // if the target has a maximum TLS alignment (zero means no constraints).
11593 if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
11594 // Protect the check so that it's not performed on dependent types and
11595 // dependent alignments (we can't determine the alignment in that case).
11596 if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
11597 !VD->isInvalidDecl()) {
11598 CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
11599 if (Context.getDeclAlign(VD) > MaxAlignChars) {
11600 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
11601 << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
11602 << (unsigned)MaxAlignChars.getQuantity();
11603 }
11604 }
11605 }
11606
11607 if (VD->isStaticLocal()) {
11608 if (FunctionDecl *FD =
11609 dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
11610 // Static locals inherit dll attributes from their function.
11611 if (Attr *A = getDLLAttr(FD)) {
11612 auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
11613 NewAttr->setInherited(true);
11614 VD->addAttr(NewAttr);
11615 }
11616 // CUDA E.2.9.4: Within the body of a __device__ or __global__
11617 // function, only __shared__ variables may be declared with
11618 // static storage class.
11619 if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
11620 CUDADiagIfDeviceCode(VD->getLocation(),
11621 diag::err_device_static_local_var)
11622 << CurrentCUDATarget())
11623 VD->setInvalidDecl();
11624 }
11625 }
11626
11627 // Perform check for initializers of device-side global variables.
11628 // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
11629 // 7.5). We must also apply the same checks to all __shared__
11630 // variables whether they are local or not. CUDA also allows
11631 // constant initializers for __constant__ and __device__ variables.
11632 if (getLangOpts().CUDA) {
11633 const Expr *Init = VD->getInit();
11634 if (Init && VD->hasGlobalStorage()) {
11635 if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
11636 VD->hasAttr<CUDASharedAttr>()) {
11637 assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>())(static_cast <bool> (!VD->isStaticLocal() || VD->
hasAttr<CUDASharedAttr>()) ? void (0) : __assert_fail (
"!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 11637, __extension__ __PRETTY_FUNCTION__))
;
11638 bool AllowedInit = false;
11639 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
11640 AllowedInit =
11641 isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
11642 // We'll allow constant initializers even if it's a non-empty
11643 // constructor according to CUDA rules. This deviates from NVCC,
11644 // but allows us to handle things like constexpr constructors.
11645 if (!AllowedInit &&
11646 (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
11647 AllowedInit = VD->getInit()->isConstantInitializer(
11648 Context, VD->getType()->isReferenceType());
11649
11650 // Also make sure that destructor, if there is one, is empty.
11651 if (AllowedInit)
11652 if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
11653 AllowedInit =
11654 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
11655
11656 if (!AllowedInit) {
11657 Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
11658 ? diag::err_shared_var_init
11659 : diag::err_dynamic_var_init)
11660 << Init->getSourceRange();
11661 VD->setInvalidDecl();
11662 }
11663 } else {
11664 // This is a host-side global variable. Check that the initializer is
11665 // callable from the host side.
11666 const FunctionDecl *InitFn = nullptr;
11667 if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
11668 InitFn = CE->getConstructor();
11669 } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
11670 InitFn = CE->getDirectCallee();
11671 }
11672 if (InitFn) {
11673 CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
11674 if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
11675 Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
11676 << InitFnTarget << InitFn;
11677 Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
11678 VD->setInvalidDecl();
11679 }
11680 }
11681 }
11682 }
11683 }
11684
11685 // Grab the dllimport or dllexport attribute off of the VarDecl.
11686 const InheritableAttr *DLLAttr = getDLLAttr(VD);
11687
11688 // Imported static data members cannot be defined out-of-line.
11689 if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
11690 if (VD->isStaticDataMember() && VD->isOutOfLine() &&
11691 VD->isThisDeclarationADefinition()) {
11692 // We allow definitions of dllimport class template static data members
11693 // with a warning.
11694 CXXRecordDecl *Context =
11695 cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
11696 bool IsClassTemplateMember =
11697 isa<ClassTemplatePartialSpecializationDecl>(Context) ||
11698 Context->getDescribedClassTemplate();
11699
11700 Diag(VD->getLocation(),
11701 IsClassTemplateMember
11702 ? diag::warn_attribute_dllimport_static_field_definition
11703 : diag::err_attribute_dllimport_static_field_definition);
11704 Diag(IA->getLocation(), diag::note_attribute);
11705 if (!IsClassTemplateMember)
11706 VD->setInvalidDecl();
11707 }
11708 }
11709
11710 // dllimport/dllexport variables cannot be thread local, their TLS index
11711 // isn't exported with the variable.
11712 if (DLLAttr && VD->getTLSKind()) {
11713 auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11714 if (F && getDLLAttr(F)) {
11715 assert(VD->isStaticLocal())(static_cast <bool> (VD->isStaticLocal()) ? void (0)
: __assert_fail ("VD->isStaticLocal()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 11715, __extension__ __PRETTY_FUNCTION__))
;
11716 // But if this is a static local in a dlimport/dllexport function, the
11717 // function will never be inlined, which means the var would never be
11718 // imported, so having it marked import/export is safe.
11719 } else {
11720 Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
11721 << DLLAttr;
11722 VD->setInvalidDecl();
11723 }
11724 }
11725
11726 if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
11727 if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
11728 Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11729 VD->dropAttr<UsedAttr>();
11730 }
11731 }
11732
11733 const DeclContext *DC = VD->getDeclContext();
11734 // If there's a #pragma GCC visibility in scope, and this isn't a class
11735 // member, set the visibility of this variable.
11736 if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11737 AddPushedVisibilityAttribute(VD);
11738
11739 // FIXME: Warn on unused var template partial specializations.
11740 if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
11741 MarkUnusedFileScopedDecl(VD);
11742
11743 // Now we have parsed the initializer and can update the table of magic
11744 // tag values.
11745 if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11746 !VD->getType()->isIntegralOrEnumerationType())
11747 return;
11748
11749 for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11750 const Expr *MagicValueExpr = VD->getInit();
11751 if (!MagicValueExpr) {
11752 continue;
11753 }
11754 llvm::APSInt MagicValueInt;
11755 if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11756 Diag(I->getRange().getBegin(),
11757 diag::err_type_tag_for_datatype_not_ice)
11758 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11759 continue;
11760 }
11761 if (MagicValueInt.getActiveBits() > 64) {
11762 Diag(I->getRange().getBegin(),
11763 diag::err_type_tag_for_datatype_too_large)
11764 << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11765 continue;
11766 }
11767 uint64_t MagicValue = MagicValueInt.getZExtValue();
11768 RegisterTypeTagForDatatype(I->getArgumentKind(),
11769 MagicValue,
11770 I->getMatchingCType(),
11771 I->getLayoutCompatible(),
11772 I->getMustBeNull());
11773 }
11774}
11775
11776static bool hasDeducedAuto(DeclaratorDecl *DD) {
11777 auto *VD = dyn_cast<VarDecl>(DD);
11778 return VD && !VD->getType()->hasAutoForTrailingReturnType();
11779}
11780
11781Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
11782 ArrayRef<Decl *> Group) {
11783 SmallVector<Decl*, 8> Decls;
11784
11785 if (DS.isTypeSpecOwned())
11786 Decls.push_back(DS.getRepAsDecl());
11787
11788 DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11789 DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11790 bool DiagnosedMultipleDecomps = false;
11791 DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
11792 bool DiagnosedNonDeducedAuto = false;
11793
11794 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11795 if (Decl *D = Group[i]) {
11796 // For declarators, there are some additional syntactic-ish checks we need
11797 // to perform.
11798 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11799 if (!FirstDeclaratorInGroup)
11800 FirstDeclaratorInGroup = DD;
11801 if (!FirstDecompDeclaratorInGroup)
11802 FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
11803 if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
11804 !hasDeducedAuto(DD))
11805 FirstNonDeducedAutoInGroup = DD;
11806
11807 if (FirstDeclaratorInGroup != DD) {
11808 // A decomposition declaration cannot be combined with any other
11809 // declaration in the same group.
11810 if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
11811 Diag(FirstDecompDeclaratorInGroup->getLocation(),
11812 diag::err_decomp_decl_not_alone)
11813 << FirstDeclaratorInGroup->getSourceRange()
11814 << DD->getSourceRange();
11815 DiagnosedMultipleDecomps = true;
11816 }
11817
11818 // A declarator that uses 'auto' in any way other than to declare a
11819 // variable with a deduced type cannot be combined with any other
11820 // declarator in the same group.
11821 if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
11822 Diag(FirstNonDeducedAutoInGroup->getLocation(),
11823 diag::err_auto_non_deduced_not_alone)
11824 << FirstNonDeducedAutoInGroup->getType()
11825 ->hasAutoForTrailingReturnType()
11826 << FirstDeclaratorInGroup->getSourceRange()
11827 << DD->getSourceRange();
11828 DiagnosedNonDeducedAuto = true;
11829 }
11830 }
11831 }
11832
11833 Decls.push_back(D);
11834 }
11835 }
11836
11837 if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11838 if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11839 handleTagNumbering(Tag, S);
11840 if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11841 getLangOpts().CPlusPlus)
11842 Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11843 }
11844 }
11845
11846 return BuildDeclaratorGroup(Decls);
11847}
11848
11849/// BuildDeclaratorGroup - convert a list of declarations into a declaration
11850/// group, performing any necessary semantic checking.
11851Sema::DeclGroupPtrTy
11852Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
11853 // C++14 [dcl.spec.auto]p7: (DR1347)
11854 // If the type that replaces the placeholder type is not the same in each
11855 // deduction, the program is ill-formed.
11856 if (Group.size() > 1) {
11857 QualType Deduced;
11858 VarDecl *DeducedDecl = nullptr;
11859 for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11860 VarDecl *D = dyn_cast<VarDecl>(Group[i]);
11861 if (!D || D->isInvalidDecl())
11862 break;
11863 DeducedType *DT = D->getType()->getContainedDeducedType();
11864 if (!DT || DT->getDeducedType().isNull())
11865 continue;
11866 if (Deduced.isNull()) {
11867 Deduced = DT->getDeducedType();
11868 DeducedDecl = D;
11869 } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
11870 auto *AT = dyn_cast<AutoType>(DT);
11871 Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11872 diag::err_auto_different_deductions)
11873 << (AT ? (unsigned)AT->getKeyword() : 3)
11874 << Deduced << DeducedDecl->getDeclName()
11875 << DT->getDeducedType() << D->getDeclName()
11876 << DeducedDecl->getInit()->getSourceRange()
11877 << D->getInit()->getSourceRange();
11878 D->setInvalidDecl();
11879 break;
11880 }
11881 }
11882 }
11883
11884 ActOnDocumentableDecls(Group);
11885
11886 return DeclGroupPtrTy::make(
11887 DeclGroupRef::Create(Context, Group.data(), Group.size()));
11888}
11889
11890void Sema::ActOnDocumentableDecl(Decl *D) {
11891 ActOnDocumentableDecls(D);
11892}
11893
11894void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11895 // Don't parse the comment if Doxygen diagnostics are ignored.
11896 if (Group.empty() || !Group[0])
11897 return;
11898
11899 if (Diags.isIgnored(diag::warn_doc_param_not_found,
11900 Group[0]->getLocation()) &&
11901 Diags.isIgnored(diag::warn_unknown_comment_command_name,
11902 Group[0]->getLocation()))
11903 return;
11904
11905 if (Group.size() >= 2) {
11906 // This is a decl group. Normally it will contain only declarations
11907 // produced from declarator list. But in case we have any definitions or
11908 // additional declaration references:
11909 // 'typedef struct S {} S;'
11910 // 'typedef struct S *S;'
11911 // 'struct S *pS;'
11912 // FinalizeDeclaratorGroup adds these as separate declarations.
11913 Decl *MaybeTagDecl = Group[0];
11914 if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11915 Group = Group.slice(1);
11916 }
11917 }
11918
11919 // See if there are any new comments that are not attached to a decl.
11920 ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11921 if (!Comments.empty() &&
11922 !Comments.back()->isAttached()) {
11923 // There is at least one comment that not attached to a decl.
11924 // Maybe it should be attached to one of these decls?
11925 //
11926 // Note that this way we pick up not only comments that precede the
11927 // declaration, but also comments that *follow* the declaration -- thanks to
11928 // the lookahead in the lexer: we've consumed the semicolon and looked
11929 // ahead through comments.
11930 for (unsigned i = 0, e = Group.size(); i != e; ++i)
11931 Context.getCommentForDecl(Group[i], &PP);
11932 }
11933}
11934
11935/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11936/// to introduce parameters into function prototype scope.
11937Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11938 const DeclSpec &DS = D.getDeclSpec();
11939
11940 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11941
11942 // C++03 [dcl.stc]p2 also permits 'auto'.
11943 StorageClass SC = SC_None;
11944 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11945 SC = SC_Register;
11946 // In C++11, the 'register' storage class specifier is deprecated.
11947 // In C++17, it is not allowed, but we tolerate it as an extension.
11948 if (getLangOpts().CPlusPlus11) {
11949 Diag(DS.getStorageClassSpecLoc(),
11950 getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
11951 : diag::warn_deprecated_register)
11952 << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
11953 }
11954 } else if (getLangOpts().CPlusPlus &&
11955 DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11956 SC = SC_Auto;
11957 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11958 Diag(DS.getStorageClassSpecLoc(),
11959 diag::err_invalid_storage_class_in_func_decl);
11960 D.getMutableDeclSpec().ClearStorageClassSpecs();
11961 }
11962
11963 if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11964 Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11965 << DeclSpec::getSpecifierName(TSCS);
11966 if (DS.isInlineSpecified())
11967 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11968 << getLangOpts().CPlusPlus17;
11969 if (DS.isConstexprSpecified())
11970 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11971 << 0;
11972
11973 DiagnoseFunctionSpecifiers(DS);
11974
11975 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11976 QualType parmDeclType = TInfo->getType();
11977
11978 if (getLangOpts().CPlusPlus) {
11979 // Check that there are no default arguments inside the type of this
11980 // parameter.
11981 CheckExtraCXXDefaultArguments(D);
11982
11983 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11984 if (D.getCXXScopeSpec().isSet()) {
11985 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11986 << D.getCXXScopeSpec().getRange();
11987 D.getCXXScopeSpec().clear();
11988 }
11989 }
11990
11991 // Ensure we have a valid name
11992 IdentifierInfo *II = nullptr;
11993 if (D.hasName()) {
11994 II = D.getIdentifier();
11995 if (!II) {
11996 Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11997 << GetNameForDeclarator(D).getName();
11998 D.setInvalidType(true);
11999 }
12000 }
12001
12002 // Check for redeclaration of parameters, e.g. int foo(int x, int x);
12003 if (II) {
12004 LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
12005 ForVisibleRedeclaration);
12006 LookupName(R, S);
12007 if (R.isSingleResult()) {
12008 NamedDecl *PrevDecl = R.getFoundDecl();
12009 if (PrevDecl->isTemplateParameter()) {
12010 // Maybe we will complain about the shadowed template parameter.
12011 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12012 // Just pretend that we didn't see the previous declaration.
12013 PrevDecl = nullptr;
12014 } else if (S->isDeclScope(PrevDecl)) {
12015 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
12016 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12017
12018 // Recover by removing the name
12019 II = nullptr;
12020 D.SetIdentifier(nullptr, D.getIdentifierLoc());
12021 D.setInvalidType(true);
12022 }
12023 }
12024 }
12025
12026 // Temporarily put parameter variables in the translation unit, not
12027 // the enclosing context. This prevents them from accidentally
12028 // looking like class members in C++.
12029 ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
12030 D.getLocStart(),
12031 D.getIdentifierLoc(), II,
12032 parmDeclType, TInfo,
12033 SC);
12034
12035 if (D.isInvalidType())
12036 New->setInvalidDecl();
12037
12038 assert(S->isFunctionPrototypeScope())(static_cast <bool> (S->isFunctionPrototypeScope()) ?
void (0) : __assert_fail ("S->isFunctionPrototypeScope()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 12038, __extension__ __PRETTY_FUNCTION__))
;
12039 assert(S->getFunctionPrototypeDepth() >= 1)(static_cast <bool> (S->getFunctionPrototypeDepth() >=
1) ? void (0) : __assert_fail ("S->getFunctionPrototypeDepth() >= 1"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 12039, __extension__ __PRETTY_FUNCTION__))
;
12040 New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
12041 S->getNextFunctionPrototypeIndex());
12042
12043 // Add the parameter declaration into this scope.
12044 S->AddDecl(New);
12045 if (II)
12046 IdResolver.AddDecl(New);
12047
12048 ProcessDeclAttributes(S, New, D);
12049
12050 if (D.getDeclSpec().isModulePrivateSpecified())
12051 Diag(New->getLocation(), diag::err_module_private_local)
12052 << 1 << New->getDeclName()
12053 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12054 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12055
12056 if (New->hasAttr<BlocksAttr>()) {
12057 Diag(New->getLocation(), diag::err_block_on_nonlocal);
12058 }
12059 return New;
12060}
12061
12062/// \brief Synthesizes a variable for a parameter arising from a
12063/// typedef.
12064ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
12065 SourceLocation Loc,
12066 QualType T) {
12067 /* FIXME: setting StartLoc == Loc.
12068 Would it be worth to modify callers so as to provide proper source
12069 location for the unnamed parameters, embedding the parameter's type? */
12070 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
12071 T, Context.getTrivialTypeSourceInfo(T, Loc),
12072 SC_None, nullptr);
12073 Param->setImplicit();
12074 return Param;
12075}
12076
12077void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
12078 // Don't diagnose unused-parameter errors in template instantiations; we
12079 // will already have done so in the template itself.
12080 if (inTemplateInstantiation())
12081 return;
12082
12083 for (const ParmVarDecl *Parameter : Parameters) {
12084 if (!Parameter->isReferenced() && Parameter->getDeclName() &&
12085 !Parameter->hasAttr<UnusedAttr>()) {
12086 Diag(Parameter->getLocation(), diag::warn_unused_parameter)
12087 << Parameter->getDeclName();
12088 }
12089 }
12090}
12091
12092void Sema::DiagnoseSizeOfParametersAndReturnValue(
12093 ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
12094 if (LangOpts.NumLargeByValueCopy == 0) // No check.
12095 return;
12096
12097 // Warn if the return value is pass-by-value and larger than the specified
12098 // threshold.
12099 if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
12100 unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
12101 if (Size > LangOpts.NumLargeByValueCopy)
12102 Diag(D->getLocation(), diag::warn_return_value_size)
12103 << D->getDeclName() << Size;
12104 }
12105
12106 // Warn if any parameter is pass-by-value and larger than the specified
12107 // threshold.
12108 for (const ParmVarDecl *Parameter : Parameters) {
12109 QualType T = Parameter->getType();
12110 if (T->isDependentType() || !T.isPODType(Context))
12111 continue;
12112 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
12113 if (Size > LangOpts.NumLargeByValueCopy)
12114 Diag(Parameter->getLocation(), diag::warn_parameter_size)
12115 << Parameter->getDeclName() << Size;
12116 }
12117}
12118
12119ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
12120 SourceLocation NameLoc, IdentifierInfo *Name,
12121 QualType T, TypeSourceInfo *TSInfo,
12122 StorageClass SC) {
12123 // In ARC, infer a lifetime qualifier for appropriate parameter types.
12124 if (getLangOpts().ObjCAutoRefCount &&
12125 T.getObjCLifetime() == Qualifiers::OCL_None &&
12126 T->isObjCLifetimeType()) {
12127
12128 Qualifiers::ObjCLifetime lifetime;
12129
12130 // Special cases for arrays:
12131 // - if it's const, use __unsafe_unretained
12132 // - otherwise, it's an error
12133 if (T->isArrayType()) {
12134 if (!T.isConstQualified()) {
12135 DelayedDiagnostics.add(
12136 sema::DelayedDiagnostic::makeForbiddenType(
12137 NameLoc, diag::err_arc_array_param_no_ownership, T, false));
12138 }
12139 lifetime = Qualifiers::OCL_ExplicitNone;
12140 } else {
12141 lifetime = T->getObjCARCImplicitLifetime();
12142 }
12143 T = Context.getLifetimeQualifiedType(T, lifetime);
12144 }
12145
12146 ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
12147 Context.getAdjustedParameterType(T),
12148 TSInfo, SC, nullptr);
12149
12150 // Parameters can not be abstract class types.
12151 // For record types, this is done by the AbstractClassUsageDiagnoser once
12152 // the class has been completely parsed.
12153 if (!CurContext->isRecord() &&
12154 RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
12155 AbstractParamType))
12156 New->setInvalidDecl();
12157
12158 // Parameter declarators cannot be interface types. All ObjC objects are
12159 // passed by reference.
12160 if (T->isObjCObjectType()) {
12161 SourceLocation TypeEndLoc =
12162 getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
12163 Diag(NameLoc,
12164 diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
12165 << FixItHint::CreateInsertion(TypeEndLoc, "*");
12166 T = Context.getObjCObjectPointerType(T);
12167 New->setType(T);
12168 }
12169
12170 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
12171 // duration shall not be qualified by an address-space qualifier."
12172 // Since all parameters have automatic store duration, they can not have
12173 // an address space.
12174 if (T.getAddressSpace() != LangAS::Default &&
12175 // OpenCL allows function arguments declared to be an array of a type
12176 // to be qualified with an address space.
12177 !(getLangOpts().OpenCL &&
12178 (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
12179 Diag(NameLoc, diag::err_arg_with_address_space);
12180 New->setInvalidDecl();
12181 }
12182
12183 return New;
12184}
12185
12186void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
12187 SourceLocation LocAfterDecls) {
12188 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
12189
12190 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
12191 // for a K&R function.
12192 if (!FTI.hasPrototype) {
12193 for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
12194 --i;
12195 if (FTI.Params[i].Param == nullptr) {
12196 SmallString<256> Code;
12197 llvm::raw_svector_ostream(Code)
12198 << " int " << FTI.Params[i].Ident->getName() << ";\n";
12199 Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
12200 << FTI.Params[i].Ident
12201 << FixItHint::CreateInsertion(LocAfterDecls, Code);
12202
12203 // Implicitly declare the argument as type 'int' for lack of a better
12204 // type.
12205 AttributeFactory attrs;
12206 DeclSpec DS(attrs);
12207 const char* PrevSpec; // unused
12208 unsigned DiagID; // unused
12209 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
12210 DiagID, Context.getPrintingPolicy());
12211 // Use the identifier location for the type source range.
12212 DS.SetRangeStart(FTI.Params[i].IdentLoc);
12213 DS.SetRangeEnd(FTI.Params[i].IdentLoc);
12214 Declarator ParamD(DS, DeclaratorContext::KNRTypeListContext);
12215 ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
12216 FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
12217 }
12218 }
12219 }
12220}
12221
12222Decl *
12223Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
12224 MultiTemplateParamsArg TemplateParameterLists,
12225 SkipBodyInfo *SkipBody) {
12226 assert(getCurFunctionDecl() == nullptr && "Function parsing confused")(static_cast <bool> (getCurFunctionDecl() == nullptr &&
"Function parsing confused") ? void (0) : __assert_fail ("getCurFunctionDecl() == nullptr && \"Function parsing confused\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 12226, __extension__ __PRETTY_FUNCTION__))
;
12227 assert(D.isFunctionDeclarator() && "Not a function declarator!")(static_cast <bool> (D.isFunctionDeclarator() &&
"Not a function declarator!") ? void (0) : __assert_fail ("D.isFunctionDeclarator() && \"Not a function declarator!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 12227, __extension__ __PRETTY_FUNCTION__))
;
12228 Scope *ParentScope = FnBodyScope->getParent();
12229
12230 D.setFunctionDefinitionKind(FDK_Definition);
12231 Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
12232 return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
12233}
12234
12235void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
12236 Consumer.HandleInlineFunctionDefinition(D);
12237}
12238
12239static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
12240 const FunctionDecl*& PossibleZeroParamPrototype) {
12241 // Don't warn about invalid declarations.
12242 if (FD->isInvalidDecl())
12243 return false;
12244
12245 // Or declarations that aren't global.
12246 if (!FD->isGlobal())
12247 return false;
12248
12249 // Don't warn about C++ member functions.
12250 if (isa<CXXMethodDecl>(FD))
12251 return false;
12252
12253 // Don't warn about 'main'.
12254 if (FD->isMain())
12255 return false;
12256
12257 // Don't warn about inline functions.
12258 if (FD->isInlined())
12259 return false;
12260
12261 // Don't warn about function templates.
12262 if (FD->getDescribedFunctionTemplate())
12263 return false;
12264
12265 // Don't warn about function template specializations.
12266 if (FD->isFunctionTemplateSpecialization())
12267 return false;
12268
12269 // Don't warn for OpenCL kernels.
12270 if (FD->hasAttr<OpenCLKernelAttr>())
12271 return false;
12272
12273 // Don't warn on explicitly deleted functions.
12274 if (FD->isDeleted())
12275 return false;
12276
12277 bool MissingPrototype = true;
12278 for (const FunctionDecl *Prev = FD->getPreviousDecl();
12279 Prev; Prev = Prev->getPreviousDecl()) {
12280 // Ignore any declarations that occur in function or method
12281 // scope, because they aren't visible from the header.
12282 if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
12283 continue;
12284
12285 MissingPrototype = !Prev->getType()->isFunctionProtoType();
12286 if (FD->getNumParams() == 0)
12287 PossibleZeroParamPrototype = Prev;
12288 break;
12289 }
12290
12291 return MissingPrototype;
12292}
12293
12294void
12295Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
12296 const FunctionDecl *EffectiveDefinition,
12297 SkipBodyInfo *SkipBody) {
12298 const FunctionDecl *Definition = EffectiveDefinition;
12299 if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
12300 // If this is a friend function defined in a class template, it does not
12301 // have a body until it is used, nevertheless it is a definition, see
12302 // [temp.inst]p2:
12303 //
12304 // ... for the purpose of determining whether an instantiated redeclaration
12305 // is valid according to [basic.def.odr] and [class.mem], a declaration that
12306 // corresponds to a definition in the template is considered to be a
12307 // definition.
12308 //
12309 // The following code must produce redefinition error:
12310 //
12311 // template<typename T> struct C20 { friend void func_20() {} };
12312 // C20<int> c20i;
12313 // void func_20() {}
12314 //
12315 for (auto I : FD->redecls()) {
12316 if (I != FD && !I->isInvalidDecl() &&
12317 I->getFriendObjectKind() != Decl::FOK_None) {
12318 if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
12319 if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
12320 // A merged copy of the same function, instantiated as a member of
12321 // the same class, is OK.
12322 if (declaresSameEntity(OrigFD, Original) &&
12323 declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
12324 cast<Decl>(FD->getLexicalDeclContext())))
12325 continue;
12326 }
12327
12328 if (Original->isThisDeclarationADefinition()) {
12329 Definition = I;
12330 break;
12331 }
12332 }
12333 }
12334 }
12335 }
12336 if (!Definition)
12337 return;
12338
12339 if (canRedefineFunction(Definition, getLangOpts()))
12340 return;
12341
12342 // Don't emit an error when this is redefinition of a typo-corrected
12343 // definition.
12344 if (TypoCorrectedFunctionDefinitions.count(Definition))
12345 return;
12346
12347 // If we don't have a visible definition of the function, and it's inline or
12348 // a template, skip the new definition.
12349 if (SkipBody && !hasVisibleDefinition(Definition) &&
12350 (Definition->getFormalLinkage() == InternalLinkage ||
12351 Definition->isInlined() ||
12352 Definition->getDescribedFunctionTemplate() ||
12353 Definition->getNumTemplateParameterLists())) {
12354 SkipBody->ShouldSkip = true;
12355 if (auto *TD = Definition->getDescribedFunctionTemplate())
12356 makeMergedDefinitionVisible(TD);
12357 makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
12358 return;
12359 }
12360
12361 if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
12362 Definition->getStorageClass() == SC_Extern)
12363 Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
12364 << FD->getDeclName() << getLangOpts().CPlusPlus;
12365 else
12366 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12367
12368 Diag(Definition->getLocation(), diag::note_previous_definition);
12369 FD->setInvalidDecl();
12370}
12371
12372static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12373 Sema &S) {
12374 CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12375
12376 LambdaScopeInfo *LSI = S.PushLambdaScope();
12377 LSI->CallOperator = CallOperator;
12378 LSI->Lambda = LambdaClass;
12379 LSI->ReturnType = CallOperator->getReturnType();
12380 const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12381
12382 if (LCD == LCD_None)
12383 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12384 else if (LCD == LCD_ByCopy)
12385 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12386 else if (LCD == LCD_ByRef)
12387 LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12388 DeclarationNameInfo DNI = CallOperator->getNameInfo();
12389
12390 LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12391 LSI->Mutable = !CallOperator->isConst();
12392
12393 // Add the captures to the LSI so they can be noted as already
12394 // captured within tryCaptureVar.
12395 auto I = LambdaClass->field_begin();
12396 for (const auto &C : LambdaClass->captures()) {
12397 if (C.capturesVariable()) {
12398 VarDecl *VD = C.getCapturedVar();
12399 if (VD->isInitCapture())
12400 S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12401 QualType CaptureType = VD->getType();
12402 const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12403 LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12404 /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12405 /*EllipsisLoc*/C.isPackExpansion()
12406 ? C.getEllipsisLoc() : SourceLocation(),
12407 CaptureType, /*Expr*/ nullptr);
12408
12409 } else if (C.capturesThis()) {
12410 LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
12411 /*Expr*/ nullptr,
12412 C.getCaptureKind() == LCK_StarThis);
12413 } else {
12414 LSI->addVLATypeCapture(C.getLocation(), I->getType());
12415 }
12416 ++I;
12417 }
12418}
12419
12420Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
12421 SkipBodyInfo *SkipBody) {
12422 if (!D) {
12423 // Parsing the function declaration failed in some way. Push on a fake scope
12424 // anyway so we can try to parse the function body.
12425 PushFunctionScope();
12426 return D;
12427 }
12428
12429 FunctionDecl *FD = nullptr;
12430
12431 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
12432 FD = FunTmpl->getTemplatedDecl();
12433 else
12434 FD = cast<FunctionDecl>(D);
12435
12436 // Check for defining attributes before the check for redefinition.
12437 if (const auto *Attr = FD->getAttr<AliasAttr>()) {
12438 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
12439 FD->dropAttr<AliasAttr>();
12440 FD->setInvalidDecl();
12441 }
12442 if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12443 Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12444 FD->dropAttr<IFuncAttr>();
12445 FD->setInvalidDecl();
12446 }
12447
12448 // See if this is a redefinition. If 'will have body' is already set, then
12449 // these checks were already performed when it was set.
12450 if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
12451 CheckForFunctionRedefinition(FD, nullptr, SkipBody);
12452
12453 // If we're skipping the body, we're done. Don't enter the scope.
12454 if (SkipBody && SkipBody->ShouldSkip)
12455 return D;
12456 }
12457
12458 // Mark this function as "will have a body eventually". This lets users to
12459 // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12460 // this function.
12461 FD->setWillHaveBody();
12462
12463 // If we are instantiating a generic lambda call operator, push
12464 // a LambdaScopeInfo onto the function stack. But use the information
12465 // that's already been calculated (ActOnLambdaExpr) to prime the current
12466 // LambdaScopeInfo.
12467 // When the template operator is being specialized, the LambdaScopeInfo,
12468 // has to be properly restored so that tryCaptureVariable doesn't try
12469 // and capture any new variables. In addition when calculating potential
12470 // captures during transformation of nested lambdas, it is necessary to
12471 // have the LSI properly restored.
12472 if (isGenericLambdaCallOperatorSpecialization(FD)) {
12473 assert(inTemplateInstantiation() &&(static_cast <bool> (inTemplateInstantiation() &&
"There should be an active template instantiation on the stack "
"when instantiating a generic lambda!") ? void (0) : __assert_fail
("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 12475, __extension__ __PRETTY_FUNCTION__))
12474 "There should be an active template instantiation on the stack "(static_cast <bool> (inTemplateInstantiation() &&
"There should be an active template instantiation on the stack "
"when instantiating a generic lambda!") ? void (0) : __assert_fail
("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 12475, __extension__ __PRETTY_FUNCTION__))
12475 "when instantiating a generic lambda!")(static_cast <bool> (inTemplateInstantiation() &&
"There should be an active template instantiation on the stack "
"when instantiating a generic lambda!") ? void (0) : __assert_fail
("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 12475, __extension__ __PRETTY_FUNCTION__))
;
12476 RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12477 } else {
12478 // Enter a new function scope
12479 PushFunctionScope();
12480 }
12481
12482 // Builtin functions cannot be defined.
12483 if (unsigned BuiltinID = FD->getBuiltinID()) {
12484 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12485 !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12486 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12487 FD->setInvalidDecl();
12488 }
12489 }
12490
12491 // The return type of a function definition must be complete
12492 // (C99 6.9.1p3, C++ [dcl.fct]p6).
12493 QualType ResultType = FD->getReturnType();
12494 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12495 !FD->isInvalidDecl() &&
12496 RequireCompleteType(FD->getLocation(), ResultType,
12497 diag::err_func_def_incomplete_result))
12498 FD->setInvalidDecl();
12499
12500 if (FnBodyScope)
12501 PushDeclContext(FnBodyScope, FD);
12502
12503 // Check the validity of our function parameters
12504 CheckParmsForFunctionDef(FD->parameters(),
12505 /*CheckParameterNames=*/true);
12506
12507 // Add non-parameter declarations already in the function to the current
12508 // scope.
12509 if (FnBodyScope) {
12510 for (Decl *NPD : FD->decls()) {
12511 auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
12512 if (!NonParmDecl)
12513 continue;
12514 assert(!isa<ParmVarDecl>(NonParmDecl) &&(static_cast <bool> (!isa<ParmVarDecl>(NonParmDecl
) && "parameters should not be in newly created FD yet"
) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(NonParmDecl) && \"parameters should not be in newly created FD yet\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 12515, __extension__ __PRETTY_FUNCTION__))
12515 "parameters should not be in newly created FD yet")(static_cast <bool> (!isa<ParmVarDecl>(NonParmDecl
) && "parameters should not be in newly created FD yet"
) ? void (0) : __assert_fail ("!isa<ParmVarDecl>(NonParmDecl) && \"parameters should not be in newly created FD yet\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 12515, __extension__ __PRETTY_FUNCTION__))
;
12516
12517 // If the decl has a name, make it accessible in the current scope.
12518 if (NonParmDecl->getDeclName())
12519 PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
12520
12521 // Similarly, dive into enums and fish their constants out, making them
12522 // accessible in this scope.
12523 if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
12524 for (auto *EI : ED->enumerators())
12525 PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
12526 }
12527 }
12528 }
12529
12530 // Introduce our parameters into the function scope
12531 for (auto Param : FD->parameters()) {
12532 Param->setOwningFunction(FD);
12533
12534 // If this has an identifier, add it to the scope stack.
12535 if (Param->getIdentifier() && FnBodyScope) {
12536 CheckShadow(FnBodyScope, Param);
12537
12538 PushOnScopeChains(Param, FnBodyScope);
12539 }
12540 }
12541
12542 // Ensure that the function's exception specification is instantiated.
12543 if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
12544 ResolveExceptionSpec(D->getLocation(), FPT);
12545
12546 // dllimport cannot be applied to non-inline function definitions.
12547 if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
12548 !FD->isTemplateInstantiation()) {
12549 assert(!FD->hasAttr<DLLExportAttr>())(static_cast <bool> (!FD->hasAttr<DLLExportAttr>
()) ? void (0) : __assert_fail ("!FD->hasAttr<DLLExportAttr>()"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 12549, __extension__ __PRETTY_FUNCTION__))
;
12550 Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
12551 FD->setInvalidDecl();
12552 return D;
12553 }
12554 // We want to attach documentation to original Decl (which might be
12555 // a function template).
12556 ActOnDocumentableDecl(D);
12557 if (getCurLexicalContext()->isObjCContainer() &&
12558 getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
12559 getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
12560 Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
12561
12562 return D;
12563}
12564
12565/// \brief Given the set of return statements within a function body,
12566/// compute the variables that are subject to the named return value
12567/// optimization.
12568///
12569/// Each of the variables that is subject to the named return value
12570/// optimization will be marked as NRVO variables in the AST, and any
12571/// return statement that has a marked NRVO variable as its NRVO candidate can
12572/// use the named return value optimization.
12573///
12574/// This function applies a very simplistic algorithm for NRVO: if every return
12575/// statement in the scope of a variable has the same NRVO candidate, that
12576/// candidate is an NRVO variable.
12577void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
12578 ReturnStmt **Returns = Scope->Returns.data();
12579
12580 for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
12581 if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
12582 if (!NRVOCandidate->isNRVOVariable())
12583 Returns[I]->setNRVOCandidate(nullptr);
12584 }
12585 }
12586}
12587
12588bool Sema::canDelayFunctionBody(const Declarator &D) {
12589 // We can't delay parsing the body of a constexpr function template (yet).
12590 if (D.getDeclSpec().isConstexprSpecified())
12591 return false;
12592
12593 // We can't delay parsing the body of a function template with a deduced
12594 // return type (yet).
12595 if (D.getDeclSpec().hasAutoTypeSpec()) {
12596 // If the placeholder introduces a non-deduced trailing return type,
12597 // we can still delay parsing it.
12598 if (D.getNumTypeObjects()) {
12599 const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
12600 if (Outer.Kind == DeclaratorChunk::Function &&
12601 Outer.Fun.hasTrailingReturnType()) {
12602 QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
12603 return Ty.isNull() || !Ty->isUndeducedType();
12604 }
12605 }
12606 return false;
12607 }
12608
12609 return true;
12610}
12611
12612bool Sema::canSkipFunctionBody(Decl *D) {
12613 // We cannot skip the body of a function (or function template) which is
12614 // constexpr, since we may need to evaluate its body in order to parse the
12615 // rest of the file.
12616 // We cannot skip the body of a function with an undeduced return type,
12617 // because any callers of that function need to know the type.
12618 if (const FunctionDecl *FD = D->getAsFunction())
12619 if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
12620 return false;
12621 return Consumer.shouldSkipFunctionBody(D);
12622}
12623
12624Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
12625 if (!Decl)
12626 return nullptr;
12627 if (FunctionDecl *FD = Decl->getAsFunction())
12628 FD->setHasSkippedBody();
12629 else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
12630 MD->setHasSkippedBody();
12631 return Decl;
12632}
12633
12634Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
12635 return ActOnFinishFunctionBody(D, BodyArg, false);
12636}
12637
12638Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
12639 bool IsInstantiation) {
12640 FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
12641
12642 sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
12643 sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
12644
12645 if (getLangOpts().CoroutinesTS && getCurFunction()->isCoroutine())
12646 CheckCompletedCoroutineBody(FD, Body);
12647
12648 if (FD) {
12649 FD->setBody(Body);
12650 FD->setWillHaveBody(false);
12651
12652 if (getLangOpts().CPlusPlus14) {
12653 if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
12654 FD->getReturnType()->isUndeducedType()) {
12655 // If the function has a deduced result type but contains no 'return'
12656 // statements, the result type as written must be exactly 'auto', and
12657 // the deduced result type is 'void'.
12658 if (!FD->getReturnType()->getAs<AutoType>()) {
12659 Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
12660 << FD->getReturnType();
12661 FD->setInvalidDecl();
12662 } else {
12663 // Substitute 'void' for the 'auto' in the type.
12664 TypeLoc ResultType = getReturnTypeLoc(FD);
12665 Context.adjustDeducedFunctionResultType(
12666 FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
12667 }
12668 }
12669 } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
12670 // In C++11, we don't use 'auto' deduction rules for lambda call
12671 // operators because we don't support return type deduction.
12672 auto *LSI = getCurLambda();
12673 if (LSI->HasImplicitReturnType) {
12674 deduceClosureReturnType(*LSI);
12675
12676 // C++11 [expr.prim.lambda]p4:
12677 // [...] if there are no return statements in the compound-statement
12678 // [the deduced type is] the type void
12679 QualType RetType =
12680 LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
12681
12682 // Update the return type to the deduced type.
12683 const FunctionProtoType *Proto =
12684 FD->getType()->getAs<FunctionProtoType>();
12685 FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
12686 Proto->getExtProtoInfo()));
12687 }
12688 }
12689
12690 // If the function implicitly returns zero (like 'main') or is naked,
12691 // don't complain about missing return statements.
12692 if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
12693 WP.disableCheckFallThrough();
12694
12695 // MSVC permits the use of pure specifier (=0) on function definition,
12696 // defined at class scope, warn about this non-standard construct.
12697 if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
12698 Diag(FD->getLocation(), diag::ext_pure_function_definition);
12699
12700 if (!FD->isInvalidDecl()) {
12701 // Don't diagnose unused parameters of defaulted or deleted functions.
12702 if (!FD->isDeleted() && !FD->isDefaulted())
12703 DiagnoseUnusedParameters(FD->parameters());
12704 DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
12705 FD->getReturnType(), FD);
12706
12707 // If this is a structor, we need a vtable.
12708 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
12709 MarkVTableUsed(FD->getLocation(), Constructor->getParent());
12710 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
12711 MarkVTableUsed(FD->getLocation(), Destructor->getParent());
12712
12713 // Try to apply the named return value optimization. We have to check
12714 // if we can do this here because lambdas keep return statements around
12715 // to deduce an implicit return type.
12716 if (FD->getReturnType()->isRecordType() &&
12717 (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
12718 computeNRVO(Body, getCurFunction());
12719 }
12720
12721 // GNU warning -Wmissing-prototypes:
12722 // Warn if a global function is defined without a previous
12723 // prototype declaration. This warning is issued even if the
12724 // definition itself provides a prototype. The aim is to detect
12725 // global functions that fail to be declared in header files.
12726 const FunctionDecl *PossibleZeroParamPrototype = nullptr;
12727 if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
12728 Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
12729
12730 if (PossibleZeroParamPrototype) {
12731 // We found a declaration that is not a prototype,
12732 // but that could be a zero-parameter prototype
12733 if (TypeSourceInfo *TI =
12734 PossibleZeroParamPrototype->getTypeSourceInfo()) {
12735 TypeLoc TL = TI->getTypeLoc();
12736 if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
12737 Diag(PossibleZeroParamPrototype->getLocation(),
12738 diag::note_declaration_not_a_prototype)
12739 << PossibleZeroParamPrototype
12740 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
12741 }
12742 }
12743
12744 // GNU warning -Wstrict-prototypes
12745 // Warn if K&R function is defined without a previous declaration.
12746 // This warning is issued only if the definition itself does not provide
12747 // a prototype. Only K&R definitions do not provide a prototype.
12748 // An empty list in a function declarator that is part of a definition
12749 // of that function specifies that the function has no parameters
12750 // (C99 6.7.5.3p14)
12751 if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
12752 !LangOpts.CPlusPlus) {
12753 TypeSourceInfo *TI = FD->getTypeSourceInfo();
12754 TypeLoc TL = TI->getTypeLoc();
12755 FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
12756 Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
12757 }
12758 }
12759
12760 if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12761 const CXXMethodDecl *KeyFunction;
12762 if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
12763 MD->isVirtual() &&
12764 (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
12765 MD == KeyFunction->getCanonicalDecl()) {
12766 // Update the key-function state if necessary for this ABI.
12767 if (FD->isInlined() &&
12768 !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12769 Context.setNonKeyFunction(MD);
12770
12771 // If the newly-chosen key function is already defined, then we
12772 // need to mark the vtable as used retroactively.
12773 KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
12774 const FunctionDecl *Definition;
12775 if (KeyFunction && KeyFunction->isDefined(Definition))
12776 MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
12777 } else {
12778 // We just defined they key function; mark the vtable as used.
12779 MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
12780 }
12781 }
12782 }
12783
12784 assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&(static_cast <bool> ((FD == getCurFunctionDecl() || getCurLambda
()->CallOperator == FD) && "Function parsing confused"
) ? void (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 12785, __extension__ __PRETTY_FUNCTION__))
12785 "Function parsing confused")(static_cast <bool> ((FD == getCurFunctionDecl() || getCurLambda
()->CallOperator == FD) && "Function parsing confused"
) ? void (0) : __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 12785, __extension__ __PRETTY_FUNCTION__))
;
12786 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
12787 assert(MD == getCurMethodDecl() && "Method parsing confused")(static_cast <bool> (MD == getCurMethodDecl() &&
"Method parsing confused") ? void (0) : __assert_fail ("MD == getCurMethodDecl() && \"Method parsing confused\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 12787, __extension__ __PRETTY_FUNCTION__))
;
12788 MD->setBody(Body);
12789 if (!MD->isInvalidDecl()) {
12790 DiagnoseUnusedParameters(MD->parameters());
12791 DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
12792 MD->getReturnType(), MD);
12793
12794 if (Body)
12795 computeNRVO(Body, getCurFunction());
12796 }
12797 if (getCurFunction()->ObjCShouldCallSuper) {
12798 Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
12799 << MD->getSelector().getAsString();
12800 getCurFunction()->ObjCShouldCallSuper = false;
12801 }
12802 if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12803 const ObjCMethodDecl *InitMethod = nullptr;
12804 bool isDesignated =
12805 MD->isDesignatedInitializerForTheInterface(&InitMethod);
12806 assert(isDesignated && InitMethod)(static_cast <bool> (isDesignated && InitMethod
) ? void (0) : __assert_fail ("isDesignated && InitMethod"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 12806, __extension__ __PRETTY_FUNCTION__))
;
12807 (void)isDesignated;
12808
12809 auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12810 auto IFace = MD->getClassInterface();
12811 if (!IFace)
12812 return false;
12813 auto SuperD = IFace->getSuperClass();
12814 if (!SuperD)
12815 return false;
12816 return SuperD->getIdentifier() ==
12817 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12818 };
12819 // Don't issue this warning for unavailable inits or direct subclasses
12820 // of NSObject.
12821 if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12822 Diag(MD->getLocation(),
12823 diag::warn_objc_designated_init_missing_super_call);
12824 Diag(InitMethod->getLocation(),
12825 diag::note_objc_designated_init_marked_here);
12826 }
12827 getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12828 }
12829 if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12830 // Don't issue this warning for unavaialable inits.
12831 if (!MD->isUnavailable())
12832 Diag(MD->getLocation(),
12833 diag::warn_objc_secondary_init_missing_init_call);
12834 getCurFunction()->ObjCWarnForNoInitDelegation = false;
12835 }
12836 } else {
12837 // Parsing the function declaration failed in some way. Pop the fake scope
12838 // we pushed on.
12839 PopFunctionScopeInfo(ActivePolicy, dcl);
12840 return nullptr;
12841 }
12842
12843 if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12844 DiagnoseUnguardedAvailabilityViolations(dcl);
12845
12846 assert(!getCurFunction()->ObjCShouldCallSuper &&(static_cast <bool> (!getCurFunction()->ObjCShouldCallSuper
&& "This should only be set for ObjC methods, which should have been "
"handled in the block above.") ? void (0) : __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 12848, __extension__ __PRETTY_FUNCTION__))
12847 "This should only be set for ObjC methods, which should have been "(static_cast <bool> (!getCurFunction()->ObjCShouldCallSuper
&& "This should only be set for ObjC methods, which should have been "
"handled in the block above.") ? void (0) : __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 12848, __extension__ __PRETTY_FUNCTION__))
12848 "handled in the block above.")(static_cast <bool> (!getCurFunction()->ObjCShouldCallSuper
&& "This should only be set for ObjC methods, which should have been "
"handled in the block above.") ? void (0) : __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 12848, __extension__ __PRETTY_FUNCTION__))
;
12849
12850 // Verify and clean out per-function state.
12851 if (Body && (!FD || !FD->isDefaulted())) {
12852 // C++ constructors that have function-try-blocks can't have return
12853 // statements in the handlers of that block. (C++ [except.handle]p14)
12854 // Verify this.
12855 if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12856 DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12857
12858 // Verify that gotos and switch cases don't jump into scopes illegally.
12859 if (getCurFunction()->NeedsScopeChecking() &&
12860 !PP.isCodeCompletionEnabled())
12861 DiagnoseInvalidJumps(Body);
12862
12863 if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12864 if (!Destructor->getParent()->isDependentType())
12865 CheckDestructor(Destructor);
12866
12867 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12868 Destructor->getParent());
12869 }
12870
12871 // If any errors have occurred, clear out any temporaries that may have
12872 // been leftover. This ensures that these temporaries won't be picked up for
12873 // deletion in some later function.
12874 if (getDiagnostics().hasErrorOccurred() ||
12875 getDiagnostics().getSuppressAllDiagnostics()) {
12876 DiscardCleanupsInEvaluationContext();
12877 }
12878 if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12879 !isa<FunctionTemplateDecl>(dcl)) {
12880 // Since the body is valid, issue any analysis-based warnings that are
12881 // enabled.
12882 ActivePolicy = &WP;
12883 }
12884
12885 if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12886 (!CheckConstexprFunctionDecl(FD) ||
12887 !CheckConstexprFunctionBody(FD, Body)))
12888 FD->setInvalidDecl();
12889
12890 if (FD && FD->hasAttr<NakedAttr>()) {
12891 for (const Stmt *S : Body->children()) {
12892 // Allow local register variables without initializer as they don't
12893 // require prologue.
12894 bool RegisterVariables = false;
12895 if (auto *DS = dyn_cast<DeclStmt>(S)) {
12896 for (const auto *Decl : DS->decls()) {
12897 if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12898 RegisterVariables =
12899 Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12900 if (!RegisterVariables)
12901 break;
12902 }
12903 }
12904 }
12905 if (RegisterVariables)
12906 continue;
12907 if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12908 Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12909 Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12910 FD->setInvalidDecl();
12911 break;
12912 }
12913 }
12914 }
12915
12916 assert(ExprCleanupObjects.size() ==(static_cast <bool> (ExprCleanupObjects.size() == ExprEvalContexts
.back().NumCleanupObjects && "Leftover temporaries in function"
) ? void (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 12918, __extension__ __PRETTY_FUNCTION__))
12917 ExprEvalContexts.back().NumCleanupObjects &&(static_cast <bool> (ExprCleanupObjects.size() == ExprEvalContexts
.back().NumCleanupObjects && "Leftover temporaries in function"
) ? void (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 12918, __extension__ __PRETTY_FUNCTION__))
12918 "Leftover temporaries in function")(static_cast <bool> (ExprCleanupObjects.size() == ExprEvalContexts
.back().NumCleanupObjects && "Leftover temporaries in function"
) ? void (0) : __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 12918, __extension__ __PRETTY_FUNCTION__))
;
12919 assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function")(static_cast <bool> (!Cleanup.exprNeedsCleanups() &&
"Unaccounted cleanups in function") ? void (0) : __assert_fail
("!Cleanup.exprNeedsCleanups() && \"Unaccounted cleanups in function\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 12919, __extension__ __PRETTY_FUNCTION__))
;
12920 assert(MaybeODRUseExprs.empty() &&(static_cast <bool> (MaybeODRUseExprs.empty() &&
"Leftover expressions for odr-use checking") ? void (0) : __assert_fail
("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 12921, __extension__ __PRETTY_FUNCTION__))
12921 "Leftover expressions for odr-use checking")(static_cast <bool> (MaybeODRUseExprs.empty() &&
"Leftover expressions for odr-use checking") ? void (0) : __assert_fail
("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 12921, __extension__ __PRETTY_FUNCTION__))
;
12922 }
12923
12924 if (!IsInstantiation)
12925 PopDeclContext();
12926
12927 PopFunctionScopeInfo(ActivePolicy, dcl);
12928 // If any errors have occurred, clear out any temporaries that may have
12929 // been leftover. This ensures that these temporaries won't be picked up for
12930 // deletion in some later function.
12931 if (getDiagnostics().hasErrorOccurred()) {
12932 DiscardCleanupsInEvaluationContext();
12933 }
12934
12935 return dcl;
12936}
12937
12938/// When we finish delayed parsing of an attribute, we must attach it to the
12939/// relevant Decl.
12940void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12941 ParsedAttributes &Attrs) {
12942 // Always attach attributes to the underlying decl.
12943 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12944 D = TD->getTemplatedDecl();
12945 ProcessDeclAttributeList(S, D, Attrs.getList());
12946
12947 if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12948 if (Method->isStatic())
12949 checkThisInStaticMemberFunctionAttributes(Method);
12950}
12951
12952/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12953/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12954NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12955 IdentifierInfo &II, Scope *S) {
12956 // Find the scope in which the identifier is injected and the corresponding
12957 // DeclContext.
12958 // FIXME: C89 does not say what happens if there is no enclosing block scope.
12959 // In that case, we inject the declaration into the translation unit scope
12960 // instead.
12961 Scope *BlockScope = S;
12962 while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
12963 BlockScope = BlockScope->getParent();
12964
12965 Scope *ContextScope = BlockScope;
12966 while (!ContextScope->getEntity())
12967 ContextScope = ContextScope->getParent();
12968 ContextRAII SavedContext(*this, ContextScope->getEntity());
12969
12970 // Before we produce a declaration for an implicitly defined
12971 // function, see whether there was a locally-scoped declaration of
12972 // this name as a function or variable. If so, use that
12973 // (non-visible) declaration, and complain about it.
12974 NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
12975 if (ExternCPrev) {
12976 // We still need to inject the function into the enclosing block scope so
12977 // that later (non-call) uses can see it.
12978 PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
12979
12980 // C89 footnote 38:
12981 // If in fact it is not defined as having type "function returning int",
12982 // the behavior is undefined.
12983 if (!isa<FunctionDecl>(ExternCPrev) ||
12984 !Context.typesAreCompatible(
12985 cast<FunctionDecl>(ExternCPrev)->getType(),
12986 Context.getFunctionNoProtoType(Context.IntTy))) {
12987 Diag(Loc, diag::ext_use_out_of_scope_declaration)
12988 << ExternCPrev << !getLangOpts().C99;
12989 Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12990 return ExternCPrev;
12991 }
12992 }
12993
12994 // Extension in C99. Legal in C90, but warn about it.
12995 // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
12996 unsigned diag_id;
12997 if (II.getName().startswith("__builtin_"))
12998 diag_id = diag::warn_builtin_unknown;
12999 else if (getLangOpts().C99 || getLangOpts().OpenCL)
13000 diag_id = diag::ext_implicit_function_decl;
13001 else
13002 diag_id = diag::warn_implicit_function_decl;
13003 Diag(Loc, diag_id) << &II << getLangOpts().OpenCL;
13004
13005 // If we found a prior declaration of this function, don't bother building
13006 // another one. We've already pushed that one into scope, so there's nothing
13007 // more to do.
13008 if (ExternCPrev)
13009 return ExternCPrev;
13010
13011 // Because typo correction is expensive, only do it if the implicit
13012 // function declaration is going to be treated as an error.
13013 if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
13014 TypoCorrection Corrected;
13015 if (S &&
13016 (Corrected = CorrectTypo(
13017 DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
13018 llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
13019 diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
13020 /*ErrorRecovery*/false);
13021 }
13022
13023 // Set a Declarator for the implicit definition: int foo();
13024 const char *Dummy;
13025 AttributeFactory attrFactory;
13026 DeclSpec DS(attrFactory);
13027 unsigned DiagID;
13028 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
13029 Context.getPrintingPolicy());
13030 (void)Error; // Silence warning.
13031 assert(!Error && "Error setting up implicit decl!")(static_cast <bool> (!Error && "Error setting up implicit decl!"
) ? void (0) : __assert_fail ("!Error && \"Error setting up implicit decl!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 13031, __extension__ __PRETTY_FUNCTION__))
;
13032 SourceLocation NoLoc;
13033 Declarator D(DS, DeclaratorContext::BlockContext);
13034 D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
13035 /*IsAmbiguous=*/false,
13036 /*LParenLoc=*/NoLoc,
13037 /*Params=*/nullptr,
13038 /*NumParams=*/0,
13039 /*EllipsisLoc=*/NoLoc,
13040 /*RParenLoc=*/NoLoc,
13041 /*TypeQuals=*/0,
13042 /*RefQualifierIsLvalueRef=*/true,
13043 /*RefQualifierLoc=*/NoLoc,
13044 /*ConstQualifierLoc=*/NoLoc,
13045 /*VolatileQualifierLoc=*/NoLoc,
13046 /*RestrictQualifierLoc=*/NoLoc,
13047 /*MutableLoc=*/NoLoc,
13048 EST_None,
13049 /*ESpecRange=*/SourceRange(),
13050 /*Exceptions=*/nullptr,
13051 /*ExceptionRanges=*/nullptr,
13052 /*NumExceptions=*/0,
13053 /*NoexceptExpr=*/nullptr,
13054 /*ExceptionSpecTokens=*/nullptr,
13055 /*DeclsInPrototype=*/None,
13056 Loc, Loc, D),
13057 DS.getAttributes(),
13058 SourceLocation());
13059 D.SetIdentifier(&II, Loc);
13060
13061 // Insert this function into the enclosing block scope.
13062 FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
13063 FD->setImplicit();
13064
13065 AddKnownFunctionAttributes(FD);
13066
13067 return FD;
13068}
13069
13070/// \brief Adds any function attributes that we know a priori based on
13071/// the declaration of this function.
13072///
13073/// These attributes can apply both to implicitly-declared builtins
13074/// (like __builtin___printf_chk) or to library-declared functions
13075/// like NSLog or printf.
13076///
13077/// We need to check for duplicate attributes both here and where user-written
13078/// attributes are applied to declarations.
13079void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
13080 if (FD->isInvalidDecl())
13081 return;
13082
13083 // If this is a built-in function, map its builtin attributes to
13084 // actual attributes.
13085 if (unsigned BuiltinID = FD->getBuiltinID()) {
13086 // Handle printf-formatting attributes.
13087 unsigned FormatIdx;
13088 bool HasVAListArg;
13089 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
13090 if (!FD->hasAttr<FormatAttr>()) {
13091 const char *fmt = "printf";
13092 unsigned int NumParams = FD->getNumParams();
13093 if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
13094 FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
13095 fmt = "NSString";
13096 FD->addAttr(FormatAttr::CreateImplicit(Context,
13097 &Context.Idents.get(fmt),
13098 FormatIdx+1,
13099 HasVAListArg ? 0 : FormatIdx+2,
13100 FD->getLocation()));
13101 }
13102 }
13103 if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
13104 HasVAListArg)) {
13105 if (!FD->hasAttr<FormatAttr>())
13106 FD->addAttr(FormatAttr::CreateImplicit(Context,
13107 &Context.Idents.get("scanf"),
13108 FormatIdx+1,
13109 HasVAListArg ? 0 : FormatIdx+2,
13110 FD->getLocation()));
13111 }
13112
13113 // Mark const if we don't care about errno and that is the only thing
13114 // preventing the function from being const. This allows IRgen to use LLVM
13115 // intrinsics for such functions.
13116 if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
13117 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
13118 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13119
13120 // We make "fma" on some platforms const because we know it does not set
13121 // errno in those environments even though it could set errno based on the
13122 // C standard.
13123 const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
13124 if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
13125 !FD->hasAttr<ConstAttr>()) {
13126 switch (BuiltinID) {
13127 case Builtin::BI__builtin_fma:
13128 case Builtin::BI__builtin_fmaf:
13129 case Builtin::BI__builtin_fmal:
13130 case Builtin::BIfma:
13131 case Builtin::BIfmaf:
13132 case Builtin::BIfmal:
13133 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13134 break;
13135 default:
13136 break;
13137 }
13138 }
13139
13140 if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
13141 !FD->hasAttr<ReturnsTwiceAttr>())
13142 FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
13143 FD->getLocation()));
13144 if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
13145 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13146 if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
13147 FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
13148 if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
13149 FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13150 if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
13151 !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
13152 // Add the appropriate attribute, depending on the CUDA compilation mode
13153 // and which target the builtin belongs to. For example, during host
13154 // compilation, aux builtins are __device__, while the rest are __host__.
13155 if (getLangOpts().CUDAIsDevice !=
13156 Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
13157 FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
13158 else
13159 FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
13160 }
13161 }
13162
13163 // If C++ exceptions are enabled but we are told extern "C" functions cannot
13164 // throw, add an implicit nothrow attribute to any extern "C" function we come
13165 // across.
13166 if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
13167 FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
13168 const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
13169 if (!FPT || FPT->getExceptionSpecType() == EST_None)
13170 FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13171 }
13172
13173 IdentifierInfo *Name = FD->getIdentifier();
13174 if (!Name)
13175 return;
13176 if ((!getLangOpts().CPlusPlus &&
13177 FD->getDeclContext()->isTranslationUnit()) ||
13178 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
13179 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
13180 LinkageSpecDecl::lang_c)) {
13181 // Okay: this could be a libc/libm/Objective-C function we know
13182 // about.
13183 } else
13184 return;
13185
13186 if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
13187 // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
13188 // target-specific builtins, perhaps?
13189 if (!FD->hasAttr<FormatAttr>())
13190 FD->addAttr(FormatAttr::CreateImplicit(Context,
13191 &Context.Idents.get("printf"), 2,
13192 Name->isStr("vasprintf") ? 0 : 3,
13193 FD->getLocation()));
13194 }
13195
13196 if (Name->isStr("__CFStringMakeConstantString")) {
13197 // We already have a __builtin___CFStringMakeConstantString,
13198 // but builds that use -fno-constant-cfstrings don't go through that.
13199 if (!FD->hasAttr<FormatArgAttr>())
13200 FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
13201 FD->getLocation()));
13202 }
13203}
13204
13205TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
13206 TypeSourceInfo *TInfo) {
13207 assert(D.getIdentifier() && "Wrong callback for declspec without declarator")(static_cast <bool> (D.getIdentifier() && "Wrong callback for declspec without declarator"
) ? void (0) : __assert_fail ("D.getIdentifier() && \"Wrong callback for declspec without declarator\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 13207, __extension__ __PRETTY_FUNCTION__))
;
13208 assert(!T.isNull() && "GetTypeForDeclarator() returned null type")(static_cast <bool> (!T.isNull() && "GetTypeForDeclarator() returned null type"
) ? void (0) : __assert_fail ("!T.isNull() && \"GetTypeForDeclarator() returned null type\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 13208, __extension__ __PRETTY_FUNCTION__))
;
13209
13210 if (!TInfo) {
13211 assert(D.isInvalidType() && "no declarator info for valid type")(static_cast <bool> (D.isInvalidType() && "no declarator info for valid type"
) ? void (0) : __assert_fail ("D.isInvalidType() && \"no declarator info for valid type\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 13211, __extension__ __PRETTY_FUNCTION__))
;
13212 TInfo = Context.getTrivialTypeSourceInfo(T);
13213 }
13214
13215 // Scope manipulation handled by caller.
13216 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
13217 D.getLocStart(),
13218 D.getIdentifierLoc(),
13219 D.getIdentifier(),
13220 TInfo);
13221
13222 // Bail out immediately if we have an invalid declaration.
13223 if (D.isInvalidType()) {
13224 NewTD->setInvalidDecl();
13225 return NewTD;
13226 }
13227
13228 if (D.getDeclSpec().isModulePrivateSpecified()) {
13229 if (CurContext->isFunctionOrMethod())
13230 Diag(NewTD->getLocation(), diag::err_module_private_local)
13231 << 2 << NewTD->getDeclName()
13232 << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13233 << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13234 else
13235 NewTD->setModulePrivate();
13236 }
13237
13238 // C++ [dcl.typedef]p8:
13239 // If the typedef declaration defines an unnamed class (or
13240 // enum), the first typedef-name declared by the declaration
13241 // to be that class type (or enum type) is used to denote the
13242 // class type (or enum type) for linkage purposes only.
13243 // We need to check whether the type was declared in the declaration.
13244 switch (D.getDeclSpec().getTypeSpecType()) {
13245 case TST_enum:
13246 case TST_struct:
13247 case TST_interface:
13248 case TST_union:
13249 case TST_class: {
13250 TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
13251 setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
13252 break;
13253 }
13254
13255 default:
13256 break;
13257 }
13258
13259 return NewTD;
13260}
13261
13262/// \brief Check that this is a valid underlying type for an enum declaration.
13263bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
13264 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
13265 QualType T = TI->getType();
13266
13267 if (T->isDependentType())
13268 return false;
13269
13270 if (const BuiltinType *BT = T->getAs<BuiltinType>())
13271 if (BT->isInteger())
13272 return false;
13273
13274 Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
13275 return true;
13276}
13277
13278/// Check whether this is a valid redeclaration of a previous enumeration.
13279/// \return true if the redeclaration was invalid.
13280bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
13281 QualType EnumUnderlyingTy, bool IsFixed,
13282 const EnumDecl *Prev) {
13283 if (IsScoped != Prev->isScoped()) {
13284 Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
13285 << Prev->isScoped();
13286 Diag(Prev->getLocation(), diag::note_previous_declaration);
13287 return true;
13288 }
13289
13290 if (IsFixed && Prev->isFixed()) {
13291 if (!EnumUnderlyingTy->isDependentType() &&
13292 !Prev->getIntegerType()->isDependentType() &&
13293 !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
13294 Prev->getIntegerType())) {
13295 // TODO: Highlight the underlying type of the redeclaration.
13296 Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
13297 << EnumUnderlyingTy << Prev->getIntegerType();
13298 Diag(Prev->getLocation(), diag::note_previous_declaration)
13299 << Prev->getIntegerTypeRange();
13300 return true;
13301 }
13302 } else if (IsFixed != Prev->isFixed()) {
13303 Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
13304 << Prev->isFixed();
13305 Diag(Prev->getLocation(), diag::note_previous_declaration);
13306 return true;
13307 }
13308
13309 return false;
13310}
13311
13312/// \brief Get diagnostic %select index for tag kind for
13313/// redeclaration diagnostic message.
13314/// WARNING: Indexes apply to particular diagnostics only!
13315///
13316/// \returns diagnostic %select index.
13317static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
13318 switch (Tag) {
13319 case TTK_Struct: return 0;
13320 case TTK_Interface: return 1;
13321 case TTK_Class: return 2;
13322 default: llvm_unreachable("Invalid tag kind for redecl diagnostic!")::llvm::llvm_unreachable_internal("Invalid tag kind for redecl diagnostic!"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 13322)
;
13323 }
13324}
13325
13326/// \brief Determine if tag kind is a class-key compatible with
13327/// class for redeclaration (class, struct, or __interface).
13328///
13329/// \returns true iff the tag kind is compatible.
13330static bool isClassCompatTagKind(TagTypeKind Tag)
13331{
13332 return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
13333}
13334
13335Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
13336 TagTypeKind TTK) {
13337 if (isa<TypedefDecl>(PrevDecl))
13338 return NTK_Typedef;
13339 else if (isa<TypeAliasDecl>(PrevDecl))
13340 return NTK_TypeAlias;
13341 else if (isa<ClassTemplateDecl>(PrevDecl))
13342 return NTK_Template;
13343 else if (isa<TypeAliasTemplateDecl>(PrevDecl))
13344 return NTK_TypeAliasTemplate;
13345 else if (isa<TemplateTemplateParmDecl>(PrevDecl))
13346 return NTK_TemplateTemplateArgument;
13347 switch (TTK) {
13348 case TTK_Struct:
13349 case TTK_Interface:
13350 case TTK_Class:
13351 return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
13352 case TTK_Union:
13353 return NTK_NonUnion;
13354 case TTK_Enum:
13355 return NTK_NonEnum;
13356 }
13357 llvm_unreachable("invalid TTK")::llvm::llvm_unreachable_internal("invalid TTK", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 13357)
;
13358}
13359
13360/// \brief Determine whether a tag with a given kind is acceptable
13361/// as a redeclaration of the given tag declaration.
13362///
13363/// \returns true if the new tag kind is acceptable, false otherwise.
13364bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
13365 TagTypeKind NewTag, bool isDefinition,
13366 SourceLocation NewTagLoc,
13367 const IdentifierInfo *Name) {
13368 // C++ [dcl.type.elab]p3:
13369 // The class-key or enum keyword present in the
13370 // elaborated-type-specifier shall agree in kind with the
13371 // declaration to which the name in the elaborated-type-specifier
13372 // refers. This rule also applies to the form of
13373 // elaborated-type-specifier that declares a class-name or
13374 // friend class since it can be construed as referring to the
13375 // definition of the class. Thus, in any
13376 // elaborated-type-specifier, the enum keyword shall be used to
13377 // refer to an enumeration (7.2), the union class-key shall be
13378 // used to refer to a union (clause 9), and either the class or
13379 // struct class-key shall be used to refer to a class (clause 9)
13380 // declared using the class or struct class-key.
13381 TagTypeKind OldTag = Previous->getTagKind();
13382 if (!isDefinition || !isClassCompatTagKind(NewTag))
13383 if (OldTag == NewTag)
13384 return true;
13385
13386 if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
13387 // Warn about the struct/class tag mismatch.
13388 bool isTemplate = false;
13389 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
13390 isTemplate = Record->getDescribedClassTemplate();
13391
13392 if (inTemplateInstantiation()) {
13393 // In a template instantiation, do not offer fix-its for tag mismatches
13394 // since they usually mess up the template instead of fixing the problem.
13395 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13396 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13397 << getRedeclDiagFromTagKind(OldTag);
13398 return true;
13399 }
13400
13401 if (isDefinition) {
13402 // On definitions, check previous tags and issue a fix-it for each
13403 // one that doesn't match the current tag.
13404 if (Previous->getDefinition()) {
13405 // Don't suggest fix-its for redefinitions.
13406 return true;
13407 }
13408
13409 bool previousMismatch = false;
13410 for (auto I : Previous->redecls()) {
13411 if (I->getTagKind() != NewTag) {
13412 if (!previousMismatch) {
13413 previousMismatch = true;
13414 Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
13415 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13416 << getRedeclDiagFromTagKind(I->getTagKind());
13417 }
13418 Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
13419 << getRedeclDiagFromTagKind(NewTag)
13420 << FixItHint::CreateReplacement(I->getInnerLocStart(),
13421 TypeWithKeyword::getTagTypeKindName(NewTag));
13422 }
13423 }
13424 return true;
13425 }
13426
13427 // Check for a previous definition. If current tag and definition
13428 // are same type, do nothing. If no definition, but disagree with
13429 // with previous tag type, give a warning, but no fix-it.
13430 const TagDecl *Redecl = Previous->getDefinition() ?
13431 Previous->getDefinition() : Previous;
13432 if (Redecl->getTagKind() == NewTag) {
13433 return true;
13434 }
13435
13436 Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13437 << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13438 << getRedeclDiagFromTagKind(OldTag);
13439 Diag(Redecl->getLocation(), diag::note_previous_use);
13440
13441 // If there is a previous definition, suggest a fix-it.
13442 if (Previous->getDefinition()) {
13443 Diag(NewTagLoc, diag::note_struct_class_suggestion)
13444 << getRedeclDiagFromTagKind(Redecl->getTagKind())
13445 << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
13446 TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
13447 }
13448
13449 return true;
13450 }
13451 return false;
13452}
13453
13454/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
13455/// from an outer enclosing namespace or file scope inside a friend declaration.
13456/// This should provide the commented out code in the following snippet:
13457/// namespace N {
13458/// struct X;
13459/// namespace M {
13460/// struct Y { friend struct /*N::*/ X; };
13461/// }
13462/// }
13463static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
13464 SourceLocation NameLoc) {
13465 // While the decl is in a namespace, do repeated lookup of that name and see
13466 // if we get the same namespace back. If we do not, continue until
13467 // translation unit scope, at which point we have a fully qualified NNS.
13468 SmallVector<IdentifierInfo *, 4> Namespaces;
13469 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13470 for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
13471 // This tag should be declared in a namespace, which can only be enclosed by
13472 // other namespaces. Bail if there's an anonymous namespace in the chain.
13473 NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
13474 if (!Namespace || Namespace->isAnonymousNamespace())
13475 return FixItHint();
13476 IdentifierInfo *II = Namespace->getIdentifier();
13477 Namespaces.push_back(II);
13478 NamedDecl *Lookup = SemaRef.LookupSingleName(
13479 S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
13480 if (Lookup == Namespace)
13481 break;
13482 }
13483
13484 // Once we have all the namespaces, reverse them to go outermost first, and
13485 // build an NNS.
13486 SmallString<64> Insertion;
13487 llvm::raw_svector_ostream OS(Insertion);
13488 if (DC->isTranslationUnit())
13489 OS << "::";
13490 std::reverse(Namespaces.begin(), Namespaces.end());
13491 for (auto *II : Namespaces)
13492 OS << II->getName() << "::";
13493 return FixItHint::CreateInsertion(NameLoc, Insertion);
13494}
13495
13496/// \brief Determine whether a tag originally declared in context \p OldDC can
13497/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
13498/// found a declaration in \p OldDC as a previous decl, perhaps through a
13499/// using-declaration).
13500static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
13501 DeclContext *NewDC) {
13502 OldDC = OldDC->getRedeclContext();
13503 NewDC = NewDC->getRedeclContext();
13504
13505 if (OldDC->Equals(NewDC))
13506 return true;
13507
13508 // In MSVC mode, we allow a redeclaration if the contexts are related (either
13509 // encloses the other).
13510 if (S.getLangOpts().MSVCCompat &&
13511 (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
13512 return true;
13513
13514 return false;
13515}
13516
13517/// \brief This is invoked when we see 'struct foo' or 'struct {'. In the
13518/// former case, Name will be non-null. In the later case, Name will be null.
13519/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
13520/// reference/declaration/definition of a tag.
13521///
13522/// \param IsTypeSpecifier \c true if this is a type-specifier (or
13523/// trailing-type-specifier) other than one in an alias-declaration.
13524///
13525/// \param SkipBody If non-null, will be set to indicate if the caller should
13526/// skip the definition of this tag and treat it as if it were a declaration.
13527Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
13528 SourceLocation KWLoc, CXXScopeSpec &SS,
13529 IdentifierInfo *Name, SourceLocation NameLoc,
13530 AttributeList *Attr, AccessSpecifier AS,
13531 SourceLocation ModulePrivateLoc,
13532 MultiTemplateParamsArg TemplateParameterLists,
13533 bool &OwnedDecl, bool &IsDependent,
13534 SourceLocation ScopedEnumKWLoc,
13535 bool ScopedEnumUsesClassTag,
13536 TypeResult UnderlyingType,
13537 bool IsTypeSpecifier, bool IsTemplateParamOrArg,
13538 SkipBodyInfo *SkipBody) {
13539 // If this is not a definition, it must have a name.
13540 IdentifierInfo *OrigName = Name;
13541 assert((Name != nullptr || TUK == TUK_Definition) &&(static_cast <bool> ((Name != nullptr || TUK == TUK_Definition
) && "Nameless record must be a definition!") ? void (
0) : __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 13542, __extension__ __PRETTY_FUNCTION__))
13542 "Nameless record must be a definition!")(static_cast <bool> ((Name != nullptr || TUK == TUK_Definition
) && "Nameless record must be a definition!") ? void (
0) : __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 13542, __extension__ __PRETTY_FUNCTION__))
;
13543 assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference)(static_cast <bool> (TemplateParameterLists.size() == 0
|| TUK != TUK_Reference) ? void (0) : __assert_fail ("TemplateParameterLists.size() == 0 || TUK != TUK_Reference"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 13543, __extension__ __PRETTY_FUNCTION__))
;
13544
13545 OwnedDecl = false;
13546 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13547 bool ScopedEnum = ScopedEnumKWLoc.isValid();
13548
13549 // FIXME: Check member specializations more carefully.
13550 bool isMemberSpecialization = false;
13551 bool Invalid = false;
13552
13553 // We only need to do this matching if we have template parameters
13554 // or a scope specifier, which also conveniently avoids this work
13555 // for non-C++ cases.
13556 if (TemplateParameterLists.size() > 0 ||
13557 (SS.isNotEmpty() && TUK != TUK_Reference)) {
13558 if (TemplateParameterList *TemplateParams =
13559 MatchTemplateParametersToScopeSpecifier(
13560 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
13561 TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
13562 if (Kind == TTK_Enum) {
13563 Diag(KWLoc, diag::err_enum_template);
13564 return nullptr;
13565 }
13566
13567 if (TemplateParams->size() > 0) {
13568 // This is a declaration or definition of a class template (which may
13569 // be a member of another template).
13570
13571 if (Invalid)
13572 return nullptr;
13573
13574 OwnedDecl = false;
13575 DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
13576 SS, Name, NameLoc, Attr,
13577 TemplateParams, AS,
13578 ModulePrivateLoc,
13579 /*FriendLoc*/SourceLocation(),
13580 TemplateParameterLists.size()-1,
13581 TemplateParameterLists.data(),
13582 SkipBody);
13583 return Result.get();
13584 } else {
13585 // The "template<>" header is extraneous.
13586 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13587 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13588 isMemberSpecialization = true;
13589 }
13590 }
13591 }
13592
13593 // Figure out the underlying type if this a enum declaration. We need to do
13594 // this early, because it's needed to detect if this is an incompatible
13595 // redeclaration.
13596 llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
13597 bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
13598
13599 if (Kind == TTK_Enum) {
13600 if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
13601 // No underlying type explicitly specified, or we failed to parse the
13602 // type, default to int.
13603 EnumUnderlying = Context.IntTy.getTypePtr();
13604 } else if (UnderlyingType.get()) {
13605 // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
13606 // integral type; any cv-qualification is ignored.
13607 TypeSourceInfo *TI = nullptr;
13608 GetTypeFromParser(UnderlyingType.get(), &TI);
13609 EnumUnderlying = TI;
13610
13611 if (CheckEnumUnderlyingType(TI))
13612 // Recover by falling back to int.
13613 EnumUnderlying = Context.IntTy.getTypePtr();
13614
13615 if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
13616 UPPC_FixedUnderlyingType))
13617 EnumUnderlying = Context.IntTy.getTypePtr();
13618
13619 } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
13620 // For MSVC ABI compatibility, unfixed enums must use an underlying type
13621 // of 'int'. However, if this is an unfixed forward declaration, don't set
13622 // the underlying type unless the user enables -fms-compatibility. This
13623 // makes unfixed forward declared enums incomplete and is more conforming.
13624 if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
13625 EnumUnderlying = Context.IntTy.getTypePtr();
13626 }
13627 }
13628
13629 DeclContext *SearchDC = CurContext;
13630 DeclContext *DC = CurContext;
13631 bool isStdBadAlloc = false;
13632 bool isStdAlignValT = false;
13633
13634 RedeclarationKind Redecl = forRedeclarationInCurContext();
13635 if (TUK == TUK_Friend || TUK == TUK_Reference)
13636 Redecl = NotForRedeclaration;
13637
13638 /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
13639 /// implemented asks for structural equivalence checking, the returned decl
13640 /// here is passed back to the parser, allowing the tag body to be parsed.
13641 auto createTagFromNewDecl = [&]() -> TagDecl * {
13642 assert(!getLangOpts().CPlusPlus && "not meant for C++ usage")(static_cast <bool> (!getLangOpts().CPlusPlus &&
"not meant for C++ usage") ? void (0) : __assert_fail ("!getLangOpts().CPlusPlus && \"not meant for C++ usage\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 13642, __extension__ __PRETTY_FUNCTION__))
;
13643 // If there is an identifier, use the location of the identifier as the
13644 // location of the decl, otherwise use the location of the struct/union
13645 // keyword.
13646 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13647 TagDecl *New = nullptr;
13648
13649 if (Kind == TTK_Enum) {
13650 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
13651 ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
13652 // If this is an undefined enum, bail.
13653 if (TUK != TUK_Definition && !Invalid)
13654 return nullptr;
13655 if (EnumUnderlying) {
13656 EnumDecl *ED = cast<EnumDecl>(New);
13657 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
13658 ED->setIntegerTypeSourceInfo(TI);
13659 else
13660 ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
13661 ED->setPromotionType(ED->getIntegerType());
13662 }
13663 } else { // struct/union
13664 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13665 nullptr);
13666 }
13667
13668 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13669 // Add alignment attributes if necessary; these attributes are checked
13670 // when the ASTContext lays out the structure.
13671 //
13672 // It is important for implementing the correct semantics that this
13673 // happen here (in ActOnTag). The #pragma pack stack is
13674 // maintained as a result of parser callbacks which can occur at
13675 // many points during the parsing of a struct declaration (because
13676 // the #pragma tokens are effectively skipped over during the
13677 // parsing of the struct).
13678 if (TUK == TUK_Definition) {
13679 AddAlignmentAttributesForRecord(RD);
13680 AddMsStructLayoutForRecord(RD);
13681 }
13682 }
13683 New->setLexicalDeclContext(CurContext);
13684 return New;
13685 };
13686
13687 LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
13688 if (Name && SS.isNotEmpty()) {
13689 // We have a nested-name tag ('struct foo::bar').
13690
13691 // Check for invalid 'foo::'.
13692 if (SS.isInvalid()) {
13693 Name = nullptr;
13694 goto CreateNewDecl;
13695 }
13696
13697 // If this is a friend or a reference to a class in a dependent
13698 // context, don't try to make a decl for it.
13699 if (TUK == TUK_Friend || TUK == TUK_Reference) {
13700 DC = computeDeclContext(SS, false);
13701 if (!DC) {
13702 IsDependent = true;
13703 return nullptr;
13704 }
13705 } else {
13706 DC = computeDeclContext(SS, true);
13707 if (!DC) {
13708 Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
13709 << SS.getRange();
13710 return nullptr;
13711 }
13712 }
13713
13714 if (RequireCompleteDeclContext(SS, DC))
13715 return nullptr;
13716
13717 SearchDC = DC;
13718 // Look-up name inside 'foo::'.
13719 LookupQualifiedName(Previous, DC);
13720
13721 if (Previous.isAmbiguous())
13722 return nullptr;
13723
13724 if (Previous.empty()) {
13725 // Name lookup did not find anything. However, if the
13726 // nested-name-specifier refers to the current instantiation,
13727 // and that current instantiation has any dependent base
13728 // classes, we might find something at instantiation time: treat
13729 // this as a dependent elaborated-type-specifier.
13730 // But this only makes any sense for reference-like lookups.
13731 if (Previous.wasNotFoundInCurrentInstantiation() &&
13732 (TUK == TUK_Reference || TUK == TUK_Friend)) {
13733 IsDependent = true;
13734 return nullptr;
13735 }
13736
13737 // A tag 'foo::bar' must already exist.
13738 Diag(NameLoc, diag::err_not_tag_in_scope)
13739 << Kind << Name << DC << SS.getRange();
13740 Name = nullptr;
13741 Invalid = true;
13742 goto CreateNewDecl;
13743 }
13744 } else if (Name) {
13745 // C++14 [class.mem]p14:
13746 // If T is the name of a class, then each of the following shall have a
13747 // name different from T:
13748 // -- every member of class T that is itself a type
13749 if (TUK != TUK_Reference && TUK != TUK_Friend &&
13750 DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
13751 return nullptr;
13752
13753 // If this is a named struct, check to see if there was a previous forward
13754 // declaration or definition.
13755 // FIXME: We're looking into outer scopes here, even when we
13756 // shouldn't be. Doing so can result in ambiguities that we
13757 // shouldn't be diagnosing.
13758 LookupName(Previous, S);
13759
13760 // When declaring or defining a tag, ignore ambiguities introduced
13761 // by types using'ed into this scope.
13762 if (Previous.isAmbiguous() &&
13763 (TUK == TUK_Definition || TUK == TUK_Declaration)) {
13764 LookupResult::Filter F = Previous.makeFilter();
13765 while (F.hasNext()) {
13766 NamedDecl *ND = F.next();
13767 if (!ND->getDeclContext()->getRedeclContext()->Equals(
13768 SearchDC->getRedeclContext()))
13769 F.erase();
13770 }
13771 F.done();
13772 }
13773
13774 // C++11 [namespace.memdef]p3:
13775 // If the name in a friend declaration is neither qualified nor
13776 // a template-id and the declaration is a function or an
13777 // elaborated-type-specifier, the lookup to determine whether
13778 // the entity has been previously declared shall not consider
13779 // any scopes outside the innermost enclosing namespace.
13780 //
13781 // MSVC doesn't implement the above rule for types, so a friend tag
13782 // declaration may be a redeclaration of a type declared in an enclosing
13783 // scope. They do implement this rule for friend functions.
13784 //
13785 // Does it matter that this should be by scope instead of by
13786 // semantic context?
13787 if (!Previous.empty() && TUK == TUK_Friend) {
13788 DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
13789 LookupResult::Filter F = Previous.makeFilter();
13790 bool FriendSawTagOutsideEnclosingNamespace = false;
13791 while (F.hasNext()) {
13792 NamedDecl *ND = F.next();
13793 DeclContext *DC = ND->getDeclContext()->getRedeclContext();
13794 if (DC->isFileContext() &&
13795 !EnclosingNS->Encloses(ND->getDeclContext())) {
13796 if (getLangOpts().MSVCCompat)
13797 FriendSawTagOutsideEnclosingNamespace = true;
13798 else
13799 F.erase();
13800 }
13801 }
13802 F.done();
13803
13804 // Diagnose this MSVC extension in the easy case where lookup would have
13805 // unambiguously found something outside the enclosing namespace.
13806 if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
13807 NamedDecl *ND = Previous.getFoundDecl();
13808 Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
13809 << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
13810 }
13811 }
13812
13813 // Note: there used to be some attempt at recovery here.
13814 if (Previous.isAmbiguous())
13815 return nullptr;
13816
13817 if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
13818 // FIXME: This makes sure that we ignore the contexts associated
13819 // with C structs, unions, and enums when looking for a matching
13820 // tag declaration or definition. See the similar lookup tweak
13821 // in Sema::LookupName; is there a better way to deal with this?
13822 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
13823 SearchDC = SearchDC->getParent();
13824 }
13825 }
13826
13827 if (Previous.isSingleResult() &&
13828 Previous.getFoundDecl()->isTemplateParameter()) {
13829 // Maybe we will complain about the shadowed template parameter.
13830 DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
13831 // Just pretend that we didn't see the previous declaration.
13832 Previous.clear();
13833 }
13834
13835 if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
13836 DC->Equals(getStdNamespace())) {
13837 if (Name->isStr("bad_alloc")) {
13838 // This is a declaration of or a reference to "std::bad_alloc".
13839 isStdBadAlloc = true;
13840
13841 // If std::bad_alloc has been implicitly declared (but made invisible to
13842 // name lookup), fill in this implicit declaration as the previous
13843 // declaration, so that the declarations get chained appropriately.
13844 if (Previous.empty() && StdBadAlloc)
13845 Previous.addDecl(getStdBadAlloc());
13846 } else if (Name->isStr("align_val_t")) {
13847 isStdAlignValT = true;
13848 if (Previous.empty() && StdAlignValT)
13849 Previous.addDecl(getStdAlignValT());
13850 }
13851 }
13852
13853 // If we didn't find a previous declaration, and this is a reference
13854 // (or friend reference), move to the correct scope. In C++, we
13855 // also need to do a redeclaration lookup there, just in case
13856 // there's a shadow friend decl.
13857 if (Name && Previous.empty() &&
13858 (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
13859 if (Invalid) goto CreateNewDecl;
13860 assert(SS.isEmpty())(static_cast <bool> (SS.isEmpty()) ? void (0) : __assert_fail
("SS.isEmpty()", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 13860, __extension__ __PRETTY_FUNCTION__))
;
13861
13862 if (TUK == TUK_Reference || IsTemplateParamOrArg) {
13863 // C++ [basic.scope.pdecl]p5:
13864 // -- for an elaborated-type-specifier of the form
13865 //
13866 // class-key identifier
13867 //
13868 // if the elaborated-type-specifier is used in the
13869 // decl-specifier-seq or parameter-declaration-clause of a
13870 // function defined in namespace scope, the identifier is
13871 // declared as a class-name in the namespace that contains
13872 // the declaration; otherwise, except as a friend
13873 // declaration, the identifier is declared in the smallest
13874 // non-class, non-function-prototype scope that contains the
13875 // declaration.
13876 //
13877 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
13878 // C structs and unions.
13879 //
13880 // It is an error in C++ to declare (rather than define) an enum
13881 // type, including via an elaborated type specifier. We'll
13882 // diagnose that later; for now, declare the enum in the same
13883 // scope as we would have picked for any other tag type.
13884 //
13885 // GNU C also supports this behavior as part of its incomplete
13886 // enum types extension, while GNU C++ does not.
13887 //
13888 // Find the context where we'll be declaring the tag.
13889 // FIXME: We would like to maintain the current DeclContext as the
13890 // lexical context,
13891 SearchDC = getTagInjectionContext(SearchDC);
13892
13893 // Find the scope where we'll be declaring the tag.
13894 S = getTagInjectionScope(S, getLangOpts());
13895 } else {
13896 assert(TUK == TUK_Friend)(static_cast <bool> (TUK == TUK_Friend) ? void (0) : __assert_fail
("TUK == TUK_Friend", "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 13896, __extension__ __PRETTY_FUNCTION__))
;
13897 // C++ [namespace.memdef]p3:
13898 // If a friend declaration in a non-local class first declares a
13899 // class or function, the friend class or function is a member of
13900 // the innermost enclosing namespace.
13901 SearchDC = SearchDC->getEnclosingNamespaceContext();
13902 }
13903
13904 // In C++, we need to do a redeclaration lookup to properly
13905 // diagnose some problems.
13906 // FIXME: redeclaration lookup is also used (with and without C++) to find a
13907 // hidden declaration so that we don't get ambiguity errors when using a
13908 // type declared by an elaborated-type-specifier. In C that is not correct
13909 // and we should instead merge compatible types found by lookup.
13910 if (getLangOpts().CPlusPlus) {
13911 Previous.setRedeclarationKind(forRedeclarationInCurContext());
13912 LookupQualifiedName(Previous, SearchDC);
13913 } else {
13914 Previous.setRedeclarationKind(forRedeclarationInCurContext());
13915 LookupName(Previous, S);
13916 }
13917 }
13918
13919 // If we have a known previous declaration to use, then use it.
13920 if (Previous.empty() && SkipBody && SkipBody->Previous)
13921 Previous.addDecl(SkipBody->Previous);
13922
13923 if (!Previous.empty()) {
13924 NamedDecl *PrevDecl = Previous.getFoundDecl();
13925 NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13926
13927 // It's okay to have a tag decl in the same scope as a typedef
13928 // which hides a tag decl in the same scope. Finding this
13929 // insanity with a redeclaration lookup can only actually happen
13930 // in C++.
13931 //
13932 // This is also okay for elaborated-type-specifiers, which is
13933 // technically forbidden by the current standard but which is
13934 // okay according to the likely resolution of an open issue;
13935 // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13936 if (getLangOpts().CPlusPlus) {
13937 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13938 if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13939 TagDecl *Tag = TT->getDecl();
13940 if (Tag->getDeclName() == Name &&
13941 Tag->getDeclContext()->getRedeclContext()
13942 ->Equals(TD->getDeclContext()->getRedeclContext())) {
13943 PrevDecl = Tag;
13944 Previous.clear();
13945 Previous.addDecl(Tag);
13946 Previous.resolveKind();
13947 }
13948 }
13949 }
13950 }
13951
13952 // If this is a redeclaration of a using shadow declaration, it must
13953 // declare a tag in the same context. In MSVC mode, we allow a
13954 // redefinition if either context is within the other.
13955 if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13956 auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13957 if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13958 isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
13959 !(OldTag && isAcceptableTagRedeclContext(
13960 *this, OldTag->getDeclContext(), SearchDC))) {
13961 Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13962 Diag(Shadow->getTargetDecl()->getLocation(),
13963 diag::note_using_decl_target);
13964 Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13965 << 0;
13966 // Recover by ignoring the old declaration.
13967 Previous.clear();
13968 goto CreateNewDecl;
13969 }
13970 }
13971
13972 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13973 // If this is a use of a previous tag, or if the tag is already declared
13974 // in the same scope (so that the definition/declaration completes or
13975 // rementions the tag), reuse the decl.
13976 if (TUK == TUK_Reference || TUK == TUK_Friend ||
13977 isDeclInScope(DirectPrevDecl, SearchDC, S,
13978 SS.isNotEmpty() || isMemberSpecialization)) {
13979 // Make sure that this wasn't declared as an enum and now used as a
13980 // struct or something similar.
13981 if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13982 TUK == TUK_Definition, KWLoc,
13983 Name)) {
13984 bool SafeToContinue
13985 = (PrevTagDecl->getTagKind() != TTK_Enum &&
13986 Kind != TTK_Enum);
13987 if (SafeToContinue)
13988 Diag(KWLoc, diag::err_use_with_wrong_tag)
13989 << Name
13990 << FixItHint::CreateReplacement(SourceRange(KWLoc),
13991 PrevTagDecl->getKindName());
13992 else
13993 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13994 Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13995
13996 if (SafeToContinue)
13997 Kind = PrevTagDecl->getTagKind();
13998 else {
13999 // Recover by making this an anonymous redefinition.
14000 Name = nullptr;
14001 Previous.clear();
14002 Invalid = true;
14003 }
14004 }
14005
14006 if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
14007 const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
14008
14009 // If this is an elaborated-type-specifier for a scoped enumeration,
14010 // the 'class' keyword is not necessary and not permitted.
14011 if (TUK == TUK_Reference || TUK == TUK_Friend) {
14012 if (ScopedEnum)
14013 Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
14014 << PrevEnum->isScoped()
14015 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
14016 return PrevTagDecl;
14017 }
14018
14019 QualType EnumUnderlyingTy;
14020 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14021 EnumUnderlyingTy = TI->getType().getUnqualifiedType();
14022 else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
14023 EnumUnderlyingTy = QualType(T, 0);
14024
14025 // All conflicts with previous declarations are recovered by
14026 // returning the previous declaration, unless this is a definition,
14027 // in which case we want the caller to bail out.
14028 if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
14029 ScopedEnum, EnumUnderlyingTy,
14030 IsFixed, PrevEnum))
14031 return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
14032 }
14033
14034 // C++11 [class.mem]p1:
14035 // A member shall not be declared twice in the member-specification,
14036 // except that a nested class or member class template can be declared
14037 // and then later defined.
14038 if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
14039 S->isDeclScope(PrevDecl)) {
14040 Diag(NameLoc, diag::ext_member_redeclared);
14041 Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
14042 }
14043
14044 if (!Invalid) {
14045 // If this is a use, just return the declaration we found, unless
14046 // we have attributes.
14047 if (TUK == TUK_Reference || TUK == TUK_Friend) {
14048 if (Attr) {
14049 // FIXME: Diagnose these attributes. For now, we create a new
14050 // declaration to hold them.
14051 } else if (TUK == TUK_Reference &&
14052 (PrevTagDecl->getFriendObjectKind() ==
14053 Decl::FOK_Undeclared ||
14054 PrevDecl->getOwningModule() != getCurrentModule()) &&
14055 SS.isEmpty()) {
14056 // This declaration is a reference to an existing entity, but
14057 // has different visibility from that entity: it either makes
14058 // a friend visible or it makes a type visible in a new module.
14059 // In either case, create a new declaration. We only do this if
14060 // the declaration would have meant the same thing if no prior
14061 // declaration were found, that is, if it was found in the same
14062 // scope where we would have injected a declaration.
14063 if (!getTagInjectionContext(CurContext)->getRedeclContext()
14064 ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
14065 return PrevTagDecl;
14066 // This is in the injected scope, create a new declaration in
14067 // that scope.
14068 S = getTagInjectionScope(S, getLangOpts());
14069 } else {
14070 return PrevTagDecl;
14071 }
14072 }
14073
14074 // Diagnose attempts to redefine a tag.
14075 if (TUK == TUK_Definition) {
14076 if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
14077 // If we're defining a specialization and the previous definition
14078 // is from an implicit instantiation, don't emit an error
14079 // here; we'll catch this in the general case below.
14080 bool IsExplicitSpecializationAfterInstantiation = false;
14081 if (isMemberSpecialization) {
14082 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
14083 IsExplicitSpecializationAfterInstantiation =
14084 RD->getTemplateSpecializationKind() !=
14085 TSK_ExplicitSpecialization;
14086 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
14087 IsExplicitSpecializationAfterInstantiation =
14088 ED->getTemplateSpecializationKind() !=
14089 TSK_ExplicitSpecialization;
14090 }
14091
14092 // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
14093 // not keep more that one definition around (merge them). However,
14094 // ensure the decl passes the structural compatibility check in
14095 // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
14096 NamedDecl *Hidden = nullptr;
14097 if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
14098 // There is a definition of this tag, but it is not visible. We
14099 // explicitly make use of C++'s one definition rule here, and
14100 // assume that this definition is identical to the hidden one
14101 // we already have. Make the existing definition visible and
14102 // use it in place of this one.
14103 if (!getLangOpts().CPlusPlus) {
14104 // Postpone making the old definition visible until after we
14105 // complete parsing the new one and do the structural
14106 // comparison.
14107 SkipBody->CheckSameAsPrevious = true;
14108 SkipBody->New = createTagFromNewDecl();
14109 SkipBody->Previous = Hidden;
14110 } else {
14111 SkipBody->ShouldSkip = true;
14112 makeMergedDefinitionVisible(Hidden);
14113 }
14114 return Def;
14115 } else if (!IsExplicitSpecializationAfterInstantiation) {
14116 // A redeclaration in function prototype scope in C isn't
14117 // visible elsewhere, so merely issue a warning.
14118 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
14119 Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
14120 else
14121 Diag(NameLoc, diag::err_redefinition) << Name;
14122 notePreviousDefinition(Def,
14123 NameLoc.isValid() ? NameLoc : KWLoc);
14124 // If this is a redefinition, recover by making this
14125 // struct be anonymous, which will make any later
14126 // references get the previous definition.
14127 Name = nullptr;
14128 Previous.clear();
14129 Invalid = true;
14130 }
14131 } else {
14132 // If the type is currently being defined, complain
14133 // about a nested redefinition.
14134 auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
14135 if (TD->isBeingDefined()) {
14136 Diag(NameLoc, diag::err_nested_redefinition) << Name;
14137 Diag(PrevTagDecl->getLocation(),
14138 diag::note_previous_definition);
14139 Name = nullptr;
14140 Previous.clear();
14141 Invalid = true;
14142 }
14143 }
14144
14145 // Okay, this is definition of a previously declared or referenced
14146 // tag. We're going to create a new Decl for it.
14147 }
14148
14149 // Okay, we're going to make a redeclaration. If this is some kind
14150 // of reference, make sure we build the redeclaration in the same DC
14151 // as the original, and ignore the current access specifier.
14152 if (TUK == TUK_Friend || TUK == TUK_Reference) {
14153 SearchDC = PrevTagDecl->getDeclContext();
14154 AS = AS_none;
14155 }
14156 }
14157 // If we get here we have (another) forward declaration or we
14158 // have a definition. Just create a new decl.
14159
14160 } else {
14161 // If we get here, this is a definition of a new tag type in a nested
14162 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
14163 // new decl/type. We set PrevDecl to NULL so that the entities
14164 // have distinct types.
14165 Previous.clear();
14166 }
14167 // If we get here, we're going to create a new Decl. If PrevDecl
14168 // is non-NULL, it's a definition of the tag declared by
14169 // PrevDecl. If it's NULL, we have a new definition.
14170
14171 // Otherwise, PrevDecl is not a tag, but was found with tag
14172 // lookup. This is only actually possible in C++, where a few
14173 // things like templates still live in the tag namespace.
14174 } else {
14175 // Use a better diagnostic if an elaborated-type-specifier
14176 // found the wrong kind of type on the first
14177 // (non-redeclaration) lookup.
14178 if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
14179 !Previous.isForRedeclaration()) {
14180 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14181 Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
14182 << Kind;
14183 Diag(PrevDecl->getLocation(), diag::note_declared_at);
14184 Invalid = true;
14185
14186 // Otherwise, only diagnose if the declaration is in scope.
14187 } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
14188 SS.isNotEmpty() || isMemberSpecialization)) {
14189 // do nothing
14190
14191 // Diagnose implicit declarations introduced by elaborated types.
14192 } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
14193 NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
14194 Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
14195 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14196 Invalid = true;
14197
14198 // Otherwise it's a declaration. Call out a particularly common
14199 // case here.
14200 } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14201 unsigned Kind = 0;
14202 if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
14203 Diag(NameLoc, diag::err_tag_definition_of_typedef)
14204 << Name << Kind << TND->getUnderlyingType();
14205 Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14206 Invalid = true;
14207
14208 // Otherwise, diagnose.
14209 } else {
14210 // The tag name clashes with something else in the target scope,
14211 // issue an error and recover by making this tag be anonymous.
14212 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
14213 notePreviousDefinition(PrevDecl, NameLoc);
14214 Name = nullptr;
14215 Invalid = true;
14216 }
14217
14218 // The existing declaration isn't relevant to us; we're in a
14219 // new scope, so clear out the previous declaration.
14220 Previous.clear();
14221 }
14222 }
14223
14224CreateNewDecl:
14225
14226 TagDecl *PrevDecl = nullptr;
14227 if (Previous.isSingleResult())
14228 PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
14229
14230 // If there is an identifier, use the location of the identifier as the
14231 // location of the decl, otherwise use the location of the struct/union
14232 // keyword.
14233 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14234
14235 // Otherwise, create a new declaration. If there is a previous
14236 // declaration of the same entity, the two will be linked via
14237 // PrevDecl.
14238 TagDecl *New;
14239
14240 bool IsForwardReference = false;
14241 if (Kind == TTK_Enum) {
14242 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14243 // enum X { A, B, C } D; D should chain to X.
14244 New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
14245 cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
14246 ScopedEnumUsesClassTag, IsFixed);
14247
14248 if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
14249 StdAlignValT = cast<EnumDecl>(New);
14250
14251 // If this is an undefined enum, warn.
14252 if (TUK != TUK_Definition && !Invalid) {
14253 TagDecl *Def;
14254 if (IsFixed && (getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
14255 cast<EnumDecl>(New)->isFixed()) {
14256 // C++0x: 7.2p2: opaque-enum-declaration.
14257 // Conflicts are diagnosed above. Do nothing.
14258 }
14259 else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
14260 Diag(Loc, diag::ext_forward_ref_enum_def)
14261 << New;
14262 Diag(Def->getLocation(), diag::note_previous_definition);
14263 } else {
14264 unsigned DiagID = diag::ext_forward_ref_enum;
14265 if (getLangOpts().MSVCCompat)
14266 DiagID = diag::ext_ms_forward_ref_enum;
14267 else if (getLangOpts().CPlusPlus)
14268 DiagID = diag::err_forward_ref_enum;
14269 Diag(Loc, DiagID);
14270
14271 // If this is a forward-declared reference to an enumeration, make a
14272 // note of it; we won't actually be introducing the declaration into
14273 // the declaration context.
14274 if (TUK == TUK_Reference)
14275 IsForwardReference = true;
14276 }
14277 }
14278
14279 if (EnumUnderlying) {
14280 EnumDecl *ED = cast<EnumDecl>(New);
14281 if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14282 ED->setIntegerTypeSourceInfo(TI);
14283 else
14284 ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
14285 ED->setPromotionType(ED->getIntegerType());
14286 assert(ED->isComplete() && "enum with type should be complete")(static_cast <bool> (ED->isComplete() && "enum with type should be complete"
) ? void (0) : __assert_fail ("ED->isComplete() && \"enum with type should be complete\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 14286, __extension__ __PRETTY_FUNCTION__))
;
14287 }
14288 } else {
14289 // struct/union/class
14290
14291 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14292 // struct X { int A; } D; D should chain to X.
14293 if (getLangOpts().CPlusPlus) {
14294 // FIXME: Look for a way to use RecordDecl for simple structs.
14295 New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14296 cast_or_null<CXXRecordDecl>(PrevDecl));
14297
14298 if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
14299 StdBadAlloc = cast<CXXRecordDecl>(New);
14300 } else
14301 New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
14302 cast_or_null<RecordDecl>(PrevDecl));
14303 }
14304
14305 // C++11 [dcl.type]p3:
14306 // A type-specifier-seq shall not define a class or enumeration [...].
14307 if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
14308 TUK == TUK_Definition) {
14309 Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
14310 << Context.getTagDeclType(New);
14311 Invalid = true;
14312 }
14313
14314 if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
14315 DC->getDeclKind() == Decl::Enum) {
14316 Diag(New->getLocation(), diag::err_type_defined_in_enum)
14317 << Context.getTagDeclType(New);
14318 Invalid = true;
14319 }
14320
14321 // Maybe add qualifier info.
14322 if (SS.isNotEmpty()) {
14323 if (SS.isSet()) {
14324 // If this is either a declaration or a definition, check the
14325 // nested-name-specifier against the current context.
14326 if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
14327 diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
14328 isMemberSpecialization))
14329 Invalid = true;
14330
14331 New->setQualifierInfo(SS.getWithLocInContext(Context));
14332 if (TemplateParameterLists.size() > 0) {
14333 New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
14334 }
14335 }
14336 else
14337 Invalid = true;
14338 }
14339
14340 if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14341 // Add alignment attributes if necessary; these attributes are checked when
14342 // the ASTContext lays out the structure.
14343 //
14344 // It is important for implementing the correct semantics that this
14345 // happen here (in ActOnTag). The #pragma pack stack is
14346 // maintained as a result of parser callbacks which can occur at
14347 // many points during the parsing of a struct declaration (because
14348 // the #pragma tokens are effectively skipped over during the
14349 // parsing of the struct).
14350 if (TUK == TUK_Definition) {
14351 AddAlignmentAttributesForRecord(RD);
14352 AddMsStructLayoutForRecord(RD);
14353 }
14354 }
14355
14356 if (ModulePrivateLoc.isValid()) {
14357 if (isMemberSpecialization)
14358 Diag(New->getLocation(), diag::err_module_private_specialization)
14359 << 2
14360 << FixItHint::CreateRemoval(ModulePrivateLoc);
14361 // __module_private__ does not apply to local classes. However, we only
14362 // diagnose this as an error when the declaration specifiers are
14363 // freestanding. Here, we just ignore the __module_private__.
14364 else if (!SearchDC->isFunctionOrMethod())
14365 New->setModulePrivate();
14366 }
14367
14368 // If this is a specialization of a member class (of a class template),
14369 // check the specialization.
14370 if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
14371 Invalid = true;
14372
14373 // If we're declaring or defining a tag in function prototype scope in C,
14374 // note that this type can only be used within the function and add it to
14375 // the list of decls to inject into the function definition scope.
14376 if ((Name || Kind == TTK_Enum) &&
14377 getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
14378 if (getLangOpts().CPlusPlus) {
14379 // C++ [dcl.fct]p6:
14380 // Types shall not be defined in return or parameter types.
14381 if (TUK == TUK_Definition && !IsTypeSpecifier) {
14382 Diag(Loc, diag::err_type_defined_in_param_type)
14383 << Name;
14384 Invalid = true;
14385 }
14386 } else if (!PrevDecl) {
14387 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
14388 }
14389 }
14390
14391 if (Invalid)
14392 New->setInvalidDecl();
14393
14394 // Set the lexical context. If the tag has a C++ scope specifier, the
14395 // lexical context will be different from the semantic context.
14396 New->setLexicalDeclContext(CurContext);
14397
14398 // Mark this as a friend decl if applicable.
14399 // In Microsoft mode, a friend declaration also acts as a forward
14400 // declaration so we always pass true to setObjectOfFriendDecl to make
14401 // the tag name visible.
14402 if (TUK == TUK_Friend)
14403 New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
14404
14405 // Set the access specifier.
14406 if (!Invalid && SearchDC->isRecord())
14407 SetMemberAccessSpecifier(New, PrevDecl, AS);
14408
14409 if (PrevDecl)
14410 CheckRedeclarationModuleOwnership(New, PrevDecl);
14411
14412 if (TUK == TUK_Definition)
14413 New->startDefinition();
14414
14415 if (Attr)
14416 ProcessDeclAttributeList(S, New, Attr);
14417 AddPragmaAttributes(S, New);
14418
14419 // If this has an identifier, add it to the scope stack.
14420 if (TUK == TUK_Friend) {
14421 // We might be replacing an existing declaration in the lookup tables;
14422 // if so, borrow its access specifier.
14423 if (PrevDecl)
14424 New->setAccess(PrevDecl->getAccess());
14425
14426 DeclContext *DC = New->getDeclContext()->getRedeclContext();
14427 DC->makeDeclVisibleInContext(New);
14428 if (Name) // can be null along some error paths
14429 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
14430 PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
14431 } else if (Name) {
14432 S = getNonFieldDeclScope(S);
14433 PushOnScopeChains(New, S, !IsForwardReference);
14434 if (IsForwardReference)
14435 SearchDC->makeDeclVisibleInContext(New);
14436 } else {
14437 CurContext->addDecl(New);
14438 }
14439
14440 // If this is the C FILE type, notify the AST context.
14441 if (IdentifierInfo *II = New->getIdentifier())
14442 if (!New->isInvalidDecl() &&
14443 New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
14444 II->isStr("FILE"))
14445 Context.setFILEDecl(New);
14446
14447 if (PrevDecl)
14448 mergeDeclAttributes(New, PrevDecl);
14449
14450 // If there's a #pragma GCC visibility in scope, set the visibility of this
14451 // record.
14452 AddPushedVisibilityAttribute(New);
14453
14454 if (isMemberSpecialization && !New->isInvalidDecl())
14455 CompleteMemberSpecialization(New, Previous);
14456
14457 OwnedDecl = true;
14458 // In C++, don't return an invalid declaration. We can't recover well from
14459 // the cases where we make the type anonymous.
14460 if (Invalid && getLangOpts().CPlusPlus) {
14461 if (New->isBeingDefined())
14462 if (auto RD = dyn_cast<RecordDecl>(New))
14463 RD->completeDefinition();
14464 return nullptr;
14465 } else {
14466 return New;
14467 }
14468}
14469
14470void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
14471 AdjustDeclIfTemplate(TagD);
14472 TagDecl *Tag = cast<TagDecl>(TagD);
14473
14474 // Enter the tag context.
14475 PushDeclContext(S, Tag);
14476
14477 ActOnDocumentableDecl(TagD);
14478
14479 // If there's a #pragma GCC visibility in scope, set the visibility of this
14480 // record.
14481 AddPushedVisibilityAttribute(Tag);
14482}
14483
14484bool Sema::ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev,
14485 SkipBodyInfo &SkipBody) {
14486 if (!hasStructuralCompatLayout(Prev, SkipBody.New))
14487 return false;
14488
14489 // Make the previous decl visible.
14490 makeMergedDefinitionVisible(SkipBody.Previous);
14491 return true;
14492}
14493
14494Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
14495 assert(isa<ObjCContainerDecl>(IDecl) &&(static_cast <bool> (isa<ObjCContainerDecl>(IDecl
) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"
) ? void (0) : __assert_fail ("isa<ObjCContainerDecl>(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 14496, __extension__ __PRETTY_FUNCTION__))
14496 "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl")(static_cast <bool> (isa<ObjCContainerDecl>(IDecl
) && "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl"
) ? void (0) : __assert_fail ("isa<ObjCContainerDecl>(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 14496, __extension__ __PRETTY_FUNCTION__))
;
14497 DeclContext *OCD = cast<DeclContext>(IDecl);
14498 assert(getContainingDC(OCD) == CurContext &&(static_cast <bool> (getContainingDC(OCD) == CurContext
&& "The next DeclContext should be lexically contained in the current one."
) ? void (0) : __assert_fail ("getContainingDC(OCD) == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 14499, __extension__ __PRETTY_FUNCTION__))
14499 "The next DeclContext should be lexically contained in the current one.")(static_cast <bool> (getContainingDC(OCD) == CurContext
&& "The next DeclContext should be lexically contained in the current one."
) ? void (0) : __assert_fail ("getContainingDC(OCD) == CurContext && \"The next DeclContext should be lexically contained in the current one.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 14499, __extension__ __PRETTY_FUNCTION__))
;
14500 CurContext = OCD;
14501 return IDecl;
14502}
14503
14504void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
14505 SourceLocation FinalLoc,
14506 bool IsFinalSpelledSealed,
14507 SourceLocation LBraceLoc) {
14508 AdjustDeclIfTemplate(TagD);
14509 CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
14510
14511 FieldCollector->StartClass();
14512
14513 if (!Record->getIdentifier())
14514 return;
14515
14516 if (FinalLoc.isValid())
14517 Record->addAttr(new (Context)
14518 FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
14519
14520 // C++ [class]p2:
14521 // [...] The class-name is also inserted into the scope of the
14522 // class itself; this is known as the injected-class-name. For
14523 // purposes of access checking, the injected-class-name is treated
14524 // as if it were a public member name.
14525 CXXRecordDecl *InjectedClassName
14526 = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
14527 Record->getLocStart(), Record->getLocation(),
14528 Record->getIdentifier(),
14529 /*PrevDecl=*/nullptr,
14530 /*DelayTypeCreation=*/true);
14531 Context.getTypeDeclType(InjectedClassName, Record);
14532 InjectedClassName->setImplicit();
14533 InjectedClassName->setAccess(AS_public);
14534 if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
14535 InjectedClassName->setDescribedClassTemplate(Template);
14536 PushOnScopeChains(InjectedClassName, S);
14537 assert(InjectedClassName->isInjectedClassName() &&(static_cast <bool> (InjectedClassName->isInjectedClassName
() && "Broken injected-class-name") ? void (0) : __assert_fail
("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 14538, __extension__ __PRETTY_FUNCTION__))
14538 "Broken injected-class-name")(static_cast <bool> (InjectedClassName->isInjectedClassName
() && "Broken injected-class-name") ? void (0) : __assert_fail
("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 14538, __extension__ __PRETTY_FUNCTION__))
;
14539}
14540
14541void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
14542 SourceRange BraceRange) {
14543 AdjustDeclIfTemplate(TagD);
14544 TagDecl *Tag = cast<TagDecl>(TagD);
14545 Tag->setBraceRange(BraceRange);
14546
14547 // Make sure we "complete" the definition even it is invalid.
14548 if (Tag->isBeingDefined()) {
14549 assert(Tag->isInvalidDecl() && "We should already have completed it")(static_cast <bool> (Tag->isInvalidDecl() &&
"We should already have completed it") ? void (0) : __assert_fail
("Tag->isInvalidDecl() && \"We should already have completed it\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 14549, __extension__ __PRETTY_FUNCTION__))
;
14550 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14551 RD->completeDefinition();
14552 }
14553
14554 if (isa<CXXRecordDecl>(Tag)) {
14555 FieldCollector->FinishClass();
14556 }
14557
14558 // Exit this scope of this tag's definition.
14559 PopDeclContext();
14560
14561 if (getCurLexicalContext()->isObjCContainer() &&
14562 Tag->getDeclContext()->isFileContext())
14563 Tag->setTopLevelDeclInObjCContainer();
14564
14565 // Notify the consumer that we've defined a tag.
14566 if (!Tag->isInvalidDecl())
14567 Consumer.HandleTagDeclDefinition(Tag);
14568}
14569
14570void Sema::ActOnObjCContainerFinishDefinition() {
14571 // Exit this scope of this interface definition.
14572 PopDeclContext();
14573}
14574
14575void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
14576 assert(DC == CurContext && "Mismatch of container contexts")(static_cast <bool> (DC == CurContext && "Mismatch of container contexts"
) ? void (0) : __assert_fail ("DC == CurContext && \"Mismatch of container contexts\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 14576, __extension__ __PRETTY_FUNCTION__))
;
14577 OriginalLexicalContext = DC;
14578 ActOnObjCContainerFinishDefinition();
14579}
14580
14581void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
14582 ActOnObjCContainerStartDefinition(cast<Decl>(DC));
14583 OriginalLexicalContext = nullptr;
14584}
14585
14586void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
14587 AdjustDeclIfTemplate(TagD);
14588 TagDecl *Tag = cast<TagDecl>(TagD);
14589 Tag->setInvalidDecl();
14590
14591 // Make sure we "complete" the definition even it is invalid.
14592 if (Tag->isBeingDefined()) {
14593 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
14594 RD->completeDefinition();
14595 }
14596
14597 // We're undoing ActOnTagStartDefinition here, not
14598 // ActOnStartCXXMemberDeclarations, so we don't have to mess with
14599 // the FieldCollector.
14600
14601 PopDeclContext();
14602}
14603
14604// Note that FieldName may be null for anonymous bitfields.
14605ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
14606 IdentifierInfo *FieldName,
14607 QualType FieldTy, bool IsMsStruct,
14608 Expr *BitWidth, bool *ZeroWidth) {
14609 // Default to true; that shouldn't confuse checks for emptiness
14610 if (ZeroWidth)
14611 *ZeroWidth = true;
14612
14613 // C99 6.7.2.1p4 - verify the field type.
14614 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
14615 if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
14616 // Handle incomplete types with specific error.
14617 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
14618 return ExprError();
14619 if (FieldName)
14620 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
14621 << FieldName << FieldTy << BitWidth->getSourceRange();
14622 return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
14623 << FieldTy << BitWidth->getSourceRange();
14624 } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
14625 UPPC_BitFieldWidth))
14626 return ExprError();
14627
14628 // If the bit-width is type- or value-dependent, don't try to check
14629 // it now.
14630 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
14631 return BitWidth;
14632
14633 llvm::APSInt Value;
14634 ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
14635 if (ICE.isInvalid())
14636 return ICE;
14637 BitWidth = ICE.get();
14638
14639 if (Value != 0 && ZeroWidth)
14640 *ZeroWidth = false;
14641
14642 // Zero-width bitfield is ok for anonymous field.
14643 if (Value == 0 && FieldName)
14644 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
14645
14646 if (Value.isSigned() && Value.isNegative()) {
14647 if (FieldName)
14648 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
14649 << FieldName << Value.toString(10);
14650 return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
14651 << Value.toString(10);
14652 }
14653
14654 if (!FieldTy->isDependentType()) {
14655 uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
14656 uint64_t TypeWidth = Context.getIntWidth(FieldTy);
14657 bool BitfieldIsOverwide = Value.ugt(TypeWidth);
14658
14659 // Over-wide bitfields are an error in C or when using the MSVC bitfield
14660 // ABI.
14661 bool CStdConstraintViolation =
14662 BitfieldIsOverwide && !getLangOpts().CPlusPlus;
14663 bool MSBitfieldViolation =
14664 Value.ugt(TypeStorageSize) &&
14665 (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
14666 if (CStdConstraintViolation || MSBitfieldViolation) {
14667 unsigned DiagWidth =
14668 CStdConstraintViolation ? TypeWidth : TypeStorageSize;
14669 if (FieldName)
14670 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
14671 << FieldName << (unsigned)Value.getZExtValue()
14672 << !CStdConstraintViolation << DiagWidth;
14673
14674 return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
14675 << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
14676 << DiagWidth;
14677 }
14678
14679 // Warn on types where the user might conceivably expect to get all
14680 // specified bits as value bits: that's all integral types other than
14681 // 'bool'.
14682 if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
14683 if (FieldName)
14684 Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
14685 << FieldName << (unsigned)Value.getZExtValue()
14686 << (unsigned)TypeWidth;
14687 else
14688 Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
14689 << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
14690 }
14691 }
14692
14693 return BitWidth;
14694}
14695
14696/// ActOnField - Each field of a C struct/union is passed into this in order
14697/// to create a FieldDecl object for it.
14698Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
14699 Declarator &D, Expr *BitfieldWidth) {
14700 FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
14701 DeclStart, D, static_cast<Expr*>(BitfieldWidth),
14702 /*InitStyle=*/ICIS_NoInit, AS_public);
14703 return Res;
14704}
14705
14706/// HandleField - Analyze a field of a C struct or a C++ data member.
14707///
14708FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
14709 SourceLocation DeclStart,
14710 Declarator &D, Expr *BitWidth,
14711 InClassInitStyle InitStyle,
14712 AccessSpecifier AS) {
14713 if (D.isDecompositionDeclarator()) {
14714 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
14715 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
14716 << Decomp.getSourceRange();
14717 return nullptr;
14718 }
14719
14720 IdentifierInfo *II = D.getIdentifier();
14721 SourceLocation Loc = DeclStart;
14722 if (II) Loc = D.getIdentifierLoc();
14723
14724 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14725 QualType T = TInfo->getType();
14726 if (getLangOpts().CPlusPlus) {
14727 CheckExtraCXXDefaultArguments(D);
14728
14729 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14730 UPPC_DataMemberType)) {
14731 D.setInvalidType();
14732 T = Context.IntTy;
14733 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14734 }
14735 }
14736
14737 // TR 18037 does not allow fields to be declared with address spaces.
14738 if (T.getQualifiers().hasAddressSpace() ||
14739 T->isDependentAddressSpaceType() ||
14740 T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
14741 Diag(Loc, diag::err_field_with_address_space);
14742 D.setInvalidType();
14743 }
14744
14745 // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
14746 // used as structure or union field: image, sampler, event or block types.
14747 if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
14748 T->isSamplerT() || T->isBlockPointerType())) {
14749 Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
14750 D.setInvalidType();
14751 }
14752
14753 DiagnoseFunctionSpecifiers(D.getDeclSpec());
14754
14755 if (D.getDeclSpec().isInlineSpecified())
14756 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14757 << getLangOpts().CPlusPlus17;
14758 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14759 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14760 diag::err_invalid_thread)
14761 << DeclSpec::getSpecifierName(TSCS);
14762
14763 // Check to see if this name was declared as a member previously
14764 NamedDecl *PrevDecl = nullptr;
14765 LookupResult Previous(*this, II, Loc, LookupMemberName,
14766 ForVisibleRedeclaration);
14767 LookupName(Previous, S);
14768 switch (Previous.getResultKind()) {
14769 case LookupResult::Found:
14770 case LookupResult::FoundUnresolvedValue:
14771 PrevDecl = Previous.getAsSingle<NamedDecl>();
14772 break;
14773
14774 case LookupResult::FoundOverloaded:
14775 PrevDecl = Previous.getRepresentativeDecl();
14776 break;
14777
14778 case LookupResult::NotFound:
14779 case LookupResult::NotFoundInCurrentInstantiation:
14780 case LookupResult::Ambiguous:
14781 break;
14782 }
14783 Previous.suppressDiagnostics();
14784
14785 if (PrevDecl && PrevDecl->isTemplateParameter()) {
14786 // Maybe we will complain about the shadowed template parameter.
14787 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14788 // Just pretend that we didn't see the previous declaration.
14789 PrevDecl = nullptr;
14790 }
14791
14792 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
14793 PrevDecl = nullptr;
14794
14795 bool Mutable
14796 = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
14797 SourceLocation TSSL = D.getLocStart();
14798 FieldDecl *NewFD
14799 = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
14800 TSSL, AS, PrevDecl, &D);
14801
14802 if (NewFD->isInvalidDecl())
14803 Record->setInvalidDecl();
14804
14805 if (D.getDeclSpec().isModulePrivateSpecified())
14806 NewFD->setModulePrivate();
14807
14808 if (NewFD->isInvalidDecl() && PrevDecl) {
14809 // Don't introduce NewFD into scope; there's already something
14810 // with the same name in the same scope.
14811 } else if (II) {
14812 PushOnScopeChains(NewFD, S);
14813 } else
14814 Record->addDecl(NewFD);
14815
14816 return NewFD;
14817}
14818
14819/// \brief Build a new FieldDecl and check its well-formedness.
14820///
14821/// This routine builds a new FieldDecl given the fields name, type,
14822/// record, etc. \p PrevDecl should refer to any previous declaration
14823/// with the same name and in the same scope as the field to be
14824/// created.
14825///
14826/// \returns a new FieldDecl.
14827///
14828/// \todo The Declarator argument is a hack. It will be removed once
14829FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
14830 TypeSourceInfo *TInfo,
14831 RecordDecl *Record, SourceLocation Loc,
14832 bool Mutable, Expr *BitWidth,
14833 InClassInitStyle InitStyle,
14834 SourceLocation TSSL,
14835 AccessSpecifier AS, NamedDecl *PrevDecl,
14836 Declarator *D) {
14837 IdentifierInfo *II = Name.getAsIdentifierInfo();
14838 bool InvalidDecl = false;
14839 if (D) InvalidDecl = D->isInvalidType();
14840
14841 // If we receive a broken type, recover by assuming 'int' and
14842 // marking this declaration as invalid.
14843 if (T.isNull()) {
14844 InvalidDecl = true;
14845 T = Context.IntTy;
14846 }
14847
14848 QualType EltTy = Context.getBaseElementType(T);
14849 if (!EltTy->isDependentType()) {
14850 if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
14851 // Fields of incomplete type force their record to be invalid.
14852 Record->setInvalidDecl();
14853 InvalidDecl = true;
14854 } else {
14855 NamedDecl *Def;
14856 EltTy->isIncompleteType(&Def);
14857 if (Def && Def->isInvalidDecl()) {
14858 Record->setInvalidDecl();
14859 InvalidDecl = true;
14860 }
14861 }
14862 }
14863
14864 // OpenCL v1.2 s6.9.c: bitfields are not supported.
14865 if (BitWidth && getLangOpts().OpenCL) {
14866 Diag(Loc, diag::err_opencl_bitfields);
14867 InvalidDecl = true;
14868 }
14869
14870 // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
14871 if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
14872 T.hasQualifiers()) {
14873 InvalidDecl = true;
14874 Diag(Loc, diag::err_anon_bitfield_qualifiers);
14875 }
14876
14877 // C99 6.7.2.1p8: A member of a structure or union may have any type other
14878 // than a variably modified type.
14879 if (!InvalidDecl && T->isVariablyModifiedType()) {
14880 bool SizeIsNegative;
14881 llvm::APSInt Oversized;
14882
14883 TypeSourceInfo *FixedTInfo =
14884 TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
14885 SizeIsNegative,
14886 Oversized);
14887 if (FixedTInfo) {
14888 Diag(Loc, diag::warn_illegal_constant_array_size);
14889 TInfo = FixedTInfo;
14890 T = FixedTInfo->getType();
14891 } else {
14892 if (SizeIsNegative)
14893 Diag(Loc, diag::err_typecheck_negative_array_size);
14894 else if (Oversized.getBoolValue())
14895 Diag(Loc, diag::err_array_too_large)
14896 << Oversized.toString(10);
14897 else
14898 Diag(Loc, diag::err_typecheck_field_variable_size);
14899 InvalidDecl = true;
14900 }
14901 }
14902
14903 // Fields can not have abstract class types
14904 if (!InvalidDecl && RequireNonAbstractType(Loc, T,
14905 diag::err_abstract_type_in_decl,
14906 AbstractFieldType))
14907 InvalidDecl = true;
14908
14909 bool ZeroWidth = false;
14910 if (InvalidDecl)
14911 BitWidth = nullptr;
14912 // If this is declared as a bit-field, check the bit-field.
14913 if (BitWidth) {
14914 BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
14915 &ZeroWidth).get();
14916 if (!BitWidth) {
14917 InvalidDecl = true;
14918 BitWidth = nullptr;
14919 ZeroWidth = false;
14920 }
14921 }
14922
14923 // Check that 'mutable' is consistent with the type of the declaration.
14924 if (!InvalidDecl && Mutable) {
14925 unsigned DiagID = 0;
14926 if (T->isReferenceType())
14927 DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
14928 : diag::err_mutable_reference;
14929 else if (T.isConstQualified())
14930 DiagID = diag::err_mutable_const;
14931
14932 if (DiagID) {
14933 SourceLocation ErrLoc = Loc;
14934 if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
14935 ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
14936 Diag(ErrLoc, DiagID);
14937 if (DiagID != diag::ext_mutable_reference) {
14938 Mutable = false;
14939 InvalidDecl = true;
14940 }
14941 }
14942 }
14943
14944 // C++11 [class.union]p8 (DR1460):
14945 // At most one variant member of a union may have a
14946 // brace-or-equal-initializer.
14947 if (InitStyle != ICIS_NoInit)
14948 checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14949
14950 FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14951 BitWidth, Mutable, InitStyle);
14952 if (InvalidDecl)
14953 NewFD->setInvalidDecl();
14954
14955 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14956 Diag(Loc, diag::err_duplicate_member) << II;
14957 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14958 NewFD->setInvalidDecl();
14959 }
14960
14961 if (!InvalidDecl && getLangOpts().CPlusPlus) {
14962 if (Record->isUnion()) {
14963 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14964 CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14965 if (RDecl->getDefinition()) {
14966 // C++ [class.union]p1: An object of a class with a non-trivial
14967 // constructor, a non-trivial copy constructor, a non-trivial
14968 // destructor, or a non-trivial copy assignment operator
14969 // cannot be a member of a union, nor can an array of such
14970 // objects.
14971 if (CheckNontrivialField(NewFD))
14972 NewFD->setInvalidDecl();
14973 }
14974 }
14975
14976 // C++ [class.union]p1: If a union contains a member of reference type,
14977 // the program is ill-formed, except when compiling with MSVC extensions
14978 // enabled.
14979 if (EltTy->isReferenceType()) {
14980 Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14981 diag::ext_union_member_of_reference_type :
14982 diag::err_union_member_of_reference_type)
14983 << NewFD->getDeclName() << EltTy;
14984 if (!getLangOpts().MicrosoftExt)
14985 NewFD->setInvalidDecl();
14986 }
14987 }
14988 }
14989
14990 // FIXME: We need to pass in the attributes given an AST
14991 // representation, not a parser representation.
14992 if (D) {
14993 // FIXME: The current scope is almost... but not entirely... correct here.
14994 ProcessDeclAttributes(getCurScope(), NewFD, *D);
14995
14996 if (NewFD->hasAttrs())
14997 CheckAlignasUnderalignment(NewFD);
14998 }
14999
15000 // In auto-retain/release, infer strong retension for fields of
15001 // retainable type.
15002 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
15003 NewFD->setInvalidDecl();
15004
15005 if (T.isObjCGCWeak())
15006 Diag(Loc, diag::warn_attribute_weak_on_field);
15007
15008 NewFD->setAccess(AS);
15009 return NewFD;
15010}
15011
15012bool Sema::CheckNontrivialField(FieldDecl *FD) {
15013 assert(FD)(static_cast <bool> (FD) ? void (0) : __assert_fail ("FD"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 15013, __extension__ __PRETTY_FUNCTION__))
;
15014 assert(getLangOpts().CPlusPlus && "valid check only for C++")(static_cast <bool> (getLangOpts().CPlusPlus &&
"valid check only for C++") ? void (0) : __assert_fail ("getLangOpts().CPlusPlus && \"valid check only for C++\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 15014, __extension__ __PRETTY_FUNCTION__))
;
15015
15016 if (FD->isInvalidDecl() || FD->getType()->isDependentType())
15017 return false;
15018
15019 QualType EltTy = Context.getBaseElementType(FD->getType());
15020 if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15021 CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
15022 if (RDecl->getDefinition()) {
15023 // We check for copy constructors before constructors
15024 // because otherwise we'll never get complaints about
15025 // copy constructors.
15026
15027 CXXSpecialMember member = CXXInvalid;
15028 // We're required to check for any non-trivial constructors. Since the
15029 // implicit default constructor is suppressed if there are any
15030 // user-declared constructors, we just need to check that there is a
15031 // trivial default constructor and a trivial copy constructor. (We don't
15032 // worry about move constructors here, since this is a C++98 check.)
15033 if (RDecl->hasNonTrivialCopyConstructor())
15034 member = CXXCopyConstructor;
15035 else if (!RDecl->hasTrivialDefaultConstructor())
15036 member = CXXDefaultConstructor;
15037 else if (RDecl->hasNonTrivialCopyAssignment())
15038 member = CXXCopyAssignment;
15039 else if (RDecl->hasNonTrivialDestructor())
15040 member = CXXDestructor;
15041
15042 if (member != CXXInvalid) {
15043 if (!getLangOpts().CPlusPlus11 &&
15044 getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
15045 // Objective-C++ ARC: it is an error to have a non-trivial field of
15046 // a union. However, system headers in Objective-C programs
15047 // occasionally have Objective-C lifetime objects within unions,
15048 // and rather than cause the program to fail, we make those
15049 // members unavailable.
15050 SourceLocation Loc = FD->getLocation();
15051 if (getSourceManager().isInSystemHeader(Loc)) {
15052 if (!FD->hasAttr<UnavailableAttr>())
15053 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15054 UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
15055 return false;
15056 }
15057 }
15058
15059 Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
15060 diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
15061 diag::err_illegal_union_or_anon_struct_member)
15062 << FD->getParent()->isUnion() << FD->getDeclName() << member;
15063 DiagnoseNontrivial(RDecl, member);
15064 return !getLangOpts().CPlusPlus11;
15065 }
15066 }
15067 }
15068
15069 return false;
15070}
15071
15072/// TranslateIvarVisibility - Translate visibility from a token ID to an
15073/// AST enum value.
15074static ObjCIvarDecl::AccessControl
15075TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
15076 switch (ivarVisibility) {
15077 default: llvm_unreachable("Unknown visitibility kind")::llvm::llvm_unreachable_internal("Unknown visitibility kind"
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 15077)
;
15078 case tok::objc_private: return ObjCIvarDecl::Private;
15079 case tok::objc_public: return ObjCIvarDecl::Public;
15080 case tok::objc_protected: return ObjCIvarDecl::Protected;
15081 case tok::objc_package: return ObjCIvarDecl::Package;
15082 }
15083}
15084
15085/// ActOnIvar - Each ivar field of an objective-c class is passed into this
15086/// in order to create an IvarDecl object for it.
15087Decl *Sema::ActOnIvar(Scope *S,
15088 SourceLocation DeclStart,
15089 Declarator &D, Expr *BitfieldWidth,
15090 tok::ObjCKeywordKind Visibility) {
15091
15092 IdentifierInfo *II = D.getIdentifier();
15093 Expr *BitWidth = (Expr*)BitfieldWidth;
15094 SourceLocation Loc = DeclStart;
15095 if (II) Loc = D.getIdentifierLoc();
15096
15097 // FIXME: Unnamed fields can be handled in various different ways, for
15098 // example, unnamed unions inject all members into the struct namespace!
15099
15100 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
15101 QualType T = TInfo->getType();
15102
15103 if (BitWidth) {
15104 // 6.7.2.1p3, 6.7.2.1p4
15105 BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
15106 if (!BitWidth)
15107 D.setInvalidType();
15108 } else {
15109 // Not a bitfield.
15110
15111 // validate II.
15112
15113 }
15114 if (T->isReferenceType()) {
15115 Diag(Loc, diag::err_ivar_reference_type);
15116 D.setInvalidType();
15117 }
15118 // C99 6.7.2.1p8: A member of a structure or union may have any type other
15119 // than a variably modified type.
15120 else if (T->isVariablyModifiedType()) {
15121 Diag(Loc, diag::err_typecheck_ivar_variable_size);
15122 D.setInvalidType();
15123 }
15124
15125 // Get the visibility (access control) for this ivar.
15126 ObjCIvarDecl::AccessControl ac =
15127 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
15128 : ObjCIvarDecl::None;
15129 // Must set ivar's DeclContext to its enclosing interface.
15130 ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
15131 if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
15132 return nullptr;
15133 ObjCContainerDecl *EnclosingContext;
15134 if (ObjCImplementationDecl *IMPDecl =
15135 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15136 if (LangOpts.ObjCRuntime.isFragile()) {
15137 // Case of ivar declared in an implementation. Context is that of its class.
15138 EnclosingContext = IMPDecl->getClassInterface();
15139 assert(EnclosingContext && "Implementation has no class interface!")(static_cast <bool> (EnclosingContext && "Implementation has no class interface!"
) ? void (0) : __assert_fail ("EnclosingContext && \"Implementation has no class interface!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 15139, __extension__ __PRETTY_FUNCTION__))
;
15140 }
15141 else
15142 EnclosingContext = EnclosingDecl;
15143 } else {
15144 if (ObjCCategoryDecl *CDecl =
15145 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15146 if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
15147 Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
15148 return nullptr;
15149 }
15150 }
15151 EnclosingContext = EnclosingDecl;
15152 }
15153
15154 // Construct the decl.
15155 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
15156 DeclStart, Loc, II, T,
15157 TInfo, ac, (Expr *)BitfieldWidth);
15158
15159 if (II) {
15160 NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
15161 ForVisibleRedeclaration);
15162 if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
15163 && !isa<TagDecl>(PrevDecl)) {
15164 Diag(Loc, diag::err_duplicate_member) << II;
15165 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15166 NewID->setInvalidDecl();
15167 }
15168 }
15169
15170 // Process attributes attached to the ivar.
15171 ProcessDeclAttributes(S, NewID, D);
15172
15173 if (D.isInvalidType())
15174 NewID->setInvalidDecl();
15175
15176 // In ARC, infer 'retaining' for ivars of retainable type.
15177 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
15178 NewID->setInvalidDecl();
15179
15180 if (D.getDeclSpec().isModulePrivateSpecified())
15181 NewID->setModulePrivate();
15182
15183 if (II) {
15184 // FIXME: When interfaces are DeclContexts, we'll need to add
15185 // these to the interface.
15186 S->AddDecl(NewID);
15187 IdResolver.AddDecl(NewID);
15188 }
15189
15190 if (LangOpts.ObjCRuntime.isNonFragile() &&
15191 !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
15192 Diag(Loc, diag::warn_ivars_in_interface);
15193
15194 return NewID;
15195}
15196
15197/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
15198/// class and class extensions. For every class \@interface and class
15199/// extension \@interface, if the last ivar is a bitfield of any type,
15200/// then add an implicit `char :0` ivar to the end of that interface.
15201void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
15202 SmallVectorImpl<Decl *> &AllIvarDecls) {
15203 if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
15204 return;
15205
15206 Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
15207 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
15208
15209 if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
15210 return;
15211 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
15212 if (!ID) {
15213 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
15214 if (!CD->IsClassExtension())
15215 return;
15216 }
15217 // No need to add this to end of @implementation.
15218 else
15219 return;
15220 }
15221 // All conditions are met. Add a new bitfield to the tail end of ivars.
15222 llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
15223 Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
15224
15225 Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
15226 DeclLoc, DeclLoc, nullptr,
15227 Context.CharTy,
15228 Context.getTrivialTypeSourceInfo(Context.CharTy,
15229 DeclLoc),
15230 ObjCIvarDecl::Private, BW,
15231 true);
15232 AllIvarDecls.push_back(Ivar);
15233}
15234
15235void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
15236 ArrayRef<Decl *> Fields, SourceLocation LBrac,
15237 SourceLocation RBrac, AttributeList *Attr) {
15238 assert(EnclosingDecl && "missing record or interface decl")(static_cast <bool> (EnclosingDecl && "missing record or interface decl"
) ? void (0) : __assert_fail ("EnclosingDecl && \"missing record or interface decl\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 15238, __extension__ __PRETTY_FUNCTION__))
;
15239
15240 // If this is an Objective-C @implementation or category and we have
15241 // new fields here we should reset the layout of the interface since
15242 // it will now change.
15243 if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
15244 ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
15245 switch (DC->getKind()) {
15246 default: break;
15247 case Decl::ObjCCategory:
15248 Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
15249 break;
15250 case Decl::ObjCImplementation:
15251 Context.
15252 ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
15253 break;
15254 }
15255 }
15256
15257 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
15258
15259 // Start counting up the number of named members; make sure to include
15260 // members of anonymous structs and unions in the total.
15261 unsigned NumNamedMembers = 0;
15262 if (Record) {
15263 for (const auto *I : Record->decls()) {
15264 if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
15265 if (IFD->getDeclName())
15266 ++NumNamedMembers;
15267 }
15268 }
15269
15270 // Verify that all the fields are okay.
15271 SmallVector<FieldDecl*, 32> RecFields;
15272
15273 bool ObjCFieldLifetimeErrReported = false;
15274 for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
15275 i != end; ++i) {
15276 FieldDecl *FD = cast<FieldDecl>(*i);
15277
15278 // Get the type for the field.
15279 const Type *FDTy = FD->getType().getTypePtr();
15280
15281 if (!FD->isAnonymousStructOrUnion()) {
15282 // Remember all fields written by the user.
15283 RecFields.push_back(FD);
15284 }
15285
15286 // If the field is already invalid for some reason, don't emit more
15287 // diagnostics about it.
15288 if (FD->isInvalidDecl()) {
15289 EnclosingDecl->setInvalidDecl();
15290 continue;
15291 }
15292
15293 // C99 6.7.2.1p2:
15294 // A structure or union shall not contain a member with
15295 // incomplete or function type (hence, a structure shall not
15296 // contain an instance of itself, but may contain a pointer to
15297 // an instance of itself), except that the last member of a
15298 // structure with more than one named member may have incomplete
15299 // array type; such a structure (and any union containing,
15300 // possibly recursively, a member that is such a structure)
15301 // shall not be a member of a structure or an element of an
15302 // array.
15303 bool IsLastField = (i + 1 == Fields.end());
15304 if (FDTy->isFunctionType()) {
15305 // Field declared as a function.
15306 Diag(FD->getLocation(), diag::err_field_declared_as_function)
15307 << FD->getDeclName();
15308 FD->setInvalidDecl();
15309 EnclosingDecl->setInvalidDecl();
15310 continue;
15311 } else if (FDTy->isIncompleteArrayType() &&
15312 (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
15313 if (Record) {
15314 // Flexible array member.
15315 // Microsoft and g++ is more permissive regarding flexible array.
15316 // It will accept flexible array in union and also
15317 // as the sole element of a struct/class.
15318 unsigned DiagID = 0;
15319 if (!Record->isUnion() && !IsLastField) {
15320 Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
15321 << FD->getDeclName() << FD->getType() << Record->getTagKind();
15322 Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
15323 FD->setInvalidDecl();
15324 EnclosingDecl->setInvalidDecl();
15325 continue;
15326 } else if (Record->isUnion())
15327 DiagID = getLangOpts().MicrosoftExt
15328 ? diag::ext_flexible_array_union_ms
15329 : getLangOpts().CPlusPlus
15330 ? diag::ext_flexible_array_union_gnu
15331 : diag::err_flexible_array_union;
15332 else if (NumNamedMembers < 1)
15333 DiagID = getLangOpts().MicrosoftExt
15334 ? diag::ext_flexible_array_empty_aggregate_ms
15335 : getLangOpts().CPlusPlus
15336 ? diag::ext_flexible_array_empty_aggregate_gnu
15337 : diag::err_flexible_array_empty_aggregate;
15338
15339 if (DiagID)
15340 Diag(FD->getLocation(), DiagID) << FD->getDeclName()
15341 << Record->getTagKind();
15342 // While the layout of types that contain virtual bases is not specified
15343 // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
15344 // virtual bases after the derived members. This would make a flexible
15345 // array member declared at the end of an object not adjacent to the end
15346 // of the type.
15347 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
15348 if (RD->getNumVBases() != 0)
15349 Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
15350 << FD->getDeclName() << Record->getTagKind();
15351 if (!getLangOpts().C99)
15352 Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
15353 << FD->getDeclName() << Record->getTagKind();
15354
15355 // If the element type has a non-trivial destructor, we would not
15356 // implicitly destroy the elements, so disallow it for now.
15357 //
15358 // FIXME: GCC allows this. We should probably either implicitly delete
15359 // the destructor of the containing class, or just allow this.
15360 QualType BaseElem = Context.getBaseElementType(FD->getType());
15361 if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
15362 Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
15363 << FD->getDeclName() << FD->getType();
15364 FD->setInvalidDecl();
15365 EnclosingDecl->setInvalidDecl();
15366 continue;
15367 }
15368 // Okay, we have a legal flexible array member at the end of the struct.
15369 Record->setHasFlexibleArrayMember(true);
15370 } else {
15371 // In ObjCContainerDecl ivars with incomplete array type are accepted,
15372 // unless they are followed by another ivar. That check is done
15373 // elsewhere, after synthesized ivars are known.
15374 }
15375 } else if (!FDTy->isDependentType() &&
15376 RequireCompleteType(FD->getLocation(), FD->getType(),
15377 diag::err_field_incomplete)) {
15378 // Incomplete type
15379 FD->setInvalidDecl();
15380 EnclosingDecl->setInvalidDecl();
15381 continue;
15382 } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
15383 if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
15384 // A type which contains a flexible array member is considered to be a
15385 // flexible array member.
15386 Record->setHasFlexibleArrayMember(true);
15387 if (!Record->isUnion()) {
15388 // If this is a struct/class and this is not the last element, reject
15389 // it. Note that GCC supports variable sized arrays in the middle of
15390 // structures.
15391 if (!IsLastField)
15392 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
15393 << FD->getDeclName() << FD->getType();
15394 else {
15395 // We support flexible arrays at the end of structs in
15396 // other structs as an extension.
15397 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
15398 << FD->getDeclName();
15399 }
15400 }
15401 }
15402 if (isa<ObjCContainerDecl>(EnclosingDecl) &&
15403 RequireNonAbstractType(FD->getLocation(), FD->getType(),
15404 diag::err_abstract_type_in_decl,
15405 AbstractIvarType)) {
15406 // Ivars can not have abstract class types
15407 FD->setInvalidDecl();
15408 }
15409 if (Record && FDTTy->getDecl()->hasObjectMember())
15410 Record->setHasObjectMember(true);
15411 if (Record && FDTTy->getDecl()->hasVolatileMember())
15412 Record->setHasVolatileMember(true);
15413 } else if (FDTy->isObjCObjectType()) {
15414 /// A field cannot be an Objective-c object
15415 Diag(FD->getLocation(), diag::err_statically_allocated_object)
15416 << FixItHint::CreateInsertion(FD->getLocation(), "*");
15417 QualType T = Context.getObjCObjectPointerType(FD->getType());
15418 FD->setType(T);
15419 } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
15420 Record && !ObjCFieldLifetimeErrReported && Record->isUnion()) {
15421 // It's an error in ARC or Weak if a field has lifetime.
15422 // We don't want to report this in a system header, though,
15423 // so we just make the field unavailable.
15424 // FIXME: that's really not sufficient; we need to make the type
15425 // itself invalid to, say, initialize or copy.
15426 QualType T = FD->getType();
15427 if (T.hasNonTrivialObjCLifetime()) {
15428 SourceLocation loc = FD->getLocation();
15429 if (getSourceManager().isInSystemHeader(loc)) {
15430 if (!FD->hasAttr<UnavailableAttr>()) {
15431 FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15432 UnavailableAttr::IR_ARCFieldWithOwnership, loc));
15433 }
15434 } else {
15435 Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
15436 << T->isBlockPointerType() << Record->getTagKind();
15437 }
15438 ObjCFieldLifetimeErrReported = true;
15439 }
15440 } else if (getLangOpts().ObjC1 &&
15441 getLangOpts().getGC() != LangOptions::NonGC &&
15442 Record && !Record->hasObjectMember()) {
15443 if (FD->getType()->isObjCObjectPointerType() ||
15444 FD->getType().isObjCGCStrong())
15445 Record->setHasObjectMember(true);
15446 else if (Context.getAsArrayType(FD->getType())) {
15447 QualType BaseType = Context.getBaseElementType(FD->getType());
15448 if (BaseType->isRecordType() &&
15449 BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
15450 Record->setHasObjectMember(true);
15451 else if (BaseType->isObjCObjectPointerType() ||
15452 BaseType.isObjCGCStrong())
15453 Record->setHasObjectMember(true);
15454 }
15455 }
15456
15457 if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
15458 QualType FT = FD->getType();
15459 if (FT.isNonTrivialToPrimitiveDefaultInitialize())
15460 Record->setNonTrivialToPrimitiveDefaultInitialize(true);
15461 QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
15462 if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial)
15463 Record->setNonTrivialToPrimitiveCopy(true);
15464 if (FT.isDestructedType()) {
15465 Record->setNonTrivialToPrimitiveDestroy(true);
15466 Record->setParamDestroyedInCallee(true);
15467 }
15468
15469 if (const auto *RT = FT->getAs<RecordType>()) {
15470 if (RT->getDecl()->getArgPassingRestrictions() ==
15471 RecordDecl::APK_CanNeverPassInRegs)
15472 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
15473 } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
15474 Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
15475 }
15476
15477 if (Record && FD->getType().isVolatileQualified())
15478 Record->setHasVolatileMember(true);
15479 // Keep track of the number of named members.
15480 if (FD->getIdentifier())
15481 ++NumNamedMembers;
15482 }
15483
15484 // Okay, we successfully defined 'Record'.
15485 if (Record) {
15486 bool Completed = false;
15487 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15488 if (!CXXRecord->isInvalidDecl()) {
15489 // Set access bits correctly on the directly-declared conversions.
15490 for (CXXRecordDecl::conversion_iterator
15491 I = CXXRecord->conversion_begin(),
15492 E = CXXRecord->conversion_end(); I != E; ++I)
15493 I.setAccess((*I)->getAccess());
15494 }
15495
15496 if (!CXXRecord->isDependentType()) {
15497 if (CXXRecord->hasUserDeclaredDestructor()) {
15498 // Adjust user-defined destructor exception spec.
15499 if (getLangOpts().CPlusPlus11)
15500 AdjustDestructorExceptionSpec(CXXRecord,
15501 CXXRecord->getDestructor());
15502 }
15503
15504 // Add any implicitly-declared members to this class.
15505 AddImplicitlyDeclaredMembersToClass(CXXRecord);
15506
15507 if (!CXXRecord->isInvalidDecl()) {
15508 // If we have virtual base classes, we may end up finding multiple
15509 // final overriders for a given virtual function. Check for this
15510 // problem now.
15511 if (CXXRecord->getNumVBases()) {
15512 CXXFinalOverriderMap FinalOverriders;
15513 CXXRecord->getFinalOverriders(FinalOverriders);
15514
15515 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
15516 MEnd = FinalOverriders.end();
15517 M != MEnd; ++M) {
15518 for (OverridingMethods::iterator SO = M->second.begin(),
15519 SOEnd = M->second.end();
15520 SO != SOEnd; ++SO) {
15521 assert(SO->second.size() > 0 &&(static_cast <bool> (SO->second.size() > 0 &&
"Virtual function without overriding functions?") ? void (0)
: __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 15522, __extension__ __PRETTY_FUNCTION__))
15522 "Virtual function without overriding functions?")(static_cast <bool> (SO->second.size() > 0 &&
"Virtual function without overriding functions?") ? void (0)
: __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 15522, __extension__ __PRETTY_FUNCTION__))
;
15523 if (SO->second.size() == 1)
15524 continue;
15525
15526 // C++ [class.virtual]p2:
15527 // In a derived class, if a virtual member function of a base
15528 // class subobject has more than one final overrider the
15529 // program is ill-formed.
15530 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
15531 << (const NamedDecl *)M->first << Record;
15532 Diag(M->first->getLocation(),
15533 diag::note_overridden_virtual_function);
15534 for (OverridingMethods::overriding_iterator
15535 OM = SO->second.begin(),
15536 OMEnd = SO->second.end();
15537 OM != OMEnd; ++OM)
15538 Diag(OM->Method->getLocation(), diag::note_final_overrider)
15539 << (const NamedDecl *)M->first << OM->Method->getParent();
15540
15541 Record->setInvalidDecl();
15542 }
15543 }
15544 CXXRecord->completeDefinition(&FinalOverriders);
15545 Completed = true;
15546 }
15547 }
15548 }
15549 }
15550
15551 if (!Completed)
15552 Record->completeDefinition();
15553
15554 // We may have deferred checking for a deleted destructor. Check now.
15555 if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
15556 auto *Dtor = CXXRecord->getDestructor();
15557 if (Dtor && Dtor->isImplicit() &&
15558 ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
15559 CXXRecord->setImplicitDestructorIsDeleted();
15560 SetDeclDeleted(Dtor, CXXRecord->getLocation());
15561 }
15562 }
15563
15564 if (Record->hasAttrs()) {
15565 CheckAlignasUnderalignment(Record);
15566
15567 if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
15568 checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
15569 IA->getRange(), IA->getBestCase(),
15570 IA->getSemanticSpelling());
15571 }
15572
15573 // Check if the structure/union declaration is a type that can have zero
15574 // size in C. For C this is a language extension, for C++ it may cause
15575 // compatibility problems.
15576 bool CheckForZeroSize;
15577 if (!getLangOpts().CPlusPlus) {
15578 CheckForZeroSize = true;
15579 } else {
15580 // For C++ filter out types that cannot be referenced in C code.
15581 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
15582 CheckForZeroSize =
15583 CXXRecord->getLexicalDeclContext()->isExternCContext() &&
15584 !CXXRecord->isDependentType() &&
15585 CXXRecord->isCLike();
15586 }
15587 if (CheckForZeroSize) {
15588 bool ZeroSize = true;
15589 bool IsEmpty = true;
15590 unsigned NonBitFields = 0;
15591 for (RecordDecl::field_iterator I = Record->field_begin(),
15592 E = Record->field_end();
15593 (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
15594 IsEmpty = false;
15595 if (I->isUnnamedBitfield()) {
15596 if (!I->isZeroLengthBitField(Context))
15597 ZeroSize = false;
15598 } else {
15599 ++NonBitFields;
15600 QualType FieldType = I->getType();
15601 if (FieldType->isIncompleteType() ||
15602 !Context.getTypeSizeInChars(FieldType).isZero())
15603 ZeroSize = false;
15604 }
15605 }
15606
15607 // Empty structs are an extension in C (C99 6.7.2.1p7). They are
15608 // allowed in C++, but warn if its declaration is inside
15609 // extern "C" block.
15610 if (ZeroSize) {
15611 Diag(RecLoc, getLangOpts().CPlusPlus ?
15612 diag::warn_zero_size_struct_union_in_extern_c :
15613 diag::warn_zero_size_struct_union_compat)
15614 << IsEmpty << Record->isUnion() << (NonBitFields > 1);
15615 }
15616
15617 // Structs without named members are extension in C (C99 6.7.2.1p7),
15618 // but are accepted by GCC.
15619 if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
15620 Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
15621 diag::ext_no_named_members_in_struct_union)
15622 << Record->isUnion();
15623 }
15624 }
15625 } else {
15626 ObjCIvarDecl **ClsFields =
15627 reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
15628 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
15629 ID->setEndOfDefinitionLoc(RBrac);
15630 // Add ivar's to class's DeclContext.
15631 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15632 ClsFields[i]->setLexicalDeclContext(ID);
15633 ID->addDecl(ClsFields[i]);
15634 }
15635 // Must enforce the rule that ivars in the base classes may not be
15636 // duplicates.
15637 if (ID->getSuperClass())
15638 DiagnoseDuplicateIvars(ID, ID->getSuperClass());
15639 } else if (ObjCImplementationDecl *IMPDecl =
15640 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15641 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl")(static_cast <bool> (IMPDecl && "ActOnFields - missing ObjCImplementationDecl"
) ? void (0) : __assert_fail ("IMPDecl && \"ActOnFields - missing ObjCImplementationDecl\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 15641, __extension__ __PRETTY_FUNCTION__))
;
15642 for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
15643 // Ivar declared in @implementation never belongs to the implementation.
15644 // Only it is in implementation's lexical context.
15645 ClsFields[I]->setLexicalDeclContext(IMPDecl);
15646 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
15647 IMPDecl->setIvarLBraceLoc(LBrac);
15648 IMPDecl->setIvarRBraceLoc(RBrac);
15649 } else if (ObjCCategoryDecl *CDecl =
15650 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15651 // case of ivars in class extension; all other cases have been
15652 // reported as errors elsewhere.
15653 // FIXME. Class extension does not have a LocEnd field.
15654 // CDecl->setLocEnd(RBrac);
15655 // Add ivar's to class extension's DeclContext.
15656 // Diagnose redeclaration of private ivars.
15657 ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
15658 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
15659 if (IDecl) {
15660 if (const ObjCIvarDecl *ClsIvar =
15661 IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
15662 Diag(ClsFields[i]->getLocation(),
15663 diag::err_duplicate_ivar_declaration);
15664 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
15665 continue;
15666 }
15667 for (const auto *Ext : IDecl->known_extensions()) {
15668 if (const ObjCIvarDecl *ClsExtIvar
15669 = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
15670 Diag(ClsFields[i]->getLocation(),
15671 diag::err_duplicate_ivar_declaration);
15672 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
15673 continue;
15674 }
15675 }
15676 }
15677 ClsFields[i]->setLexicalDeclContext(CDecl);
15678 CDecl->addDecl(ClsFields[i]);
15679 }
15680 CDecl->setIvarLBraceLoc(LBrac);
15681 CDecl->setIvarRBraceLoc(RBrac);
15682 }
15683 }
15684
15685 if (Attr)
15686 ProcessDeclAttributeList(S, Record, Attr);
15687}
15688
15689/// \brief Determine whether the given integral value is representable within
15690/// the given type T.
15691static bool isRepresentableIntegerValue(ASTContext &Context,
15692 llvm::APSInt &Value,
15693 QualType T) {
15694 assert((T->isIntegralType(Context) || T->isEnumeralType()) &&(static_cast <bool> ((T->isIntegralType(Context) || T
->isEnumeralType()) && "Integral type required!") ?
void (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 15695, __extension__ __PRETTY_FUNCTION__))
15695 "Integral type required!")(static_cast <bool> ((T->isIntegralType(Context) || T
->isEnumeralType()) && "Integral type required!") ?
void (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 15695, __extension__ __PRETTY_FUNCTION__))
;
15696 unsigned BitWidth = Context.getIntWidth(T);
15697
15698 if (Value.isUnsigned() || Value.isNonNegative()) {
15699 if (T->isSignedIntegerOrEnumerationType())
15700 --BitWidth;
15701 return Value.getActiveBits() <= BitWidth;
15702 }
15703 return Value.getMinSignedBits() <= BitWidth;
15704}
15705
15706// \brief Given an integral type, return the next larger integral type
15707// (or a NULL type of no such type exists).
15708static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
15709 // FIXME: Int128/UInt128 support, which also needs to be introduced into
15710 // enum checking below.
15711 assert((T->isIntegralType(Context) ||(static_cast <bool> ((T->isIntegralType(Context) || T
->isEnumeralType()) && "Integral type required!") ?
void (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 15712, __extension__ __PRETTY_FUNCTION__))
15712 T->isEnumeralType()) && "Integral type required!")(static_cast <bool> ((T->isIntegralType(Context) || T
->isEnumeralType()) && "Integral type required!") ?
void (0) : __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 15712, __extension__ __PRETTY_FUNCTION__))
;
15713 const unsigned NumTypes = 4;
15714 QualType SignedIntegralTypes[NumTypes] = {
15715 Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
15716 };
15717 QualType UnsignedIntegralTypes[NumTypes] = {
15718 Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
15719 Context.UnsignedLongLongTy
15720 };
15721
15722 unsigned BitWidth = Context.getTypeSize(T);
15723 QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
15724 : UnsignedIntegralTypes;
15725 for (unsigned I = 0; I != NumTypes; ++I)
15726 if (Context.getTypeSize(Types[I]) > BitWidth)
15727 return Types[I];
15728
15729 return QualType();
15730}
15731
15732EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
15733 EnumConstantDecl *LastEnumConst,
15734 SourceLocation IdLoc,
15735 IdentifierInfo *Id,
15736 Expr *Val) {
15737 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15738 llvm::APSInt EnumVal(IntWidth);
15739 QualType EltTy;
15740
15741 if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
15742 Val = nullptr;
15743
15744 if (Val)
15745 Val = DefaultLvalueConversion(Val).get();
15746
15747 if (Val) {
15748 if (Enum->isDependentType() || Val->isTypeDependent())
15749 EltTy = Context.DependentTy;
15750 else {
15751 if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
15752 !getLangOpts().MSVCCompat) {
15753 // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
15754 // constant-expression in the enumerator-definition shall be a converted
15755 // constant expression of the underlying type.
15756 EltTy = Enum->getIntegerType();
15757 ExprResult Converted =
15758 CheckConvertedConstantExpression(Val, EltTy, EnumVal,
15759 CCEK_Enumerator);
15760 if (Converted.isInvalid())
15761 Val = nullptr;
15762 else
15763 Val = Converted.get();
15764 } else if (!Val->isValueDependent() &&
15765 !(Val = VerifyIntegerConstantExpression(Val,
15766 &EnumVal).get())) {
15767 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
15768 } else {
15769 if (Enum->isComplete()) {
15770 EltTy = Enum->getIntegerType();
15771
15772 // In Obj-C and Microsoft mode, require the enumeration value to be
15773 // representable in the underlying type of the enumeration. In C++11,
15774 // we perform a non-narrowing conversion as part of converted constant
15775 // expression checking.
15776 if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15777 if (getLangOpts().MSVCCompat) {
15778 Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
15779 Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
15780 } else
15781 Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
15782 } else
15783 Val = ImpCastExprToType(Val, EltTy,
15784 EltTy->isBooleanType() ?
15785 CK_IntegralToBoolean : CK_IntegralCast)
15786 .get();
15787 } else if (getLangOpts().CPlusPlus) {
15788 // C++11 [dcl.enum]p5:
15789 // If the underlying type is not fixed, the type of each enumerator
15790 // is the type of its initializing value:
15791 // - If an initializer is specified for an enumerator, the
15792 // initializing value has the same type as the expression.
15793 EltTy = Val->getType();
15794 } else {
15795 // C99 6.7.2.2p2:
15796 // The expression that defines the value of an enumeration constant
15797 // shall be an integer constant expression that has a value
15798 // representable as an int.
15799
15800 // Complain if the value is not representable in an int.
15801 if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
15802 Diag(IdLoc, diag::ext_enum_value_not_int)
15803 << EnumVal.toString(10) << Val->getSourceRange()
15804 << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
15805 else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
15806 // Force the type of the expression to 'int'.
15807 Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
15808 }
15809 EltTy = Val->getType();
15810 }
15811 }
15812 }
15813 }
15814
15815 if (!Val) {
15816 if (Enum->isDependentType())
15817 EltTy = Context.DependentTy;
15818 else if (!LastEnumConst) {
15819 // C++0x [dcl.enum]p5:
15820 // If the underlying type is not fixed, the type of each enumerator
15821 // is the type of its initializing value:
15822 // - If no initializer is specified for the first enumerator, the
15823 // initializing value has an unspecified integral type.
15824 //
15825 // GCC uses 'int' for its unspecified integral type, as does
15826 // C99 6.7.2.2p3.
15827 if (Enum->isFixed()) {
15828 EltTy = Enum->getIntegerType();
15829 }
15830 else {
15831 EltTy = Context.IntTy;
15832 }
15833 } else {
15834 // Assign the last value + 1.
15835 EnumVal = LastEnumConst->getInitVal();
15836 ++EnumVal;
15837 EltTy = LastEnumConst->getType();
15838
15839 // Check for overflow on increment.
15840 if (EnumVal < LastEnumConst->getInitVal()) {
15841 // C++0x [dcl.enum]p5:
15842 // If the underlying type is not fixed, the type of each enumerator
15843 // is the type of its initializing value:
15844 //
15845 // - Otherwise the type of the initializing value is the same as
15846 // the type of the initializing value of the preceding enumerator
15847 // unless the incremented value is not representable in that type,
15848 // in which case the type is an unspecified integral type
15849 // sufficient to contain the incremented value. If no such type
15850 // exists, the program is ill-formed.
15851 QualType T = getNextLargerIntegralType(Context, EltTy);
15852 if (T.isNull() || Enum->isFixed()) {
15853 // There is no integral type larger enough to represent this
15854 // value. Complain, then allow the value to wrap around.
15855 EnumVal = LastEnumConst->getInitVal();
15856 EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
15857 ++EnumVal;
15858 if (Enum->isFixed())
15859 // When the underlying type is fixed, this is ill-formed.
15860 Diag(IdLoc, diag::err_enumerator_wrapped)
15861 << EnumVal.toString(10)
15862 << EltTy;
15863 else
15864 Diag(IdLoc, diag::ext_enumerator_increment_too_large)
15865 << EnumVal.toString(10);
15866 } else {
15867 EltTy = T;
15868 }
15869
15870 // Retrieve the last enumerator's value, extent that type to the
15871 // type that is supposed to be large enough to represent the incremented
15872 // value, then increment.
15873 EnumVal = LastEnumConst->getInitVal();
15874 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15875 EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
15876 ++EnumVal;
15877
15878 // If we're not in C++, diagnose the overflow of enumerator values,
15879 // which in C99 means that the enumerator value is not representable in
15880 // an int (C99 6.7.2.2p2). However, we support GCC's extension that
15881 // permits enumerator values that are representable in some larger
15882 // integral type.
15883 if (!getLangOpts().CPlusPlus && !T.isNull())
15884 Diag(IdLoc, diag::warn_enum_value_overflow);
15885 } else if (!getLangOpts().CPlusPlus &&
15886 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
15887 // Enforce C99 6.7.2.2p2 even when we compute the next value.
15888 Diag(IdLoc, diag::ext_enum_value_not_int)
15889 << EnumVal.toString(10) << 1;
15890 }
15891 }
15892 }
15893
15894 if (!EltTy->isDependentType()) {
15895 // Make the enumerator value match the signedness and size of the
15896 // enumerator's type.
15897 EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
15898 EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
15899 }
15900
15901 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
15902 Val, EnumVal);
15903}
15904
15905Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
15906 SourceLocation IILoc) {
15907 if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
15908 !getLangOpts().CPlusPlus)
15909 return SkipBodyInfo();
15910
15911 // We have an anonymous enum definition. Look up the first enumerator to
15912 // determine if we should merge the definition with an existing one and
15913 // skip the body.
15914 NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
15915 forRedeclarationInCurContext());
15916 auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
15917 if (!PrevECD)
15918 return SkipBodyInfo();
15919
15920 EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
15921 NamedDecl *Hidden;
15922 if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
15923 SkipBodyInfo Skip;
15924 Skip.Previous = Hidden;
15925 return Skip;
15926 }
15927
15928 return SkipBodyInfo();
15929}
15930
15931Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
15932 SourceLocation IdLoc, IdentifierInfo *Id,
15933 AttributeList *Attr,
15934 SourceLocation EqualLoc, Expr *Val) {
15935 EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
15936 EnumConstantDecl *LastEnumConst =
15937 cast_or_null<EnumConstantDecl>(lastEnumConst);
15938
15939 // The scope passed in may not be a decl scope. Zip up the scope tree until
15940 // we find one that is.
15941 S = getNonFieldDeclScope(S);
15942
15943 // Verify that there isn't already something declared with this name in this
15944 // scope.
15945 NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
15946 ForVisibleRedeclaration);
15947 if (PrevDecl && PrevDecl->isTemplateParameter()) {
15948 // Maybe we will complain about the shadowed template parameter.
15949 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
15950 // Just pretend that we didn't see the previous declaration.
15951 PrevDecl = nullptr;
15952 }
15953
15954 // C++ [class.mem]p15:
15955 // If T is the name of a class, then each of the following shall have a name
15956 // different from T:
15957 // - every enumerator of every member of class T that is an unscoped
15958 // enumerated type
15959 if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
15960 DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
15961 DeclarationNameInfo(Id, IdLoc));
15962
15963 EnumConstantDecl *New =
15964 CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
15965 if (!New)
15966 return nullptr;
15967
15968 if (PrevDecl) {
15969 // When in C++, we may get a TagDecl with the same name; in this case the
15970 // enum constant will 'hide' the tag.
15971 assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&(static_cast <bool> ((getLangOpts().CPlusPlus || !isa<
TagDecl>(PrevDecl)) && "Received TagDecl when not in C++!"
) ? void (0) : __assert_fail ("(getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && \"Received TagDecl when not in C++!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 15972, __extension__ __PRETTY_FUNCTION__))
15972 "Received TagDecl when not in C++!")(static_cast <bool> ((getLangOpts().CPlusPlus || !isa<
TagDecl>(PrevDecl)) && "Received TagDecl when not in C++!"
) ? void (0) : __assert_fail ("(getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) && \"Received TagDecl when not in C++!\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 15972, __extension__ __PRETTY_FUNCTION__))
;
15973 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
15974 if (isa<EnumConstantDecl>(PrevDecl))
15975 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15976 else
15977 Diag(IdLoc, diag::err_redefinition) << Id;
15978 notePreviousDefinition(PrevDecl, IdLoc);
15979 return nullptr;
15980 }
15981 }
15982
15983 // Process attributes.
15984 if (Attr) ProcessDeclAttributeList(S, New, Attr);
15985 AddPragmaAttributes(S, New);
15986
15987 // Register this decl in the current scope stack.
15988 New->setAccess(TheEnumDecl->getAccess());
15989 PushOnScopeChains(New, S);
15990
15991 ActOnDocumentableDecl(New);
15992
15993 return New;
15994}
15995
15996// Returns true when the enum initial expression does not trigger the
15997// duplicate enum warning. A few common cases are exempted as follows:
15998// Element2 = Element1
15999// Element2 = Element1 + 1
16000// Element2 = Element1 - 1
16001// Where Element2 and Element1 are from the same enum.
16002static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
16003 Expr *InitExpr = ECD->getInitExpr();
16004 if (!InitExpr)
16005 return true;
16006 InitExpr = InitExpr->IgnoreImpCasts();
16007
16008 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
16009 if (!BO->isAdditiveOp())
16010 return true;
16011 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
16012 if (!IL)
16013 return true;
16014 if (IL->getValue() != 1)
16015 return true;
16016
16017 InitExpr = BO->getLHS();
16018 }
16019
16020 // This checks if the elements are from the same enum.
16021 DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
16022 if (!DRE)
16023 return true;
16024
16025 EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
16026 if (!EnumConstant)
16027 return true;
16028
16029 if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
16030 Enum)
16031 return true;
16032
16033 return false;
16034}
16035
16036// Emits a warning when an element is implicitly set a value that
16037// a previous element has already been set to.
16038static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
16039 EnumDecl *Enum, QualType EnumType) {
16040 // Avoid anonymous enums
16041 if (!Enum->getIdentifier())
16042 return;
16043
16044 // Only check for small enums.
16045 if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
16046 return;
16047
16048 if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
16049 return;
16050
16051 typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
16052 typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
16053
16054 typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
16055 typedef llvm::DenseMap<int64_t, DeclOrVector> ValueToVectorMap;
16056
16057 // Use int64_t as a key to avoid needing special handling for DenseMap keys.
16058 auto EnumConstantToKey = [](const EnumConstantDecl *D) {
16059 llvm::APSInt Val = D->getInitVal();
16060 return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
16061 };
16062
16063 DuplicatesVector DupVector;
16064 ValueToVectorMap EnumMap;
16065
16066 // Populate the EnumMap with all values represented by enum constants without
16067 // an initializer.
16068 for (auto *Element : Elements) {
16069 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
16070
16071 // Null EnumConstantDecl means a previous diagnostic has been emitted for
16072 // this constant. Skip this enum since it may be ill-formed.
16073 if (!ECD) {
16074 return;
16075 }
16076
16077 // Constants with initalizers are handled in the next loop.
16078 if (ECD->getInitExpr())
16079 continue;
16080
16081 // Duplicate values are handled in the next loop.
16082 EnumMap.insert({EnumConstantToKey(ECD), ECD});
16083 }
16084
16085 if (EnumMap.size() == 0)
16086 return;
16087
16088 // Create vectors for any values that has duplicates.
16089 for (auto *Element : Elements) {
16090 // The last loop returned if any constant was null.
16091 EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
16092 if (!ValidDuplicateEnum(ECD, Enum))
16093 continue;
16094
16095 auto Iter = EnumMap.find(EnumConstantToKey(ECD));
16096 if (Iter == EnumMap.end())
16097 continue;
16098
16099 DeclOrVector& Entry = Iter->second;
16100 if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
16101 // Ensure constants are different.
16102 if (D == ECD)
16103 continue;
16104
16105 // Create new vector and push values onto it.
16106 auto Vec = llvm::make_unique<ECDVector>();
16107 Vec->push_back(D);
16108 Vec->push_back(ECD);
16109
16110 // Update entry to point to the duplicates vector.
16111 Entry = Vec.get();
16112
16113 // Store the vector somewhere we can consult later for quick emission of
16114 // diagnostics.
16115 DupVector.emplace_back(std::move(Vec));
16116 continue;
16117 }
16118
16119 ECDVector *Vec = Entry.get<ECDVector*>();
16120 // Make sure constants are not added more than once.
16121 if (*Vec->begin() == ECD)
16122 continue;
16123
16124 Vec->push_back(ECD);
16125 }
16126
16127 // Emit diagnostics.
16128 for (const auto &Vec : DupVector) {
16129 assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.")(static_cast <bool> (Vec->size() > 1 && "ECDVector should have at least 2 elements."
) ? void (0) : __assert_fail ("Vec->size() > 1 && \"ECDVector should have at least 2 elements.\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 16129, __extension__ __PRETTY_FUNCTION__))
;
16130
16131 // Emit warning for one enum constant.
16132 auto *FirstECD = Vec->front();
16133 S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
16134 << FirstECD << FirstECD->getInitVal().toString(10)
16135 << FirstECD->getSourceRange();
16136
16137 // Emit one note for each of the remaining enum constants with
16138 // the same value.
16139 for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
16140 S.Diag(ECD->getLocation(), diag::note_duplicate_element)
16141 << ECD << ECD->getInitVal().toString(10)
16142 << ECD->getSourceRange();
16143 }
16144}
16145
16146bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
16147 bool AllowMask) const {
16148 assert(ED->isClosedFlag() && "looking for value in non-flag or open enum")(static_cast <bool> (ED->isClosedFlag() && "looking for value in non-flag or open enum"
) ? void (0) : __assert_fail ("ED->isClosedFlag() && \"looking for value in non-flag or open enum\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 16148, __extension__ __PRETTY_FUNCTION__))
;
16149 assert(ED->isCompleteDefinition() && "expected enum definition")(static_cast <bool> (ED->isCompleteDefinition() &&
"expected enum definition") ? void (0) : __assert_fail ("ED->isCompleteDefinition() && \"expected enum definition\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 16149, __extension__ __PRETTY_FUNCTION__))
;
16150
16151 auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
16152 llvm::APInt &FlagBits = R.first->second;
16153
16154 if (R.second) {
16155 for (auto *E : ED->enumerators()) {
16156 const auto &EVal = E->getInitVal();
16157 // Only single-bit enumerators introduce new flag values.
16158 if (EVal.isPowerOf2())
16159 FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
16160 }
16161 }
16162
16163 // A value is in a flag enum if either its bits are a subset of the enum's
16164 // flag bits (the first condition) or we are allowing masks and the same is
16165 // true of its complement (the second condition). When masks are allowed, we
16166 // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
16167 //
16168 // While it's true that any value could be used as a mask, the assumption is
16169 // that a mask will have all of the insignificant bits set. Anything else is
16170 // likely a logic error.
16171 llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
16172 return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
16173}
16174
16175void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
16176 Decl *EnumDeclX,
16177 ArrayRef<Decl *> Elements,
16178 Scope *S, AttributeList *Attr) {
16179 EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
16180 QualType EnumType = Context.getTypeDeclType(Enum);
16181
16182 if (Attr)
16183 ProcessDeclAttributeList(S, Enum, Attr);
16184
16185 if (Enum->isDependentType()) {
16186 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16187 EnumConstantDecl *ECD =
16188 cast_or_null<EnumConstantDecl>(Elements[i]);
16189 if (!ECD) continue;
16190
16191 ECD->setType(EnumType);
16192 }
16193
16194 Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
16195 return;
16196 }
16197
16198 // TODO: If the result value doesn't fit in an int, it must be a long or long
16199 // long value. ISO C does not support this, but GCC does as an extension,
16200 // emit a warning.
16201 unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16202 unsigned CharWidth = Context.getTargetInfo().getCharWidth();
16203 unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
16204
16205 // Verify that all the values are okay, compute the size of the values, and
16206 // reverse the list.
16207 unsigned NumNegativeBits = 0;
16208 unsigned NumPositiveBits = 0;
16209
16210 // Keep track of whether all elements have type int.
16211 bool AllElementsInt = true;
16212
16213 for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
16214 EnumConstantDecl *ECD =
16215 cast_or_null<EnumConstantDecl>(Elements[i]);
16216 if (!ECD) continue; // Already issued a diagnostic.
16217
16218 const llvm::APSInt &InitVal = ECD->getInitVal();
16219
16220 // Keep track of the size of positive and negative values.
16221 if (InitVal.isUnsigned() || InitVal.isNonNegative())
16222 NumPositiveBits = std::max(NumPositiveBits,
16223 (unsigned)InitVal.getActiveBits());
16224 else
16225 NumNegativeBits = std::max(NumNegativeBits,
16226 (unsigned)InitVal.getMinSignedBits());
16227
16228 // Keep track of whether every enum element has type int (very commmon).
16229 if (AllElementsInt)
16230 AllElementsInt = ECD->getType() == Context.IntTy;
16231 }
16232
16233 // Figure out the type that should be used for this enum.
16234 QualType BestType;
16235 unsigned BestWidth;
16236
16237 // C++0x N3000 [conv.prom]p3:
16238 // An rvalue of an unscoped enumeration type whose underlying
16239 // type is not fixed can be converted to an rvalue of the first
16240 // of the following types that can represent all the values of
16241 // the enumeration: int, unsigned int, long int, unsigned long
16242 // int, long long int, or unsigned long long int.
16243 // C99 6.4.4.3p2:
16244 // An identifier declared as an enumeration constant has type int.
16245 // The C99 rule is modified by a gcc extension
16246 QualType BestPromotionType;
16247
16248 bool Packed = Enum->hasAttr<PackedAttr>();
16249 // -fshort-enums is the equivalent to specifying the packed attribute on all
16250 // enum definitions.
16251 if (LangOpts.ShortEnums)
16252 Packed = true;
16253
16254 // If the enum already has a type because it is fixed or dictated by the
16255 // target, promote that type instead of analyzing the enumerators.
16256 if (Enum->isComplete()) {
16257 BestType = Enum->getIntegerType();
16258 if (BestType->isPromotableIntegerType())
16259 BestPromotionType = Context.getPromotedIntegerType(BestType);
16260 else
16261 BestPromotionType = BestType;
16262
16263 BestWidth = Context.getIntWidth(BestType);
16264 }
16265 else if (NumNegativeBits) {
16266 // If there is a negative value, figure out the smallest integer type (of
16267 // int/long/longlong) that fits.
16268 // If it's packed, check also if it fits a char or a short.
16269 if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
16270 BestType = Context.SignedCharTy;
16271 BestWidth = CharWidth;
16272 } else if (Packed && NumNegativeBits <= ShortWidth &&
16273 NumPositiveBits < ShortWidth) {
16274 BestType = Context.ShortTy;
16275 BestWidth = ShortWidth;
16276 } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
16277 BestType = Context.IntTy;
16278 BestWidth = IntWidth;
16279 } else {
16280 BestWidth = Context.getTargetInfo().getLongWidth();
16281
16282 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
16283 BestType = Context.LongTy;
16284 } else {
16285 BestWidth = Context.getTargetInfo().getLongLongWidth();
16286
16287 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
16288 Diag(Enum->getLocation(), diag::ext_enum_too_large);
16289 BestType = Context.LongLongTy;
16290 }
16291 }
16292 BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
16293 } else {
16294 // If there is no negative value, figure out the smallest type that fits
16295 // all of the enumerator values.
16296 // If it's packed, check also if it fits a char or a short.
16297 if (Packed && NumPositiveBits <= CharWidth) {
16298 BestType = Context.UnsignedCharTy;
16299 BestPromotionType = Context.IntTy;
16300 BestWidth = CharWidth;
16301 } else if (Packed && NumPositiveBits <= ShortWidth) {
16302 BestType = Context.UnsignedShortTy;
16303 BestPromotionType = Context.IntTy;
16304 BestWidth = ShortWidth;
16305 } else if (NumPositiveBits <= IntWidth) {
16306 BestType = Context.UnsignedIntTy;
16307 BestWidth = IntWidth;
16308 BestPromotionType
16309 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16310 ? Context.UnsignedIntTy : Context.IntTy;
16311 } else if (NumPositiveBits <=
16312 (BestWidth = Context.getTargetInfo().getLongWidth())) {
16313 BestType = Context.UnsignedLongTy;
16314 BestPromotionType
16315 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16316 ? Context.UnsignedLongTy : Context.LongTy;
16317 } else {
16318 BestWidth = Context.getTargetInfo().getLongLongWidth();
16319 assert(NumPositiveBits <= BestWidth &&(static_cast <bool> (NumPositiveBits <= BestWidth &&
"How could an initializer get larger than ULL?") ? void (0) :
__assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 16320, __extension__ __PRETTY_FUNCTION__))
16320 "How could an initializer get larger than ULL?")(static_cast <bool> (NumPositiveBits <= BestWidth &&
"How could an initializer get larger than ULL?") ? void (0) :
__assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 16320, __extension__ __PRETTY_FUNCTION__))
;
16321 BestType = Context.UnsignedLongLongTy;
16322 BestPromotionType
16323 = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16324 ? Context.UnsignedLongLongTy : Context.LongLongTy;
16325 }
16326 }
16327
16328 // Loop over all of the enumerator constants, changing their types to match
16329 // the type of the enum if needed.
16330 for (auto *D : Elements) {
16331 auto *ECD = cast_or_null<EnumConstantDecl>(D);
16332 if (!ECD) continue; // Already issued a diagnostic.
16333
16334 // Standard C says the enumerators have int type, but we allow, as an
16335 // extension, the enumerators to be larger than int size. If each
16336 // enumerator value fits in an int, type it as an int, otherwise type it the
16337 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
16338 // that X has type 'int', not 'unsigned'.
16339
16340 // Determine whether the value fits into an int.
16341 llvm::APSInt InitVal = ECD->getInitVal();
16342
16343 // If it fits into an integer type, force it. Otherwise force it to match
16344 // the enum decl type.
16345 QualType NewTy;
16346 unsigned NewWidth;
16347 bool NewSign;
16348 if (!getLangOpts().CPlusPlus &&
16349 !Enum->isFixed() &&
16350 isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
16351 NewTy = Context.IntTy;
16352 NewWidth = IntWidth;
16353 NewSign = true;
16354 } else if (ECD->getType() == BestType) {
16355 // Already the right type!
16356 if (getLangOpts().CPlusPlus)
16357 // C++ [dcl.enum]p4: Following the closing brace of an
16358 // enum-specifier, each enumerator has the type of its
16359 // enumeration.
16360 ECD->setType(EnumType);
16361 continue;
16362 } else {
16363 NewTy = BestType;
16364 NewWidth = BestWidth;
16365 NewSign = BestType->isSignedIntegerOrEnumerationType();
16366 }
16367
16368 // Adjust the APSInt value.
16369 InitVal = InitVal.extOrTrunc(NewWidth);
16370 InitVal.setIsSigned(NewSign);
16371 ECD->setInitVal(InitVal);
16372
16373 // Adjust the Expr initializer and type.
16374 if (ECD->getInitExpr() &&
16375 !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
16376 ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
16377 CK_IntegralCast,
16378 ECD->getInitExpr(),
16379 /*base paths*/ nullptr,
16380 VK_RValue));
16381 if (getLangOpts().CPlusPlus)
16382 // C++ [dcl.enum]p4: Following the closing brace of an
16383 // enum-specifier, each enumerator has the type of its
16384 // enumeration.
16385 ECD->setType(EnumType);
16386 else
16387 ECD->setType(NewTy);
16388 }
16389
16390 Enum->completeDefinition(BestType, BestPromotionType,
16391 NumPositiveBits, NumNegativeBits);
16392
16393 CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
16394
16395 if (Enum->isClosedFlag()) {
16396 for (Decl *D : Elements) {
16397 EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
16398 if (!ECD) continue; // Already issued a diagnostic.
16399
16400 llvm::APSInt InitVal = ECD->getInitVal();
16401 if (InitVal != 0 && !InitVal.isPowerOf2() &&
16402 !IsValueInFlagEnum(Enum, InitVal, true))
16403 Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
16404 << ECD << Enum;
16405 }
16406 }
16407
16408 // Now that the enum type is defined, ensure it's not been underaligned.
16409 if (Enum->hasAttrs())
16410 CheckAlignasUnderalignment(Enum);
16411}
16412
16413Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
16414 SourceLocation StartLoc,
16415 SourceLocation EndLoc) {
16416 StringLiteral *AsmString = cast<StringLiteral>(expr);
16417
16418 FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
16419 AsmString, StartLoc,
16420 EndLoc);
16421 CurContext->addDecl(New);
16422 return New;
16423}
16424
16425static void checkModuleImportContext(Sema &S, Module *M,
16426 SourceLocation ImportLoc, DeclContext *DC,
16427 bool FromInclude = false) {
16428 SourceLocation ExternCLoc;
16429
16430 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
16431 switch (LSD->getLanguage()) {
16432 case LinkageSpecDecl::lang_c:
16433 if (ExternCLoc.isInvalid())
16434 ExternCLoc = LSD->getLocStart();
16435 break;
16436 case LinkageSpecDecl::lang_cxx:
16437 break;
16438 }
16439 DC = LSD->getParent();
16440 }
16441
16442 while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
16443 DC = DC->getParent();
16444
16445 if (!isa<TranslationUnitDecl>(DC)) {
16446 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
16447 ? diag::ext_module_import_not_at_top_level_noop
16448 : diag::err_module_import_not_at_top_level_fatal)
16449 << M->getFullModuleName() << DC;
16450 S.Diag(cast<Decl>(DC)->getLocStart(),
16451 diag::note_module_import_not_at_top_level) << DC;
16452 } else if (!M->IsExternC && ExternCLoc.isValid()) {
16453 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
16454 << M->getFullModuleName();
16455 S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
16456 }
16457}
16458
16459Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
16460 SourceLocation ModuleLoc,
16461 ModuleDeclKind MDK,
16462 ModuleIdPath Path) {
16463 assert(getLangOpts().ModulesTS &&(static_cast <bool> (getLangOpts().ModulesTS &&
"should only have module decl in modules TS") ? void (0) : __assert_fail
("getLangOpts().ModulesTS && \"should only have module decl in modules TS\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 16464, __extension__ __PRETTY_FUNCTION__))
16464 "should only have module decl in modules TS")(static_cast <bool> (getLangOpts().ModulesTS &&
"should only have module decl in modules TS") ? void (0) : __assert_fail
("getLangOpts().ModulesTS && \"should only have module decl in modules TS\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 16464, __extension__ __PRETTY_FUNCTION__))
;
16465
16466 // A module implementation unit requires that we are not compiling a module
16467 // of any kind. A module interface unit requires that we are not compiling a
16468 // module map.
16469 switch (getLangOpts().getCompilingModule()) {
16470 case LangOptions::CMK_None:
16471 // It's OK to compile a module interface as a normal translation unit.
16472 break;
16473
16474 case LangOptions::CMK_ModuleInterface:
16475 if (MDK != ModuleDeclKind::Implementation)
16476 break;
16477
16478 // We were asked to compile a module interface unit but this is a module
16479 // implementation unit. That indicates the 'export' is missing.
16480 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
16481 << FixItHint::CreateInsertion(ModuleLoc, "export ");
16482 MDK = ModuleDeclKind::Interface;
16483 break;
16484
16485 case LangOptions::CMK_ModuleMap:
16486 Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
16487 return nullptr;
16488 }
16489
16490 assert(ModuleScopes.size() == 1 && "expected to be at global module scope")(static_cast <bool> (ModuleScopes.size() == 1 &&
"expected to be at global module scope") ? void (0) : __assert_fail
("ModuleScopes.size() == 1 && \"expected to be at global module scope\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 16490, __extension__ __PRETTY_FUNCTION__))
;
16491
16492 // FIXME: Most of this work should be done by the preprocessor rather than
16493 // here, in order to support macro import.
16494
16495 // Only one module-declaration is permitted per source file.
16496 if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) {
16497 Diag(ModuleLoc, diag::err_module_redeclaration);
16498 Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
16499 diag::note_prev_module_declaration);
16500 return nullptr;
16501 }
16502
16503 // Flatten the dots in a module name. Unlike Clang's hierarchical module map
16504 // modules, the dots here are just another character that can appear in a
16505 // module name.
16506 std::string ModuleName;
16507 for (auto &Piece : Path) {
16508 if (!ModuleName.empty())
16509 ModuleName += ".";
16510 ModuleName += Piece.first->getName();
16511 }
16512
16513 // If a module name was explicitly specified on the command line, it must be
16514 // correct.
16515 if (!getLangOpts().CurrentModule.empty() &&
16516 getLangOpts().CurrentModule != ModuleName) {
16517 Diag(Path.front().second, diag::err_current_module_name_mismatch)
16518 << SourceRange(Path.front().second, Path.back().second)
16519 << getLangOpts().CurrentModule;
16520 return nullptr;
16521 }
16522 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
16523
16524 auto &Map = PP.getHeaderSearchInfo().getModuleMap();
16525 Module *Mod;
16526
16527 switch (MDK) {
16528 case ModuleDeclKind::Interface: {
16529 // We can't have parsed or imported a definition of this module or parsed a
16530 // module map defining it already.
16531 if (auto *M = Map.findModule(ModuleName)) {
16532 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
16533 if (M->DefinitionLoc.isValid())
16534 Diag(M->DefinitionLoc, diag::note_prev_module_definition);
16535 else if (const auto *FE = M->getASTFile())
16536 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
16537 << FE->getName();
16538 Mod = M;
16539 break;
16540 }
16541
16542 // Create a Module for the module that we're defining.
16543 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16544 ModuleScopes.front().Module);
16545 assert(Mod && "module creation should not fail")(static_cast <bool> (Mod && "module creation should not fail"
) ? void (0) : __assert_fail ("Mod && \"module creation should not fail\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 16545, __extension__ __PRETTY_FUNCTION__))
;
16546 break;
16547 }
16548
16549 case ModuleDeclKind::Partition:
16550 // FIXME: Check we are in a submodule of the named module.
16551 return nullptr;
16552
16553 case ModuleDeclKind::Implementation:
16554 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
16555 PP.getIdentifierInfo(ModuleName), Path[0].second);
16556 Mod = getModuleLoader().loadModule(ModuleLoc, Path, Module::AllVisible,
16557 /*IsIncludeDirective=*/false);
16558 if (!Mod) {
16559 Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
16560 // Create an empty module interface unit for error recovery.
16561 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
16562 ModuleScopes.front().Module);
16563 }
16564 break;
16565 }
16566
16567 // Switch from the global module to the named module.
16568 ModuleScopes.back().Module = Mod;
16569 ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
16570 VisibleModules.setVisible(Mod, ModuleLoc);
16571
16572 // From now on, we have an owning module for all declarations we see.
16573 // However, those declarations are module-private unless explicitly
16574 // exported.
16575 auto *TU = Context.getTranslationUnitDecl();
16576 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
16577 TU->setLocalOwningModule(Mod);
16578
16579 // FIXME: Create a ModuleDecl.
16580 return nullptr;
16581}
16582
16583DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
16584 SourceLocation ImportLoc,
16585 ModuleIdPath Path) {
16586 Module *Mod =
16587 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
16588 /*IsIncludeDirective=*/false);
16589 if (!Mod)
16590 return true;
16591
16592 VisibleModules.setVisible(Mod, ImportLoc);
16593
16594 checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
16595
16596 // FIXME: we should support importing a submodule within a different submodule
16597 // of the same top-level module. Until we do, make it an error rather than
16598 // silently ignoring the import.
16599 // Import-from-implementation is valid in the Modules TS. FIXME: Should we
16600 // warn on a redundant import of the current module?
16601 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
16602 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
16603 Diag(ImportLoc, getLangOpts().isCompilingModule()
16604 ? diag::err_module_self_import
16605 : diag::err_module_import_in_implementation)
16606 << Mod->getFullModuleName() << getLangOpts().CurrentModule;
16607
16608 SmallVector<SourceLocation, 2> IdentifierLocs;
16609 Module *ModCheck = Mod;
16610 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
16611 // If we've run out of module parents, just drop the remaining identifiers.
16612 // We need the length to be consistent.
16613 if (!ModCheck)
16614 break;
16615 ModCheck = ModCheck->Parent;
16616
16617 IdentifierLocs.push_back(Path[I].second);
16618 }
16619
16620 ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
16621 Mod, IdentifierLocs);
16622 if (!ModuleScopes.empty())
16623 Context.addModuleInitializer(ModuleScopes.back().Module, Import);
16624 CurContext->addDecl(Import);
16625
16626 // Re-export the module if needed.
16627 if (Import->isExported() &&
16628 !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface)
16629 getCurrentModule()->Exports.emplace_back(Mod, false);
16630
16631 return Import;
16632}
16633
16634void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16635 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16636 BuildModuleInclude(DirectiveLoc, Mod);
16637}
16638
16639void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
16640 // Determine whether we're in the #include buffer for a module. The #includes
16641 // in that buffer do not qualify as module imports; they're just an
16642 // implementation detail of us building the module.
16643 //
16644 // FIXME: Should we even get ActOnModuleInclude calls for those?
16645 bool IsInModuleIncludes =
16646 TUKind == TU_Module &&
16647 getSourceManager().isWrittenInMainFile(DirectiveLoc);
16648
16649 bool ShouldAddImport = !IsInModuleIncludes;
16650
16651 // If this module import was due to an inclusion directive, create an
16652 // implicit import declaration to capture it in the AST.
16653 if (ShouldAddImport) {
16654 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16655 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16656 DirectiveLoc, Mod,
16657 DirectiveLoc);
16658 if (!ModuleScopes.empty())
16659 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
16660 TU->addDecl(ImportD);
16661 Consumer.HandleImplicitImportDecl(ImportD);
16662 }
16663
16664 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
16665 VisibleModules.setVisible(Mod, DirectiveLoc);
16666}
16667
16668void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
16669 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
16670
16671 ModuleScopes.push_back({});
16672 ModuleScopes.back().Module = Mod;
16673 if (getLangOpts().ModulesLocalVisibility)
16674 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
16675
16676 VisibleModules.setVisible(Mod, DirectiveLoc);
16677
16678 // The enclosing context is now part of this module.
16679 // FIXME: Consider creating a child DeclContext to hold the entities
16680 // lexically within the module.
16681 if (getLangOpts().trackLocalOwningModule()) {
16682 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16683 cast<Decl>(DC)->setModuleOwnershipKind(
16684 getLangOpts().ModulesLocalVisibility
16685 ? Decl::ModuleOwnershipKind::VisibleWhenImported
16686 : Decl::ModuleOwnershipKind::Visible);
16687 cast<Decl>(DC)->setLocalOwningModule(Mod);
16688 }
16689 }
16690}
16691
16692void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
16693 if (getLangOpts().ModulesLocalVisibility) {
16694 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
16695 // Leaving a module hides namespace names, so our visible namespace cache
16696 // is now out of date.
16697 VisibleNamespaceCache.clear();
16698 }
16699
16700 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&(static_cast <bool> (!ModuleScopes.empty() && ModuleScopes
.back().Module == Mod && "left the wrong module scope"
) ? void (0) : __assert_fail ("!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && \"left the wrong module scope\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 16701, __extension__ __PRETTY_FUNCTION__))
16701 "left the wrong module scope")(static_cast <bool> (!ModuleScopes.empty() && ModuleScopes
.back().Module == Mod && "left the wrong module scope"
) ? void (0) : __assert_fail ("!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && \"left the wrong module scope\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 16701, __extension__ __PRETTY_FUNCTION__))
;
16702 ModuleScopes.pop_back();
16703
16704 // We got to the end of processing a local module. Create an
16705 // ImportDecl as we would for an imported module.
16706 FileID File = getSourceManager().getFileID(EomLoc);
16707 SourceLocation DirectiveLoc;
16708 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
16709 // We reached the end of a #included module header. Use the #include loc.
16710 assert(File != getSourceManager().getMainFileID() &&(static_cast <bool> (File != getSourceManager().getMainFileID
() && "end of submodule in main source file") ? void (
0) : __assert_fail ("File != getSourceManager().getMainFileID() && \"end of submodule in main source file\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 16711, __extension__ __PRETTY_FUNCTION__))
16711 "end of submodule in main source file")(static_cast <bool> (File != getSourceManager().getMainFileID
() && "end of submodule in main source file") ? void (
0) : __assert_fail ("File != getSourceManager().getMainFileID() && \"end of submodule in main source file\""
, "/build/llvm-toolchain-snapshot-7~svn329677/tools/clang/lib/Sema/SemaDecl.cpp"
, 16711, __extension__ __PRETTY_FUNCTION__))
;
16712 DirectiveLoc = getSourceManager().getIncludeLoc(File);
16713 } else {
16714 // We reached an EOM pragma. Use the pragma location.
16715 DirectiveLoc = EomLoc;
16716 }
16717 BuildModuleInclude(DirectiveLoc, Mod);
16718
16719 // Any further declarations are in whatever module we returned to.
16720 if (getLangOpts().trackLocalOwningModule()) {
16721 // The parser guarantees that this is the same context that we entered
16722 // the module within.
16723 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
16724 cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
16725 if (!getCurrentModule())
16726 cast<Decl>(DC)->setModuleOwnershipKind(
16727 Decl::ModuleOwnershipKind::Unowned);
16728 }
16729 }
16730}
16731
16732void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
16733 Module *Mod) {
16734 // Bail if we're not allowed to implicitly import a module here.
16735 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
16736 VisibleModules.isVisible(Mod))
16737 return;
16738
16739 // Create the implicit import declaration.
16740 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
16741 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
16742 Loc, Mod, Loc);
16743 TU->addDecl(ImportD);
16744 Consumer.HandleImplicitImportDecl(ImportD);
16745
16746 // Make the module visible.
16747 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
16748 VisibleModules.setVisible(Mod, Loc);
16749}
16750
16751/// We have parsed the start of an export declaration, including the '{'
16752/// (if present).
16753Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
16754 SourceLocation LBraceLoc) {
16755 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
16756
16757 // C++ Modules TS draft:
16758 // An export-declaration shall appear in the purview of a module other than
16759 // the global module.
16760 if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface)
16761 Diag(ExportLoc, diag::err_export_not_in_module_interface);
16762
16763 // An export-declaration [...] shall not contain more than one
16764 // export keyword.
16765 //
16766 // The intent here is that an export-declaration cannot appear within another
16767 // export-declaration.
16768 if (D->isExported())
16769 Diag(ExportLoc, diag::err_export_within_export);
16770
16771 CurContext->addDecl(D);
16772 PushDeclContext(S, D);
16773 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
16774 return D;
16775}
16776
16777/// Complete the definition of an export declaration.
16778Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
16779 auto *ED = cast<ExportDecl>(D);
16780 if (RBraceLoc.isValid())
16781 ED->setRBraceLoc(RBraceLoc);
16782
16783 // FIXME: Diagnose export of internal-linkage declaration (including
16784 // anonymous namespace).
16785
16786 PopDeclContext();
16787 return D;
16788}
16789
16790void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
16791 IdentifierInfo* AliasName,
16792 SourceLocation PragmaLoc,
16793 SourceLocation NameLoc,
16794 SourceLocation AliasNameLoc) {
16795 NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
16796 LookupOrdinaryName);
16797 AsmLabelAttr *Attr =
16798 AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
16799
16800 // If a declaration that:
16801 // 1) declares a function or a variable
16802 // 2) has external linkage
16803 // already exists, add a label attribute to it.
16804 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16805 if (isDeclExternC(PrevDecl))
16806 PrevDecl->addAttr(Attr);
16807 else
16808 Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
16809 << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
16810 // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
16811 } else
16812 (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
16813}
16814
16815void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
16816 SourceLocation PragmaLoc,
16817 SourceLocation NameLoc) {
16818 Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
16819
16820 if (PrevDecl) {
16821 PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
16822 } else {
16823 (void)WeakUndeclaredIdentifiers.insert(
16824 std::pair<IdentifierInfo*,WeakInfo>
16825 (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
16826 }
16827}
16828
16829void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
16830 IdentifierInfo* AliasName,
16831 SourceLocation PragmaLoc,
16832 SourceLocation NameLoc,
16833 SourceLocation AliasNameLoc) {
16834 Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
16835 LookupOrdinaryName);
16836 WeakInfo W = WeakInfo(Name, NameLoc);
16837
16838 if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
16839 if (!PrevDecl->hasAttr<AliasAttr>())
16840 if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
16841 DeclApplyPragmaWeak(TUScope, ND, W);
16842 } else {
16843 (void)WeakUndeclaredIdentifiers.insert(
16844 std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
16845 }
16846}
16847
16848Decl *Sema::getObjCDeclContext() const {
16849 return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
16850}

/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc

1/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\
2|* *|
3|* Attribute classes' definitions *|
4|* *|
5|* Automatically generated file, do not edit! *|
6|* *|
7\*===----------------------------------------------------------------------===*/
8
9#ifndef LLVM_CLANG_ATTR_CLASSES_INC
10#define LLVM_CLANG_ATTR_CLASSES_INC
11
12class AMDGPUFlatWorkGroupSizeAttr : public InheritableAttr {
13unsigned min;
14
15unsigned max;
16
17public:
18 static AMDGPUFlatWorkGroupSizeAttr *CreateImplicit(ASTContext &Ctx, unsigned Min, unsigned Max, SourceRange Loc = SourceRange()) {
19 auto *A = new (Ctx) AMDGPUFlatWorkGroupSizeAttr(Loc, Ctx, Min, Max, 0);
20 A->setImplicit(true);
21 return A;
22 }
23
24 AMDGPUFlatWorkGroupSizeAttr(SourceRange R, ASTContext &Ctx
25 , unsigned Min
26 , unsigned Max
27 , unsigned SI
28 )
29 : InheritableAttr(attr::AMDGPUFlatWorkGroupSize, R, SI, false, false)
30 , min(Min)
31 , max(Max)
32 {
33 }
34
35 AMDGPUFlatWorkGroupSizeAttr *clone(ASTContext &C) const;
36 void printPretty(raw_ostream &OS,
37 const PrintingPolicy &Policy) const;
38 const char *getSpelling() const;
39 unsigned getMin() const {
40 return min;
41 }
42
43 unsigned getMax() const {
44 return max;
45 }
46
47
48
49 static bool classof(const Attr *A) { return A->getKind() == attr::AMDGPUFlatWorkGroupSize; }
50};
51
52class AMDGPUNumSGPRAttr : public InheritableAttr {
53unsigned numSGPR;
54
55public:
56 static AMDGPUNumSGPRAttr *CreateImplicit(ASTContext &Ctx, unsigned NumSGPR, SourceRange Loc = SourceRange()) {
57 auto *A = new (Ctx) AMDGPUNumSGPRAttr(Loc, Ctx, NumSGPR, 0);
58 A->setImplicit(true);
59 return A;
60 }
61
62 AMDGPUNumSGPRAttr(SourceRange R, ASTContext &Ctx
63 , unsigned NumSGPR
64 , unsigned SI
65 )
66 : InheritableAttr(attr::AMDGPUNumSGPR, R, SI, false, false)
67 , numSGPR(NumSGPR)
68 {
69 }
70
71 AMDGPUNumSGPRAttr *clone(ASTContext &C) const;
72 void printPretty(raw_ostream &OS,
73 const PrintingPolicy &Policy) const;
74 const char *getSpelling() const;
75 unsigned getNumSGPR() const {
76 return numSGPR;
77 }
78
79
80
81 static bool classof(const Attr *A) { return A->getKind() == attr::AMDGPUNumSGPR; }
82};
83
84class AMDGPUNumVGPRAttr : public InheritableAttr {
85unsigned numVGPR;
86
87public:
88 static AMDGPUNumVGPRAttr *CreateImplicit(ASTContext &Ctx, unsigned NumVGPR, SourceRange Loc = SourceRange()) {
89 auto *A = new (Ctx) AMDGPUNumVGPRAttr(Loc, Ctx, NumVGPR, 0);
90 A->setImplicit(true);
91 return A;
92 }
93
94 AMDGPUNumVGPRAttr(SourceRange R, ASTContext &Ctx
95 , unsigned NumVGPR
96 , unsigned SI
97 )
98 : InheritableAttr(attr::AMDGPUNumVGPR, R, SI, false, false)
99 , numVGPR(NumVGPR)
100 {
101 }
102
103 AMDGPUNumVGPRAttr *clone(ASTContext &C) const;
104 void printPretty(raw_ostream &OS,
105 const PrintingPolicy &Policy) const;
106 const char *getSpelling() const;
107 unsigned getNumVGPR() const {
108 return numVGPR;
109 }
110
111
112
113 static bool classof(const Attr *A) { return A->getKind() == attr::AMDGPUNumVGPR; }
114};
115
116class AMDGPUWavesPerEUAttr : public InheritableAttr {
117unsigned min;
118
119unsigned max;
120
121public:
122 static AMDGPUWavesPerEUAttr *CreateImplicit(ASTContext &Ctx, unsigned Min, unsigned Max, SourceRange Loc = SourceRange()) {
123 auto *A = new (Ctx) AMDGPUWavesPerEUAttr(Loc, Ctx, Min, Max, 0);
124 A->setImplicit(true);
125 return A;
126 }
127
128 AMDGPUWavesPerEUAttr(SourceRange R, ASTContext &Ctx
129 , unsigned Min
130 , unsigned Max
131 , unsigned SI
132 )
133 : InheritableAttr(attr::AMDGPUWavesPerEU, R, SI, false, false)
134 , min(Min)
135 , max(Max)
136 {
137 }
138
139 AMDGPUWavesPerEUAttr(SourceRange R, ASTContext &Ctx
140 , unsigned Min
141 , unsigned SI
142 )
143 : InheritableAttr(attr::AMDGPUWavesPerEU, R, SI, false, false)
144 , min(Min)
145 , max()
146 {
147 }
148
149 AMDGPUWavesPerEUAttr *clone(ASTContext &C) const;
150 void printPretty(raw_ostream &OS,
151 const PrintingPolicy &Policy) const;
152 const char *getSpelling() const;
153 unsigned getMin() const {
154 return min;
155 }
156
157 unsigned getMax() const {
158 return max;
159 }
160
161
162
163 static bool classof(const Attr *A) { return A->getKind() == attr::AMDGPUWavesPerEU; }
164};
165
166class ARMInterruptAttr : public InheritableAttr {
167public:
168 enum InterruptType {
169 IRQ,
170 FIQ,
171 SWI,
172 ABORT,
173 UNDEF,
174 Generic
175 };
176private:
177 InterruptType interrupt;
178
179public:
180 static ARMInterruptAttr *CreateImplicit(ASTContext &Ctx, InterruptType Interrupt, SourceRange Loc = SourceRange()) {
181 auto *A = new (Ctx) ARMInterruptAttr(Loc, Ctx, Interrupt, 0);
182 A->setImplicit(true);
183 return A;
184 }
185
186 ARMInterruptAttr(SourceRange R, ASTContext &Ctx
187 , InterruptType Interrupt
188 , unsigned SI
189 )
190 : InheritableAttr(attr::ARMInterrupt, R, SI, false, false)
191 , interrupt(Interrupt)
192 {
193 }
194
195 ARMInterruptAttr(SourceRange R, ASTContext &Ctx
196 , unsigned SI
197 )
198 : InheritableAttr(attr::ARMInterrupt, R, SI, false, false)
199 , interrupt(InterruptType(0))
200 {
201 }
202
203 ARMInterruptAttr *clone(ASTContext &C) const;
204 void printPretty(raw_ostream &OS,
205 const PrintingPolicy &Policy) const;
206 const char *getSpelling() const;
207 InterruptType getInterrupt() const {
208 return interrupt;
209 }
210
211 static bool ConvertStrToInterruptType(StringRef Val, InterruptType &Out) {
212 Optional<InterruptType> R = llvm::StringSwitch<Optional<InterruptType>>(Val)
213 .Case("IRQ", ARMInterruptAttr::IRQ)
214 .Case("FIQ", ARMInterruptAttr::FIQ)
215 .Case("SWI", ARMInterruptAttr::SWI)
216 .Case("ABORT", ARMInterruptAttr::ABORT)
217 .Case("UNDEF", ARMInterruptAttr::UNDEF)
218 .Case("", ARMInterruptAttr::Generic)
219 .Default(Optional<InterruptType>());
220 if (R) {
221 Out = *R;
222 return true;
223 }
224 return false;
225 }
226
227 static const char *ConvertInterruptTypeToStr(InterruptType Val) {
228 switch(Val) {
229 case ARMInterruptAttr::IRQ: return "IRQ";
230 case ARMInterruptAttr::FIQ: return "FIQ";
231 case ARMInterruptAttr::SWI: return "SWI";
232 case ARMInterruptAttr::ABORT: return "ABORT";
233 case ARMInterruptAttr::UNDEF: return "UNDEF";
234 case ARMInterruptAttr::Generic: return "";
235 }
236 llvm_unreachable("No enumerator with that value")::llvm::llvm_unreachable_internal("No enumerator with that value"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 236)
;
237 }
238
239
240 static bool classof(const Attr *A) { return A->getKind() == attr::ARMInterrupt; }
241};
242
243class AVRInterruptAttr : public InheritableAttr {
244public:
245 static AVRInterruptAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
246 auto *A = new (Ctx) AVRInterruptAttr(Loc, Ctx, 0);
247 A->setImplicit(true);
248 return A;
249 }
250
251 AVRInterruptAttr(SourceRange R, ASTContext &Ctx
252 , unsigned SI
253 )
254 : InheritableAttr(attr::AVRInterrupt, R, SI, false, false)
255 {
256 }
257
258 AVRInterruptAttr *clone(ASTContext &C) const;
259 void printPretty(raw_ostream &OS,
260 const PrintingPolicy &Policy) const;
261 const char *getSpelling() const;
262
263
264 static bool classof(const Attr *A) { return A->getKind() == attr::AVRInterrupt; }
265};
266
267class AVRSignalAttr : public InheritableAttr {
268public:
269 static AVRSignalAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
270 auto *A = new (Ctx) AVRSignalAttr(Loc, Ctx, 0);
271 A->setImplicit(true);
272 return A;
273 }
274
275 AVRSignalAttr(SourceRange R, ASTContext &Ctx
276 , unsigned SI
277 )
278 : InheritableAttr(attr::AVRSignal, R, SI, false, false)
279 {
280 }
281
282 AVRSignalAttr *clone(ASTContext &C) const;
283 void printPretty(raw_ostream &OS,
284 const PrintingPolicy &Policy) const;
285 const char *getSpelling() const;
286
287
288 static bool classof(const Attr *A) { return A->getKind() == attr::AVRSignal; }
289};
290
291class AbiTagAttr : public Attr {
292 unsigned tags_Size;
293 StringRef *tags_;
294
295public:
296 static AbiTagAttr *CreateImplicit(ASTContext &Ctx, StringRef *Tags, unsigned TagsSize, SourceRange Loc = SourceRange()) {
297 auto *A = new (Ctx) AbiTagAttr(Loc, Ctx, Tags, TagsSize, 0);
298 A->setImplicit(true);
299 return A;
300 }
301
302 AbiTagAttr(SourceRange R, ASTContext &Ctx
303 , StringRef *Tags, unsigned TagsSize
304 , unsigned SI
305 )
306 : Attr(attr::AbiTag, R, SI, false)
307 , tags_Size(TagsSize), tags_(new (Ctx, 16) StringRef[tags_Size])
308 {
309 for (size_t I = 0, E = tags_Size; I != E;
310 ++I) {
311 StringRef Ref = Tags[I];
312 if (!Ref.empty()) {
313 char *Mem = new (Ctx, 1) char[Ref.size()];
314 std::memcpy(Mem, Ref.data(), Ref.size());
315 tags_[I] = StringRef(Mem, Ref.size());
316 }
317 }
318 }
319
320 AbiTagAttr(SourceRange R, ASTContext &Ctx
321 , unsigned SI
322 )
323 : Attr(attr::AbiTag, R, SI, false)
324 , tags_Size(0), tags_(nullptr)
325 {
326 }
327
328 AbiTagAttr *clone(ASTContext &C) const;
329 void printPretty(raw_ostream &OS,
330 const PrintingPolicy &Policy) const;
331 const char *getSpelling() const;
332 typedef StringRef* tags_iterator;
333 tags_iterator tags_begin() const { return tags_; }
334 tags_iterator tags_end() const { return tags_ + tags_Size; }
335 unsigned tags_size() const { return tags_Size; }
336 llvm::iterator_range<tags_iterator> tags() const { return llvm::make_range(tags_begin(), tags_end()); }
337
338
339
340
341 static bool classof(const Attr *A) { return A->getKind() == attr::AbiTag; }
342};
343
344class AcquireCapabilityAttr : public InheritableAttr {
345 unsigned args_Size;
346 Expr * *args_;
347
348public:
349 enum Spelling {
350 GNU_acquire_capability = 0,
351 CXX11_clang_acquire_capability = 1,
352 GNU_acquire_shared_capability = 2,
353 CXX11_clang_acquire_shared_capability = 3,
354 GNU_exclusive_lock_function = 4,
355 GNU_shared_lock_function = 5
356 };
357
358 static AcquireCapabilityAttr *CreateImplicit(ASTContext &Ctx, Spelling S, Expr * *Args, unsigned ArgsSize, SourceRange Loc = SourceRange()) {
359 auto *A = new (Ctx) AcquireCapabilityAttr(Loc, Ctx, Args, ArgsSize, S);
360 A->setImplicit(true);
361 return A;
362 }
363
364 AcquireCapabilityAttr(SourceRange R, ASTContext &Ctx
365 , Expr * *Args, unsigned ArgsSize
366 , unsigned SI
367 )
368 : InheritableAttr(attr::AcquireCapability, R, SI, true, true)
369 , args_Size(ArgsSize), args_(new (Ctx, 16) Expr *[args_Size])
370 {
371 std::copy(Args, Args + args_Size, args_);
372 }
373
374 AcquireCapabilityAttr(SourceRange R, ASTContext &Ctx
375 , unsigned SI
376 )
377 : InheritableAttr(attr::AcquireCapability, R, SI, true, true)
378 , args_Size(0), args_(nullptr)
379 {
380 }
381
382 AcquireCapabilityAttr *clone(ASTContext &C) const;
383 void printPretty(raw_ostream &OS,
384 const PrintingPolicy &Policy) const;
385 const char *getSpelling() const;
386 Spelling getSemanticSpelling() const {
387 switch (SpellingListIndex) {
388 default: llvm_unreachable("Unknown spelling list index")::llvm::llvm_unreachable_internal("Unknown spelling list index"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 388)
;
389 case 0: return GNU_acquire_capability;
390 case 1: return CXX11_clang_acquire_capability;
391 case 2: return GNU_acquire_shared_capability;
392 case 3: return CXX11_clang_acquire_shared_capability;
393 case 4: return GNU_exclusive_lock_function;
394 case 5: return GNU_shared_lock_function;
395 }
396 }
397 bool isShared() const { return SpellingListIndex == 2 ||
398 SpellingListIndex == 3 ||
399 SpellingListIndex == 5; }
400 typedef Expr ** args_iterator;
401 args_iterator args_begin() const { return args_; }
402 args_iterator args_end() const { return args_ + args_Size; }
403 unsigned args_size() const { return args_Size; }
404 llvm::iterator_range<args_iterator> args() const { return llvm::make_range(args_begin(), args_end()); }
405
406
407
408
409 static bool classof(const Attr *A) { return A->getKind() == attr::AcquireCapability; }
410};
411
412class AcquiredAfterAttr : public InheritableAttr {
413 unsigned args_Size;
414 Expr * *args_;
415
416public:
417 static AcquiredAfterAttr *CreateImplicit(ASTContext &Ctx, Expr * *Args, unsigned ArgsSize, SourceRange Loc = SourceRange()) {
418 auto *A = new (Ctx) AcquiredAfterAttr(Loc, Ctx, Args, ArgsSize, 0);
419 A->setImplicit(true);
420 return A;
421 }
422
423 AcquiredAfterAttr(SourceRange R, ASTContext &Ctx
424 , Expr * *Args, unsigned ArgsSize
425 , unsigned SI
426 )
427 : InheritableAttr(attr::AcquiredAfter, R, SI, true, true)
428 , args_Size(ArgsSize), args_(new (Ctx, 16) Expr *[args_Size])
429 {
430 std::copy(Args, Args + args_Size, args_);
431 }
432
433 AcquiredAfterAttr(SourceRange R, ASTContext &Ctx
434 , unsigned SI
435 )
436 : InheritableAttr(attr::AcquiredAfter, R, SI, true, true)
437 , args_Size(0), args_(nullptr)
438 {
439 }
440
441 AcquiredAfterAttr *clone(ASTContext &C) const;
442 void printPretty(raw_ostream &OS,
443 const PrintingPolicy &Policy) const;
444 const char *getSpelling() const;
445 typedef Expr ** args_iterator;
446 args_iterator args_begin() const { return args_; }
447 args_iterator args_end() const { return args_ + args_Size; }
448 unsigned args_size() const { return args_Size; }
449 llvm::iterator_range<args_iterator> args() const { return llvm::make_range(args_begin(), args_end()); }
450
451
452
453
454 static bool classof(const Attr *A) { return A->getKind() == attr::AcquiredAfter; }
455};
456
457class AcquiredBeforeAttr : public InheritableAttr {
458 unsigned args_Size;
459 Expr * *args_;
460
461public:
462 static AcquiredBeforeAttr *CreateImplicit(ASTContext &Ctx, Expr * *Args, unsigned ArgsSize, SourceRange Loc = SourceRange()) {
463 auto *A = new (Ctx) AcquiredBeforeAttr(Loc, Ctx, Args, ArgsSize, 0);
464 A->setImplicit(true);
465 return A;
466 }
467
468 AcquiredBeforeAttr(SourceRange R, ASTContext &Ctx
469 , Expr * *Args, unsigned ArgsSize
470 , unsigned SI
471 )
472 : InheritableAttr(attr::AcquiredBefore, R, SI, true, true)
473 , args_Size(ArgsSize), args_(new (Ctx, 16) Expr *[args_Size])
474 {
475 std::copy(Args, Args + args_Size, args_);
476 }
477
478 AcquiredBeforeAttr(SourceRange R, ASTContext &Ctx
479 , unsigned SI
480 )
481 : InheritableAttr(attr::AcquiredBefore, R, SI, true, true)
482 , args_Size(0), args_(nullptr)
483 {
484 }
485
486 AcquiredBeforeAttr *clone(ASTContext &C) const;
487 void printPretty(raw_ostream &OS,
488 const PrintingPolicy &Policy) const;
489 const char *getSpelling() const;
490 typedef Expr ** args_iterator;
491 args_iterator args_begin() const { return args_; }
492 args_iterator args_end() const { return args_ + args_Size; }
493 unsigned args_size() const { return args_Size; }
494 llvm::iterator_range<args_iterator> args() const { return llvm::make_range(args_begin(), args_end()); }
495
496
497
498
499 static bool classof(const Attr *A) { return A->getKind() == attr::AcquiredBefore; }
500};
501
502class AliasAttr : public Attr {
503unsigned aliaseeLength;
504char *aliasee;
505
506public:
507 static AliasAttr *CreateImplicit(ASTContext &Ctx, llvm::StringRef Aliasee, SourceRange Loc = SourceRange()) {
508 auto *A = new (Ctx) AliasAttr(Loc, Ctx, Aliasee, 0);
509 A->setImplicit(true);
510 return A;
511 }
512
513 AliasAttr(SourceRange R, ASTContext &Ctx
514 , llvm::StringRef Aliasee
515 , unsigned SI
516 )
517 : Attr(attr::Alias, R, SI, false)
518 , aliaseeLength(Aliasee.size()),aliasee(new (Ctx, 1) char[aliaseeLength])
519 {
520 if (!Aliasee.empty())
521 std::memcpy(aliasee, Aliasee.data(), aliaseeLength);
522 }
523
524 AliasAttr *clone(ASTContext &C) const;
525 void printPretty(raw_ostream &OS,
526 const PrintingPolicy &Policy) const;
527 const char *getSpelling() const;
528 llvm::StringRef getAliasee() const {
529 return llvm::StringRef(aliasee, aliaseeLength);
530 }
531 unsigned getAliaseeLength() const {
532 return aliaseeLength;
533 }
534 void setAliasee(ASTContext &C, llvm::StringRef S) {
535 aliaseeLength = S.size();
536 this->aliasee = new (C, 1) char [aliaseeLength];
537 if (!S.empty())
538 std::memcpy(this->aliasee, S.data(), aliaseeLength);
539 }
540
541
542
543 static bool classof(const Attr *A) { return A->getKind() == attr::Alias; }
544};
545
546class AlignMac68kAttr : public InheritableAttr {
547public:
548 static AlignMac68kAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
549 auto *A = new (Ctx) AlignMac68kAttr(Loc, Ctx, 0);
550 A->setImplicit(true);
551 return A;
552 }
553
554 AlignMac68kAttr(SourceRange R, ASTContext &Ctx
555 , unsigned SI
556 )
557 : InheritableAttr(attr::AlignMac68k, R, SI, false, false)
558 {
559 }
560
561 AlignMac68kAttr *clone(ASTContext &C) const;
562 void printPretty(raw_ostream &OS,
563 const PrintingPolicy &Policy) const;
564 const char *getSpelling() const;
565
566
567 static bool classof(const Attr *A) { return A->getKind() == attr::AlignMac68k; }
568};
569
570class AlignValueAttr : public Attr {
571Expr * alignment;
572
573public:
574 static AlignValueAttr *CreateImplicit(ASTContext &Ctx, Expr * Alignment, SourceRange Loc = SourceRange()) {
575 auto *A = new (Ctx) AlignValueAttr(Loc, Ctx, Alignment, 0);
576 A->setImplicit(true);
577 return A;
578 }
579
580 AlignValueAttr(SourceRange R, ASTContext &Ctx
581 , Expr * Alignment
582 , unsigned SI
583 )
584 : Attr(attr::AlignValue, R, SI, false)
585 , alignment(Alignment)
586 {
587 }
588
589 AlignValueAttr *clone(ASTContext &C) const;
590 void printPretty(raw_ostream &OS,
591 const PrintingPolicy &Policy) const;
592 const char *getSpelling() const;
593 Expr * getAlignment() const {
594 return alignment;
595 }
596
597
598
599 static bool classof(const Attr *A) { return A->getKind() == attr::AlignValue; }
600};
601
602class AlignedAttr : public InheritableAttr {
603bool isalignmentExpr;
604union {
605Expr *alignmentExpr;
606TypeSourceInfo *alignmentType;
607};
608
609public:
610 enum Spelling {
611 GNU_aligned = 0,
612 CXX11_gnu_aligned = 1,
613 Declspec_align = 2,
614 Keyword_alignas = 3,
615 Keyword_Alignas = 4
616 };
617
618 static AlignedAttr *CreateImplicit(ASTContext &Ctx, Spelling S, bool IsAlignmentExpr, void *Alignment, SourceRange Loc = SourceRange()) {
619 auto *A = new (Ctx) AlignedAttr(Loc, Ctx, IsAlignmentExpr, Alignment, S);
620 A->setImplicit(true);
621 return A;
622 }
623
624 AlignedAttr(SourceRange R, ASTContext &Ctx
625 , bool IsAlignmentExpr, void *Alignment
626 , unsigned SI
627 )
628 : InheritableAttr(attr::Aligned, R, SI, false, false)
629 , isalignmentExpr(IsAlignmentExpr)
630 {
631 if (isalignmentExpr)
632 alignmentExpr = reinterpret_cast<Expr *>(Alignment);
633 else
634 alignmentType = reinterpret_cast<TypeSourceInfo *>(Alignment);
635 }
636
637 AlignedAttr(SourceRange R, ASTContext &Ctx
638 , unsigned SI
639 )
640 : InheritableAttr(attr::Aligned, R, SI, false, false)
641 , isalignmentExpr(false)
642 {
643 }
644
645 AlignedAttr *clone(ASTContext &C) const;
646 void printPretty(raw_ostream &OS,
647 const PrintingPolicy &Policy) const;
648 const char *getSpelling() const;
649 Spelling getSemanticSpelling() const {
650 switch (SpellingListIndex) {
651 default: llvm_unreachable("Unknown spelling list index")::llvm::llvm_unreachable_internal("Unknown spelling list index"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 651)
;
652 case 0: return GNU_aligned;
653 case 1: return CXX11_gnu_aligned;
654 case 2: return Declspec_align;
655 case 3: return Keyword_alignas;
656 case 4: return Keyword_Alignas;
657 }
658 }
659 bool isGNU() const { return SpellingListIndex == 0 ||
660 SpellingListIndex == 1; }
661 bool isC11() const { return SpellingListIndex == 4; }
662 bool isAlignas() const { return SpellingListIndex == 3 ||
663 SpellingListIndex == 4; }
664 bool isDeclspec() const { return SpellingListIndex == 2; }
665 bool isAlignmentDependent() const;
666 unsigned getAlignment(ASTContext &Ctx) const;
667 bool isAlignmentExpr() const {
668 return isalignmentExpr;
669 }
670 Expr *getAlignmentExpr() const {
671 assert(isalignmentExpr)(static_cast <bool> (isalignmentExpr) ? void (0) : __assert_fail
("isalignmentExpr", "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 671, __extension__ __PRETTY_FUNCTION__))
;
672 return alignmentExpr;
673 }
674 TypeSourceInfo *getAlignmentType() const {
675 assert(!isalignmentExpr)(static_cast <bool> (!isalignmentExpr) ? void (0) : __assert_fail
("!isalignmentExpr", "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 675, __extension__ __PRETTY_FUNCTION__))
;
676 return alignmentType;
677 }
678
679
680
681 static bool classof(const Attr *A) { return A->getKind() == attr::Aligned; }
682};
683
684class AllocAlignAttr : public InheritableAttr {
685ParamIdx paramIndex;
686
687public:
688 static AllocAlignAttr *CreateImplicit(ASTContext &Ctx, ParamIdx ParamIndex, SourceRange Loc = SourceRange()) {
689 auto *A = new (Ctx) AllocAlignAttr(Loc, Ctx, ParamIndex, 0);
690 A->setImplicit(true);
691 return A;
692 }
693
694 AllocAlignAttr(SourceRange R, ASTContext &Ctx
695 , ParamIdx ParamIndex
696 , unsigned SI
697 )
698 : InheritableAttr(attr::AllocAlign, R, SI, false, false)
699 , paramIndex(ParamIndex)
700 {
701 }
702
703 AllocAlignAttr *clone(ASTContext &C) const;
704 void printPretty(raw_ostream &OS,
705 const PrintingPolicy &Policy) const;
706 const char *getSpelling() const;
707 ParamIdx getParamIndex() const {
708 return paramIndex;
709 }
710
711
712
713 static bool classof(const Attr *A) { return A->getKind() == attr::AllocAlign; }
714};
715
716class AllocSizeAttr : public InheritableAttr {
717ParamIdx elemSizeParam;
718
719ParamIdx numElemsParam;
720
721public:
722 static AllocSizeAttr *CreateImplicit(ASTContext &Ctx, ParamIdx ElemSizeParam, ParamIdx NumElemsParam, SourceRange Loc = SourceRange()) {
723 auto *A = new (Ctx) AllocSizeAttr(Loc, Ctx, ElemSizeParam, NumElemsParam, 0);
724 A->setImplicit(true);
725 return A;
726 }
727
728 AllocSizeAttr(SourceRange R, ASTContext &Ctx
729 , ParamIdx ElemSizeParam
730 , ParamIdx NumElemsParam
731 , unsigned SI
732 )
733 : InheritableAttr(attr::AllocSize, R, SI, false, false)
734 , elemSizeParam(ElemSizeParam)
735 , numElemsParam(NumElemsParam)
736 {
737 }
738
739 AllocSizeAttr(SourceRange R, ASTContext &Ctx
740 , ParamIdx ElemSizeParam
741 , unsigned SI
742 )
743 : InheritableAttr(attr::AllocSize, R, SI, false, false)
744 , elemSizeParam(ElemSizeParam)
745 , numElemsParam()
746 {
747 }
748
749 AllocSizeAttr *clone(ASTContext &C) const;
750 void printPretty(raw_ostream &OS,
751 const PrintingPolicy &Policy) const;
752 const char *getSpelling() const;
753 ParamIdx getElemSizeParam() const {
754 return elemSizeParam;
755 }
756
757 ParamIdx getNumElemsParam() const {
758 return numElemsParam;
759 }
760
761
762
763 static bool classof(const Attr *A) { return A->getKind() == attr::AllocSize; }
764};
765
766class AlwaysInlineAttr : public InheritableAttr {
767public:
768 enum Spelling {
769 GNU_always_inline = 0,
770 CXX11_gnu_always_inline = 1,
771 Keyword_forceinline = 2
772 };
773
774 static AlwaysInlineAttr *CreateImplicit(ASTContext &Ctx, Spelling S, SourceRange Loc = SourceRange()) {
775 auto *A = new (Ctx) AlwaysInlineAttr(Loc, Ctx, S);
776 A->setImplicit(true);
777 return A;
778 }
779
780 AlwaysInlineAttr(SourceRange R, ASTContext &Ctx
781 , unsigned SI
782 )
783 : InheritableAttr(attr::AlwaysInline, R, SI, false, false)
784 {
785 }
786
787 AlwaysInlineAttr *clone(ASTContext &C) const;
788 void printPretty(raw_ostream &OS,
789 const PrintingPolicy &Policy) const;
790 const char *getSpelling() const;
791 Spelling getSemanticSpelling() const {
792 switch (SpellingListIndex) {
793 default: llvm_unreachable("Unknown spelling list index")::llvm::llvm_unreachable_internal("Unknown spelling list index"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 793)
;
794 case 0: return GNU_always_inline;
795 case 1: return CXX11_gnu_always_inline;
796 case 2: return Keyword_forceinline;
797 }
798 }
799
800
801 static bool classof(const Attr *A) { return A->getKind() == attr::AlwaysInline; }
802};
803
804class AnalyzerNoReturnAttr : public InheritableAttr {
805public:
806 static AnalyzerNoReturnAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
807 auto *A = new (Ctx) AnalyzerNoReturnAttr(Loc, Ctx, 0);
808 A->setImplicit(true);
809 return A;
810 }
811
812 AnalyzerNoReturnAttr(SourceRange R, ASTContext &Ctx
813 , unsigned SI
814 )
815 : InheritableAttr(attr::AnalyzerNoReturn, R, SI, false, false)
816 {
817 }
818
819 AnalyzerNoReturnAttr *clone(ASTContext &C) const;
820 void printPretty(raw_ostream &OS,
821 const PrintingPolicy &Policy) const;
822 const char *getSpelling() const;
823
824
825 static bool classof(const Attr *A) { return A->getKind() == attr::AnalyzerNoReturn; }
826};
827
828class AnnotateAttr : public InheritableParamAttr {
829unsigned annotationLength;
830char *annotation;
831
832public:
833 static AnnotateAttr *CreateImplicit(ASTContext &Ctx, llvm::StringRef Annotation, SourceRange Loc = SourceRange()) {
834 auto *A = new (Ctx) AnnotateAttr(Loc, Ctx, Annotation, 0);
835 A->setImplicit(true);
836 return A;
837 }
838
839 AnnotateAttr(SourceRange R, ASTContext &Ctx
840 , llvm::StringRef Annotation
841 , unsigned SI
842 )
843 : InheritableParamAttr(attr::Annotate, R, SI, false, false)
844 , annotationLength(Annotation.size()),annotation(new (Ctx, 1) char[annotationLength])
845 {
846 if (!Annotation.empty())
847 std::memcpy(annotation, Annotation.data(), annotationLength);
848 }
849
850 AnnotateAttr *clone(ASTContext &C) const;
851 void printPretty(raw_ostream &OS,
852 const PrintingPolicy &Policy) const;
853 const char *getSpelling() const;
854 llvm::StringRef getAnnotation() const {
855 return llvm::StringRef(annotation, annotationLength);
856 }
857 unsigned getAnnotationLength() const {
858 return annotationLength;
859 }
860 void setAnnotation(ASTContext &C, llvm::StringRef S) {
861 annotationLength = S.size();
862 this->annotation = new (C, 1) char [annotationLength];
863 if (!S.empty())
864 std::memcpy(this->annotation, S.data(), annotationLength);
865 }
866
867
868
869 static bool classof(const Attr *A) { return A->getKind() == attr::Annotate; }
870};
871
872class AnyX86InterruptAttr : public InheritableAttr {
873public:
874 static AnyX86InterruptAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
875 auto *A = new (Ctx) AnyX86InterruptAttr(Loc, Ctx, 0);
876 A->setImplicit(true);
877 return A;
878 }
879
880 AnyX86InterruptAttr(SourceRange R, ASTContext &Ctx
881 , unsigned SI
882 )
883 : InheritableAttr(attr::AnyX86Interrupt, R, SI, false, false)
884 {
885 }
886
887 AnyX86InterruptAttr *clone(ASTContext &C) const;
888 void printPretty(raw_ostream &OS,
889 const PrintingPolicy &Policy) const;
890 const char *getSpelling() const;
891
892
893 static bool classof(const Attr *A) { return A->getKind() == attr::AnyX86Interrupt; }
894};
895
896class AnyX86NoCallerSavedRegistersAttr : public InheritableAttr {
897public:
898 static AnyX86NoCallerSavedRegistersAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
899 auto *A = new (Ctx) AnyX86NoCallerSavedRegistersAttr(Loc, Ctx, 0);
900 A->setImplicit(true);
901 return A;
902 }
903
904 AnyX86NoCallerSavedRegistersAttr(SourceRange R, ASTContext &Ctx
905 , unsigned SI
906 )
907 : InheritableAttr(attr::AnyX86NoCallerSavedRegisters, R, SI, false, false)
908 {
909 }
910
911 AnyX86NoCallerSavedRegistersAttr *clone(ASTContext &C) const;
912 void printPretty(raw_ostream &OS,
913 const PrintingPolicy &Policy) const;
914 const char *getSpelling() const;
915
916
917 static bool classof(const Attr *A) { return A->getKind() == attr::AnyX86NoCallerSavedRegisters; }
918};
919
920class AnyX86NoCfCheckAttr : public InheritableAttr {
921public:
922 static AnyX86NoCfCheckAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
923 auto *A = new (Ctx) AnyX86NoCfCheckAttr(Loc, Ctx, 0);
924 A->setImplicit(true);
925 return A;
926 }
927
928 AnyX86NoCfCheckAttr(SourceRange R, ASTContext &Ctx
929 , unsigned SI
930 )
931 : InheritableAttr(attr::AnyX86NoCfCheck, R, SI, false, false)
932 {
933 }
934
935 AnyX86NoCfCheckAttr *clone(ASTContext &C) const;
936 void printPretty(raw_ostream &OS,
937 const PrintingPolicy &Policy) const;
938 const char *getSpelling() const;
939
940
941 static bool classof(const Attr *A) { return A->getKind() == attr::AnyX86NoCfCheck; }
942};
943
944class ArcWeakrefUnavailableAttr : public InheritableAttr {
945public:
946 static ArcWeakrefUnavailableAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
947 auto *A = new (Ctx) ArcWeakrefUnavailableAttr(Loc, Ctx, 0);
948 A->setImplicit(true);
949 return A;
950 }
951
952 ArcWeakrefUnavailableAttr(SourceRange R, ASTContext &Ctx
953 , unsigned SI
954 )
955 : InheritableAttr(attr::ArcWeakrefUnavailable, R, SI, false, false)
956 {
957 }
958
959 ArcWeakrefUnavailableAttr *clone(ASTContext &C) const;
960 void printPretty(raw_ostream &OS,
961 const PrintingPolicy &Policy) const;
962 const char *getSpelling() const;
963
964
965 static bool classof(const Attr *A) { return A->getKind() == attr::ArcWeakrefUnavailable; }
966};
967
968class ArgumentWithTypeTagAttr : public InheritableAttr {
969IdentifierInfo * argumentKind;
970
971ParamIdx argumentIdx;
972
973ParamIdx typeTagIdx;
974
975bool isPointer;
976
977public:
978 enum Spelling {
979 GNU_argument_with_type_tag = 0,
980 CXX11_clang_argument_with_type_tag = 1,
981 C2x_clang_argument_with_type_tag = 2,
982 GNU_pointer_with_type_tag = 3,
983 CXX11_clang_pointer_with_type_tag = 4,
984 C2x_clang_pointer_with_type_tag = 5
985 };
986
987 static ArgumentWithTypeTagAttr *CreateImplicit(ASTContext &Ctx, Spelling S, IdentifierInfo * ArgumentKind, ParamIdx ArgumentIdx, ParamIdx TypeTagIdx, bool IsPointer, SourceRange Loc = SourceRange()) {
988 auto *A = new (Ctx) ArgumentWithTypeTagAttr(Loc, Ctx, ArgumentKind, ArgumentIdx, TypeTagIdx, IsPointer, S);
989 A->setImplicit(true);
990 return A;
991 }
992
993 static ArgumentWithTypeTagAttr *CreateImplicit(ASTContext &Ctx, Spelling S, IdentifierInfo * ArgumentKind, ParamIdx ArgumentIdx, ParamIdx TypeTagIdx, SourceRange Loc = SourceRange()) {
994 auto *A = new (Ctx) ArgumentWithTypeTagAttr(Loc, Ctx, ArgumentKind, ArgumentIdx, TypeTagIdx, S);
995 A->setImplicit(true);
996 return A;
997 }
998
999 ArgumentWithTypeTagAttr(SourceRange R, ASTContext &Ctx
1000 , IdentifierInfo * ArgumentKind
1001 , ParamIdx ArgumentIdx
1002 , ParamIdx TypeTagIdx
1003 , bool IsPointer
1004 , unsigned SI
1005 )
1006 : InheritableAttr(attr::ArgumentWithTypeTag, R, SI, false, false)
1007 , argumentKind(ArgumentKind)
1008 , argumentIdx(ArgumentIdx)
1009 , typeTagIdx(TypeTagIdx)
1010 , isPointer(IsPointer)
1011 {
1012 }
1013
1014 ArgumentWithTypeTagAttr(SourceRange R, ASTContext &Ctx
1015 , IdentifierInfo * ArgumentKind
1016 , ParamIdx ArgumentIdx
1017 , ParamIdx TypeTagIdx
1018 , unsigned SI
1019 )
1020 : InheritableAttr(attr::ArgumentWithTypeTag, R, SI, false, false)
1021 , argumentKind(ArgumentKind)
1022 , argumentIdx(ArgumentIdx)
1023 , typeTagIdx(TypeTagIdx)
1024 , isPointer()
1025 {
1026 }
1027
1028 ArgumentWithTypeTagAttr *clone(ASTContext &C) const;
1029 void printPretty(raw_ostream &OS,
1030 const PrintingPolicy &Policy) const;
1031 const char *getSpelling() const;
1032 Spelling getSemanticSpelling() const {
1033 switch (SpellingListIndex) {
1034 default: llvm_unreachable("Unknown spelling list index")::llvm::llvm_unreachable_internal("Unknown spelling list index"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 1034)
;
1035 case 0: return GNU_argument_with_type_tag;
1036 case 1: return CXX11_clang_argument_with_type_tag;
1037 case 2: return C2x_clang_argument_with_type_tag;
1038 case 3: return GNU_pointer_with_type_tag;
1039 case 4: return CXX11_clang_pointer_with_type_tag;
1040 case 5: return C2x_clang_pointer_with_type_tag;
1041 }
1042 }
1043 IdentifierInfo * getArgumentKind() const {
1044 return argumentKind;
1045 }
1046
1047 ParamIdx getArgumentIdx() const {
1048 return argumentIdx;
1049 }
1050
1051 ParamIdx getTypeTagIdx() const {
1052 return typeTagIdx;
1053 }
1054
1055 bool getIsPointer() const {
1056 return isPointer;
1057 }
1058
1059
1060
1061 static bool classof(const Attr *A) { return A->getKind() == attr::ArgumentWithTypeTag; }
1062};
1063
1064class ArtificialAttr : public InheritableAttr {
1065public:
1066 static ArtificialAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
1067 auto *A = new (Ctx) ArtificialAttr(Loc, Ctx, 0);
1068 A->setImplicit(true);
1069 return A;
1070 }
1071
1072 ArtificialAttr(SourceRange R, ASTContext &Ctx
1073 , unsigned SI
1074 )
1075 : InheritableAttr(attr::Artificial, R, SI, false, false)
1076 {
1077 }
1078
1079 ArtificialAttr *clone(ASTContext &C) const;
1080 void printPretty(raw_ostream &OS,
1081 const PrintingPolicy &Policy) const;
1082 const char *getSpelling() const;
1083
1084
1085 static bool classof(const Attr *A) { return A->getKind() == attr::Artificial; }
1086};
1087
1088class AsmLabelAttr : public InheritableAttr {
1089unsigned labelLength;
1090char *label;
1091
1092public:
1093 static AsmLabelAttr *CreateImplicit(ASTContext &Ctx, llvm::StringRef Label, SourceRange Loc = SourceRange()) {
1094 auto *A = new (Ctx) AsmLabelAttr(Loc, Ctx, Label, 0);
1095 A->setImplicit(true);
1096 return A;
1097 }
1098
1099 AsmLabelAttr(SourceRange R, ASTContext &Ctx
1100 , llvm::StringRef Label
1101 , unsigned SI
1102 )
1103 : InheritableAttr(attr::AsmLabel, R, SI, false, false)
1104 , labelLength(Label.size()),label(new (Ctx, 1) char[labelLength])
1105 {
1106 if (!Label.empty())
1107 std::memcpy(label, Label.data(), labelLength);
1108 }
1109
1110 AsmLabelAttr *clone(ASTContext &C) const;
1111 void printPretty(raw_ostream &OS,
1112 const PrintingPolicy &Policy) const;
1113 const char *getSpelling() const;
1114 llvm::StringRef getLabel() const {
1115 return llvm::StringRef(label, labelLength);
1116 }
1117 unsigned getLabelLength() const {
1118 return labelLength;
1119 }
1120 void setLabel(ASTContext &C, llvm::StringRef S) {
1121 labelLength = S.size();
1122 this->label = new (C, 1) char [labelLength];
1123 if (!S.empty())
1124 std::memcpy(this->label, S.data(), labelLength);
1125 }
1126
1127
1128
1129 static bool classof(const Attr *A) { return A->getKind() == attr::AsmLabel; }
1130};
1131
1132class AssertCapabilityAttr : public InheritableAttr {
1133 unsigned args_Size;
1134 Expr * *args_;
1135
1136public:
1137 enum Spelling {
1138 GNU_assert_capability = 0,
1139 CXX11_clang_assert_capability = 1,
1140 GNU_assert_shared_capability = 2,
1141 CXX11_clang_assert_shared_capability = 3
1142 };
1143
1144 static AssertCapabilityAttr *CreateImplicit(ASTContext &Ctx, Spelling S, Expr * *Args, unsigned ArgsSize, SourceRange Loc = SourceRange()) {
1145 auto *A = new (Ctx) AssertCapabilityAttr(Loc, Ctx, Args, ArgsSize, S);
1146 A->setImplicit(true);
1147 return A;
1148 }
1149
1150 AssertCapabilityAttr(SourceRange R, ASTContext &Ctx
1151 , Expr * *Args, unsigned ArgsSize
1152 , unsigned SI
1153 )
1154 : InheritableAttr(attr::AssertCapability, R, SI, true, true)
1155 , args_Size(ArgsSize), args_(new (Ctx, 16) Expr *[args_Size])
1156 {
1157 std::copy(Args, Args + args_Size, args_);
1158 }
1159
1160 AssertCapabilityAttr(SourceRange R, ASTContext &Ctx
1161 , unsigned SI
1162 )
1163 : InheritableAttr(attr::AssertCapability, R, SI, true, true)
1164 , args_Size(0), args_(nullptr)
1165 {
1166 }
1167
1168 AssertCapabilityAttr *clone(ASTContext &C) const;
1169 void printPretty(raw_ostream &OS,
1170 const PrintingPolicy &Policy) const;
1171 const char *getSpelling() const;
1172 Spelling getSemanticSpelling() const {
1173 switch (SpellingListIndex) {
1174 default: llvm_unreachable("Unknown spelling list index")::llvm::llvm_unreachable_internal("Unknown spelling list index"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 1174)
;
1175 case 0: return GNU_assert_capability;
1176 case 1: return CXX11_clang_assert_capability;
1177 case 2: return GNU_assert_shared_capability;
1178 case 3: return CXX11_clang_assert_shared_capability;
1179 }
1180 }
1181 bool isShared() const { return SpellingListIndex == 2 ||
1182 SpellingListIndex == 3; }
1183 typedef Expr ** args_iterator;
1184 args_iterator args_begin() const { return args_; }
1185 args_iterator args_end() const { return args_ + args_Size; }
1186 unsigned args_size() const { return args_Size; }
1187 llvm::iterator_range<args_iterator> args() const { return llvm::make_range(args_begin(), args_end()); }
1188
1189
1190
1191
1192 static bool classof(const Attr *A) { return A->getKind() == attr::AssertCapability; }
1193};
1194
1195class AssertExclusiveLockAttr : public InheritableAttr {
1196 unsigned args_Size;
1197 Expr * *args_;
1198
1199public:
1200 static AssertExclusiveLockAttr *CreateImplicit(ASTContext &Ctx, Expr * *Args, unsigned ArgsSize, SourceRange Loc = SourceRange()) {
1201 auto *A = new (Ctx) AssertExclusiveLockAttr(Loc, Ctx, Args, ArgsSize, 0);
1202 A->setImplicit(true);
1203 return A;
1204 }
1205
1206 AssertExclusiveLockAttr(SourceRange R, ASTContext &Ctx
1207 , Expr * *Args, unsigned ArgsSize
1208 , unsigned SI
1209 )
1210 : InheritableAttr(attr::AssertExclusiveLock, R, SI, true, true)
1211 , args_Size(ArgsSize), args_(new (Ctx, 16) Expr *[args_Size])
1212 {
1213 std::copy(Args, Args + args_Size, args_);
1214 }
1215
1216 AssertExclusiveLockAttr(SourceRange R, ASTContext &Ctx
1217 , unsigned SI
1218 )
1219 : InheritableAttr(attr::AssertExclusiveLock, R, SI, true, true)
1220 , args_Size(0), args_(nullptr)
1221 {
1222 }
1223
1224 AssertExclusiveLockAttr *clone(ASTContext &C) const;
1225 void printPretty(raw_ostream &OS,
1226 const PrintingPolicy &Policy) const;
1227 const char *getSpelling() const;
1228 typedef Expr ** args_iterator;
1229 args_iterator args_begin() const { return args_; }
1230 args_iterator args_end() const { return args_ + args_Size; }
1231 unsigned args_size() const { return args_Size; }
1232 llvm::iterator_range<args_iterator> args() const { return llvm::make_range(args_begin(), args_end()); }
1233
1234
1235
1236
1237 static bool classof(const Attr *A) { return A->getKind() == attr::AssertExclusiveLock; }
1238};
1239
1240class AssertSharedLockAttr : public InheritableAttr {
1241 unsigned args_Size;
1242 Expr * *args_;
1243
1244public:
1245 static AssertSharedLockAttr *CreateImplicit(ASTContext &Ctx, Expr * *Args, unsigned ArgsSize, SourceRange Loc = SourceRange()) {
1246 auto *A = new (Ctx) AssertSharedLockAttr(Loc, Ctx, Args, ArgsSize, 0);
1247 A->setImplicit(true);
1248 return A;
1249 }
1250
1251 AssertSharedLockAttr(SourceRange R, ASTContext &Ctx
1252 , Expr * *Args, unsigned ArgsSize
1253 , unsigned SI
1254 )
1255 : InheritableAttr(attr::AssertSharedLock, R, SI, true, true)
1256 , args_Size(ArgsSize), args_(new (Ctx, 16) Expr *[args_Size])
1257 {
1258 std::copy(Args, Args + args_Size, args_);
1259 }
1260
1261 AssertSharedLockAttr(SourceRange R, ASTContext &Ctx
1262 , unsigned SI
1263 )
1264 : InheritableAttr(attr::AssertSharedLock, R, SI, true, true)
1265 , args_Size(0), args_(nullptr)
1266 {
1267 }
1268
1269 AssertSharedLockAttr *clone(ASTContext &C) const;
1270 void printPretty(raw_ostream &OS,
1271 const PrintingPolicy &Policy) const;
1272 const char *getSpelling() const;
1273 typedef Expr ** args_iterator;
1274 args_iterator args_begin() const { return args_; }
1275 args_iterator args_end() const { return args_ + args_Size; }
1276 unsigned args_size() const { return args_Size; }
1277 llvm::iterator_range<args_iterator> args() const { return llvm::make_range(args_begin(), args_end()); }
1278
1279
1280
1281
1282 static bool classof(const Attr *A) { return A->getKind() == attr::AssertSharedLock; }
1283};
1284
1285class AssumeAlignedAttr : public InheritableAttr {
1286Expr * alignment;
1287
1288Expr * offset;
1289
1290public:
1291 static AssumeAlignedAttr *CreateImplicit(ASTContext &Ctx, Expr * Alignment, Expr * Offset, SourceRange Loc = SourceRange()) {
1292 auto *A = new (Ctx) AssumeAlignedAttr(Loc, Ctx, Alignment, Offset, 0);
1293 A->setImplicit(true);
1294 return A;
1295 }
1296
1297 AssumeAlignedAttr(SourceRange R, ASTContext &Ctx
1298 , Expr * Alignment
1299 , Expr * Offset
1300 , unsigned SI
1301 )
1302 : InheritableAttr(attr::AssumeAligned, R, SI, false, false)
1303 , alignment(Alignment)
1304 , offset(Offset)
1305 {
1306 }
1307
1308 AssumeAlignedAttr(SourceRange R, ASTContext &Ctx
1309 , Expr * Alignment
1310 , unsigned SI
1311 )
1312 : InheritableAttr(attr::AssumeAligned, R, SI, false, false)
1313 , alignment(Alignment)
1314 , offset()
1315 {
1316 }
1317
1318 AssumeAlignedAttr *clone(ASTContext &C) const;
1319 void printPretty(raw_ostream &OS,
1320 const PrintingPolicy &Policy) const;
1321 const char *getSpelling() const;
1322 Expr * getAlignment() const {
1323 return alignment;
1324 }
1325
1326 Expr * getOffset() const {
1327 return offset;
1328 }
1329
1330
1331
1332 static bool classof(const Attr *A) { return A->getKind() == attr::AssumeAligned; }
1333};
1334
1335class AvailabilityAttr : public InheritableAttr {
1336IdentifierInfo * platform;
1337
1338VersionTuple introduced;
1339
1340
1341VersionTuple deprecated;
1342
1343
1344VersionTuple obsoleted;
1345
1346
1347bool unavailable;
1348
1349unsigned messageLength;
1350char *message;
1351
1352bool strict;
1353
1354unsigned replacementLength;
1355char *replacement;
1356
1357public:
1358 static AvailabilityAttr *CreateImplicit(ASTContext &Ctx, IdentifierInfo * Platform, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool Unavailable, llvm::StringRef Message, bool Strict, llvm::StringRef Replacement, SourceRange Loc = SourceRange()) {
1359 auto *A = new (Ctx) AvailabilityAttr(Loc, Ctx, Platform, Introduced, Deprecated, Obsoleted, Unavailable, Message, Strict, Replacement, 0);
1360 A->setImplicit(true);
1361 return A;
1362 }
1363
1364 AvailabilityAttr(SourceRange R, ASTContext &Ctx
1365 , IdentifierInfo * Platform
1366 , VersionTuple Introduced
1367 , VersionTuple Deprecated
1368 , VersionTuple Obsoleted
1369 , bool Unavailable
1370 , llvm::StringRef Message
1371 , bool Strict
1372 , llvm::StringRef Replacement
1373 , unsigned SI
1374 )
1375 : InheritableAttr(attr::Availability, R, SI, false, true)
1376 , platform(Platform)
1377 , introduced(Introduced)
1378 , deprecated(Deprecated)
1379 , obsoleted(Obsoleted)
1380 , unavailable(Unavailable)
1381 , messageLength(Message.size()),message(new (Ctx, 1) char[messageLength])
1382 , strict(Strict)
1383 , replacementLength(Replacement.size()),replacement(new (Ctx, 1) char[replacementLength])
1384 {
1385 if (!Message.empty())
1386 std::memcpy(message, Message.data(), messageLength);
1387 if (!Replacement.empty())
1388 std::memcpy(replacement, Replacement.data(), replacementLength);
1389 }
1390
1391 AvailabilityAttr *clone(ASTContext &C) const;
1392 void printPretty(raw_ostream &OS,
1393 const PrintingPolicy &Policy) const;
1394 const char *getSpelling() const;
1395 IdentifierInfo * getPlatform() const {
1396 return platform;
1397 }
1398
1399 VersionTuple getIntroduced() const {
1400 return introduced;
1401 }
1402 void setIntroduced(ASTContext &C, VersionTuple V) {
1403 introduced = V;
1404 }
1405
1406 VersionTuple getDeprecated() const {
1407 return deprecated;
1408 }
1409 void setDeprecated(ASTContext &C, VersionTuple V) {
1410 deprecated = V;
1411 }
1412
1413 VersionTuple getObsoleted() const {
1414 return obsoleted;
1415 }
1416 void setObsoleted(ASTContext &C, VersionTuple V) {
1417 obsoleted = V;
1418 }
1419
1420 bool getUnavailable() const {
1421 return unavailable;
1422 }
1423
1424 llvm::StringRef getMessage() const {
1425 return llvm::StringRef(message, messageLength);
1426 }
1427 unsigned getMessageLength() const {
1428 return messageLength;
1429 }
1430 void setMessage(ASTContext &C, llvm::StringRef S) {
1431 messageLength = S.size();
1432 this->message = new (C, 1) char [messageLength];
1433 if (!S.empty())
1434 std::memcpy(this->message, S.data(), messageLength);
1435 }
1436
1437 bool getStrict() const {
1438 return strict;
1439 }
1440
1441 llvm::StringRef getReplacement() const {
1442 return llvm::StringRef(replacement, replacementLength);
1443 }
1444 unsigned getReplacementLength() const {
1445 return replacementLength;
1446 }
1447 void setReplacement(ASTContext &C, llvm::StringRef S) {
1448 replacementLength = S.size();
1449 this->replacement = new (C, 1) char [replacementLength];
1450 if (!S.empty())
1451 std::memcpy(this->replacement, S.data(), replacementLength);
1452 }
1453
1454static llvm::StringRef getPrettyPlatformName(llvm::StringRef Platform) {
1455 return llvm::StringSwitch<llvm::StringRef>(Platform)
1456 .Case("android", "Android")
1457 .Case("ios", "iOS")
1458 .Case("macos", "macOS")
1459 .Case("tvos", "tvOS")
1460 .Case("watchos", "watchOS")
1461 .Case("ios_app_extension", "iOS (App Extension)")
1462 .Case("macos_app_extension", "macOS (App Extension)")
1463 .Case("tvos_app_extension", "tvOS (App Extension)")
1464 .Case("watchos_app_extension", "watchOS (App Extension)")
1465 .Default(llvm::StringRef());
1466}
1467static llvm::StringRef getPlatformNameSourceSpelling(llvm::StringRef Platform) {
1468 return llvm::StringSwitch<llvm::StringRef>(Platform)
1469 .Case("ios", "iOS")
1470 .Case("macos", "macOS")
1471 .Case("tvos", "tvOS")
1472 .Case("watchos", "watchOS")
1473 .Case("ios_app_extension", "iOSApplicationExtension")
1474 .Case("macos_app_extension", "macOSApplicationExtension")
1475 .Case("tvos_app_extension", "tvOSApplicationExtension")
1476 .Case("watchos_app_extension", "watchOSApplicationExtension")
1477 .Default(Platform);
1478}
1479static llvm::StringRef canonicalizePlatformName(llvm::StringRef Platform) {
1480 return llvm::StringSwitch<llvm::StringRef>(Platform)
1481 .Case("iOS", "ios")
1482 .Case("macOS", "macos")
1483 .Case("tvOS", "tvos")
1484 .Case("watchOS", "watchos")
1485 .Case("iOSApplicationExtension", "ios_app_extension")
1486 .Case("macOSApplicationExtension", "macos_app_extension")
1487 .Case("tvOSApplicationExtension", "tvos_app_extension")
1488 .Case("watchOSApplicationExtension", "watchos_app_extension")
1489 .Default(Platform);
1490}
1491
1492 static bool classof(const Attr *A) { return A->getKind() == attr::Availability; }
1493};
1494
1495class BlocksAttr : public InheritableAttr {
1496public:
1497 enum BlockType {
1498 ByRef
1499 };
1500private:
1501 BlockType type;
1502
1503public:
1504 static BlocksAttr *CreateImplicit(ASTContext &Ctx, BlockType Type, SourceRange Loc = SourceRange()) {
1505 auto *A = new (Ctx) BlocksAttr(Loc, Ctx, Type, 0);
1506 A->setImplicit(true);
1507 return A;
1508 }
1509
1510 BlocksAttr(SourceRange R, ASTContext &Ctx
1511 , BlockType Type
1512 , unsigned SI
1513 )
1514 : InheritableAttr(attr::Blocks, R, SI, false, false)
1515 , type(Type)
1516 {
1517 }
1518
1519 BlocksAttr *clone(ASTContext &C) const;
1520 void printPretty(raw_ostream &OS,
1521 const PrintingPolicy &Policy) const;
1522 const char *getSpelling() const;
1523 BlockType getType() const {
1524 return type;
1525 }
1526
1527 static bool ConvertStrToBlockType(StringRef Val, BlockType &Out) {
1528 Optional<BlockType> R = llvm::StringSwitch<Optional<BlockType>>(Val)
1529 .Case("byref", BlocksAttr::ByRef)
1530 .Default(Optional<BlockType>());
1531 if (R) {
1532 Out = *R;
1533 return true;
1534 }
1535 return false;
1536 }
1537
1538 static const char *ConvertBlockTypeToStr(BlockType Val) {
1539 switch(Val) {
1540 case BlocksAttr::ByRef: return "byref";
1541 }
1542 llvm_unreachable("No enumerator with that value")::llvm::llvm_unreachable_internal("No enumerator with that value"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 1542)
;
1543 }
1544
1545
1546 static bool classof(const Attr *A) { return A->getKind() == attr::Blocks; }
1547};
1548
1549class C11NoReturnAttr : public InheritableAttr {
1550public:
1551 static C11NoReturnAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
1552 auto *A = new (Ctx) C11NoReturnAttr(Loc, Ctx, 0);
1553 A->setImplicit(true);
1554 return A;
1555 }
1556
1557 C11NoReturnAttr(SourceRange R, ASTContext &Ctx
1558 , unsigned SI
1559 )
1560 : InheritableAttr(attr::C11NoReturn, R, SI, false, false)
1561 {
1562 }
1563
1564 C11NoReturnAttr *clone(ASTContext &C) const;
1565 void printPretty(raw_ostream &OS,
1566 const PrintingPolicy &Policy) const;
1567 const char *getSpelling() const;
1568
1569
1570 static bool classof(const Attr *A) { return A->getKind() == attr::C11NoReturn; }
1571};
1572
1573class CDeclAttr : public InheritableAttr {
1574public:
1575 static CDeclAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
1576 auto *A = new (Ctx) CDeclAttr(Loc, Ctx, 0);
1577 A->setImplicit(true);
1578 return A;
1579 }
1580
1581 CDeclAttr(SourceRange R, ASTContext &Ctx
1582 , unsigned SI
1583 )
1584 : InheritableAttr(attr::CDecl, R, SI, false, false)
1585 {
1586 }
1587
1588 CDeclAttr *clone(ASTContext &C) const;
1589 void printPretty(raw_ostream &OS,
1590 const PrintingPolicy &Policy) const;
1591 const char *getSpelling() const;
1592
1593
1594 static bool classof(const Attr *A) { return A->getKind() == attr::CDecl; }
1595};
1596
1597class CFAuditedTransferAttr : public InheritableAttr {
1598public:
1599 static CFAuditedTransferAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
1600 auto *A = new (Ctx) CFAuditedTransferAttr(Loc, Ctx, 0);
1601 A->setImplicit(true);
1602 return A;
1603 }
1604
1605 CFAuditedTransferAttr(SourceRange R, ASTContext &Ctx
1606 , unsigned SI
1607 )
1608 : InheritableAttr(attr::CFAuditedTransfer, R, SI, false, false)
1609 {
1610 }
1611
1612 CFAuditedTransferAttr *clone(ASTContext &C) const;
1613 void printPretty(raw_ostream &OS,
1614 const PrintingPolicy &Policy) const;
1615 const char *getSpelling() const;
1616
1617
1618 static bool classof(const Attr *A) { return A->getKind() == attr::CFAuditedTransfer; }
1619};
1620
1621class CFConsumedAttr : public InheritableParamAttr {
1622public:
1623 static CFConsumedAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
1624 auto *A = new (Ctx) CFConsumedAttr(Loc, Ctx, 0);
1625 A->setImplicit(true);
1626 return A;
1627 }
1628
1629 CFConsumedAttr(SourceRange R, ASTContext &Ctx
1630 , unsigned SI
1631 )
1632 : InheritableParamAttr(attr::CFConsumed, R, SI, false, false)
1633 {
1634 }
1635
1636 CFConsumedAttr *clone(ASTContext &C) const;
1637 void printPretty(raw_ostream &OS,
1638 const PrintingPolicy &Policy) const;
1639 const char *getSpelling() const;
1640
1641
1642 static bool classof(const Attr *A) { return A->getKind() == attr::CFConsumed; }
1643};
1644
1645class CFReturnsNotRetainedAttr : public InheritableAttr {
1646public:
1647 static CFReturnsNotRetainedAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
1648 auto *A = new (Ctx) CFReturnsNotRetainedAttr(Loc, Ctx, 0);
1649 A->setImplicit(true);
1650 return A;
1651 }
1652
1653 CFReturnsNotRetainedAttr(SourceRange R, ASTContext &Ctx
1654 , unsigned SI
1655 )
1656 : InheritableAttr(attr::CFReturnsNotRetained, R, SI, false, false)
1657 {
1658 }
1659
1660 CFReturnsNotRetainedAttr *clone(ASTContext &C) const;
1661 void printPretty(raw_ostream &OS,
1662 const PrintingPolicy &Policy) const;
1663 const char *getSpelling() const;
1664
1665
1666 static bool classof(const Attr *A) { return A->getKind() == attr::CFReturnsNotRetained; }
1667};
1668
1669class CFReturnsRetainedAttr : public InheritableAttr {
1670public:
1671 static CFReturnsRetainedAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
1672 auto *A = new (Ctx) CFReturnsRetainedAttr(Loc, Ctx, 0);
1673 A->setImplicit(true);
1674 return A;
1675 }
1676
1677 CFReturnsRetainedAttr(SourceRange R, ASTContext &Ctx
1678 , unsigned SI
1679 )
1680 : InheritableAttr(attr::CFReturnsRetained, R, SI, false, false)
1681 {
1682 }
1683
1684 CFReturnsRetainedAttr *clone(ASTContext &C) const;
1685 void printPretty(raw_ostream &OS,
1686 const PrintingPolicy &Policy) const;
1687 const char *getSpelling() const;
1688
1689
1690 static bool classof(const Attr *A) { return A->getKind() == attr::CFReturnsRetained; }
1691};
1692
1693class CFUnknownTransferAttr : public InheritableAttr {
1694public:
1695 static CFUnknownTransferAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
1696 auto *A = new (Ctx) CFUnknownTransferAttr(Loc, Ctx, 0);
1697 A->setImplicit(true);
1698 return A;
1699 }
1700
1701 CFUnknownTransferAttr(SourceRange R, ASTContext &Ctx
1702 , unsigned SI
1703 )
1704 : InheritableAttr(attr::CFUnknownTransfer, R, SI, false, false)
1705 {
1706 }
1707
1708 CFUnknownTransferAttr *clone(ASTContext &C) const;
1709 void printPretty(raw_ostream &OS,
1710 const PrintingPolicy &Policy) const;
1711 const char *getSpelling() const;
1712
1713
1714 static bool classof(const Attr *A) { return A->getKind() == attr::CFUnknownTransfer; }
1715};
1716
1717class CUDAConstantAttr : public InheritableAttr {
1718public:
1719 static CUDAConstantAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
1720 auto *A = new (Ctx) CUDAConstantAttr(Loc, Ctx, 0);
1721 A->setImplicit(true);
1722 return A;
1723 }
1724
1725 CUDAConstantAttr(SourceRange R, ASTContext &Ctx
1726 , unsigned SI
1727 )
1728 : InheritableAttr(attr::CUDAConstant, R, SI, false, false)
1729 {
1730 }
1731
1732 CUDAConstantAttr *clone(ASTContext &C) const;
1733 void printPretty(raw_ostream &OS,
1734 const PrintingPolicy &Policy) const;
1735 const char *getSpelling() const;
1736
1737
1738 static bool classof(const Attr *A) { return A->getKind() == attr::CUDAConstant; }
1739};
1740
1741class CUDADeviceAttr : public InheritableAttr {
1742public:
1743 static CUDADeviceAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
1744 auto *A = new (Ctx) CUDADeviceAttr(Loc, Ctx, 0);
1745 A->setImplicit(true);
1746 return A;
1747 }
1748
1749 CUDADeviceAttr(SourceRange R, ASTContext &Ctx
1750 , unsigned SI
1751 )
1752 : InheritableAttr(attr::CUDADevice, R, SI, false, false)
1753 {
1754 }
1755
1756 CUDADeviceAttr *clone(ASTContext &C) const;
1757 void printPretty(raw_ostream &OS,
1758 const PrintingPolicy &Policy) const;
1759 const char *getSpelling() const;
1760
1761
1762 static bool classof(const Attr *A) { return A->getKind() == attr::CUDADevice; }
1763};
1764
1765class CUDAGlobalAttr : public InheritableAttr {
1766public:
1767 static CUDAGlobalAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
1768 auto *A = new (Ctx) CUDAGlobalAttr(Loc, Ctx, 0);
1769 A->setImplicit(true);
1770 return A;
1771 }
1772
1773 CUDAGlobalAttr(SourceRange R, ASTContext &Ctx
1774 , unsigned SI
1775 )
1776 : InheritableAttr(attr::CUDAGlobal, R, SI, false, false)
1777 {
1778 }
1779
1780 CUDAGlobalAttr *clone(ASTContext &C) const;
1781 void printPretty(raw_ostream &OS,
1782 const PrintingPolicy &Policy) const;
1783 const char *getSpelling() const;
1784
1785
1786 static bool classof(const Attr *A) { return A->getKind() == attr::CUDAGlobal; }
1787};
1788
1789class CUDAHostAttr : public InheritableAttr {
1790public:
1791 static CUDAHostAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
1792 auto *A = new (Ctx) CUDAHostAttr(Loc, Ctx, 0);
1793 A->setImplicit(true);
1794 return A;
1795 }
1796
1797 CUDAHostAttr(SourceRange R, ASTContext &Ctx
1798 , unsigned SI
1799 )
1800 : InheritableAttr(attr::CUDAHost, R, SI, false, false)
1801 {
1802 }
1803
1804 CUDAHostAttr *clone(ASTContext &C) const;
1805 void printPretty(raw_ostream &OS,
1806 const PrintingPolicy &Policy) const;
1807 const char *getSpelling() const;
1808
1809
1810 static bool classof(const Attr *A) { return A->getKind() == attr::CUDAHost; }
1811};
1812
1813class CUDAInvalidTargetAttr : public InheritableAttr {
1814public:
1815 static CUDAInvalidTargetAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
1816 auto *A = new (Ctx) CUDAInvalidTargetAttr(Loc, Ctx, 0);
1817 A->setImplicit(true);
1818 return A;
1819 }
1820
1821 CUDAInvalidTargetAttr(SourceRange R, ASTContext &Ctx
1822 , unsigned SI
1823 )
1824 : InheritableAttr(attr::CUDAInvalidTarget, R, SI, false, false)
1825 {
1826 }
1827
1828 CUDAInvalidTargetAttr *clone(ASTContext &C) const;
1829 void printPretty(raw_ostream &OS,
1830 const PrintingPolicy &Policy) const;
1831 const char *getSpelling() const;
1832
1833
1834 static bool classof(const Attr *A) { return A->getKind() == attr::CUDAInvalidTarget; }
1835};
1836
1837class CUDALaunchBoundsAttr : public InheritableAttr {
1838Expr * maxThreads;
1839
1840Expr * minBlocks;
1841
1842public:
1843 static CUDALaunchBoundsAttr *CreateImplicit(ASTContext &Ctx, Expr * MaxThreads, Expr * MinBlocks, SourceRange Loc = SourceRange()) {
1844 auto *A = new (Ctx) CUDALaunchBoundsAttr(Loc, Ctx, MaxThreads, MinBlocks, 0);
1845 A->setImplicit(true);
1846 return A;
1847 }
1848
1849 CUDALaunchBoundsAttr(SourceRange R, ASTContext &Ctx
1850 , Expr * MaxThreads
1851 , Expr * MinBlocks
1852 , unsigned SI
1853 )
1854 : InheritableAttr(attr::CUDALaunchBounds, R, SI, false, false)
1855 , maxThreads(MaxThreads)
1856 , minBlocks(MinBlocks)
1857 {
1858 }
1859
1860 CUDALaunchBoundsAttr(SourceRange R, ASTContext &Ctx
1861 , Expr * MaxThreads
1862 , unsigned SI
1863 )
1864 : InheritableAttr(attr::CUDALaunchBounds, R, SI, false, false)
1865 , maxThreads(MaxThreads)
1866 , minBlocks()
1867 {
1868 }
1869
1870 CUDALaunchBoundsAttr *clone(ASTContext &C) const;
1871 void printPretty(raw_ostream &OS,
1872 const PrintingPolicy &Policy) const;
1873 const char *getSpelling() const;
1874 Expr * getMaxThreads() const {
1875 return maxThreads;
1876 }
1877
1878 Expr * getMinBlocks() const {
1879 return minBlocks;
1880 }
1881
1882
1883
1884 static bool classof(const Attr *A) { return A->getKind() == attr::CUDALaunchBounds; }
1885};
1886
1887class CUDASharedAttr : public InheritableAttr {
1888public:
1889 static CUDASharedAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
1890 auto *A = new (Ctx) CUDASharedAttr(Loc, Ctx, 0);
1891 A->setImplicit(true);
1892 return A;
1893 }
1894
1895 CUDASharedAttr(SourceRange R, ASTContext &Ctx
1896 , unsigned SI
1897 )
1898 : InheritableAttr(attr::CUDAShared, R, SI, false, false)
1899 {
1900 }
1901
1902 CUDASharedAttr *clone(ASTContext &C) const;
1903 void printPretty(raw_ostream &OS,
1904 const PrintingPolicy &Policy) const;
1905 const char *getSpelling() const;
1906
1907
1908 static bool classof(const Attr *A) { return A->getKind() == attr::CUDAShared; }
1909};
1910
1911class CXX11NoReturnAttr : public InheritableAttr {
1912public:
1913 static CXX11NoReturnAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
1914 auto *A = new (Ctx) CXX11NoReturnAttr(Loc, Ctx, 0);
1915 A->setImplicit(true);
1916 return A;
1917 }
1918
1919 CXX11NoReturnAttr(SourceRange R, ASTContext &Ctx
1920 , unsigned SI
1921 )
1922 : InheritableAttr(attr::CXX11NoReturn, R, SI, false, false)
1923 {
1924 }
1925
1926 CXX11NoReturnAttr *clone(ASTContext &C) const;
1927 void printPretty(raw_ostream &OS,
1928 const PrintingPolicy &Policy) const;
1929 const char *getSpelling() const;
1930
1931
1932 static bool classof(const Attr *A) { return A->getKind() == attr::CXX11NoReturn; }
1933};
1934
1935class CallableWhenAttr : public InheritableAttr {
1936public:
1937 enum ConsumedState {
1938 Unknown,
1939 Consumed,
1940 Unconsumed
1941 };
1942private:
1943 unsigned callableStates_Size;
1944 ConsumedState *callableStates_;
1945
1946public:
1947 static CallableWhenAttr *CreateImplicit(ASTContext &Ctx, ConsumedState *CallableStates, unsigned CallableStatesSize, SourceRange Loc = SourceRange()) {
1948 auto *A = new (Ctx) CallableWhenAttr(Loc, Ctx, CallableStates, CallableStatesSize, 0);
1949 A->setImplicit(true);
1950 return A;
1951 }
1952
1953 CallableWhenAttr(SourceRange R, ASTContext &Ctx
1954 , ConsumedState *CallableStates, unsigned CallableStatesSize
1955 , unsigned SI
1956 )
1957 : InheritableAttr(attr::CallableWhen, R, SI, false, false)
1958 , callableStates_Size(CallableStatesSize), callableStates_(new (Ctx, 16) ConsumedState[callableStates_Size])
1959 {
1960 std::copy(CallableStates, CallableStates + callableStates_Size, callableStates_);
1961 }
1962
1963 CallableWhenAttr(SourceRange R, ASTContext &Ctx
1964 , unsigned SI
1965 )
1966 : InheritableAttr(attr::CallableWhen, R, SI, false, false)
1967 , callableStates_Size(0), callableStates_(nullptr)
1968 {
1969 }
1970
1971 CallableWhenAttr *clone(ASTContext &C) const;
1972 void printPretty(raw_ostream &OS,
1973 const PrintingPolicy &Policy) const;
1974 const char *getSpelling() const;
1975 typedef ConsumedState* callableStates_iterator;
1976 callableStates_iterator callableStates_begin() const { return callableStates_; }
1977 callableStates_iterator callableStates_end() const { return callableStates_ + callableStates_Size; }
1978 unsigned callableStates_size() const { return callableStates_Size; }
1979 llvm::iterator_range<callableStates_iterator> callableStates() const { return llvm::make_range(callableStates_begin(), callableStates_end()); }
1980
1981
1982 static bool ConvertStrToConsumedState(StringRef Val, ConsumedState &Out) {
1983 Optional<ConsumedState> R = llvm::StringSwitch<Optional<ConsumedState>>(Val)
1984 .Case("unknown", CallableWhenAttr::Unknown)
1985 .Case("consumed", CallableWhenAttr::Consumed)
1986 .Case("unconsumed", CallableWhenAttr::Unconsumed)
1987 .Default(Optional<ConsumedState>());
1988 if (R) {
1989 Out = *R;
1990 return true;
1991 }
1992 return false;
1993 }
1994
1995 static const char *ConvertConsumedStateToStr(ConsumedState Val) {
1996 switch(Val) {
1997 case CallableWhenAttr::Unknown: return "unknown";
1998 case CallableWhenAttr::Consumed: return "consumed";
1999 case CallableWhenAttr::Unconsumed: return "unconsumed";
2000 }
2001 llvm_unreachable("No enumerator with that value")::llvm::llvm_unreachable_internal("No enumerator with that value"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 2001)
;
2002 }
2003
2004
2005 static bool classof(const Attr *A) { return A->getKind() == attr::CallableWhen; }
2006};
2007
2008class CapabilityAttr : public InheritableAttr {
2009unsigned nameLength;
2010char *name;
2011
2012public:
2013 enum Spelling {
2014 GNU_capability = 0,
2015 CXX11_clang_capability = 1,
2016 GNU_shared_capability = 2,
2017 CXX11_clang_shared_capability = 3
2018 };
2019
2020 static CapabilityAttr *CreateImplicit(ASTContext &Ctx, Spelling S, llvm::StringRef Name, SourceRange Loc = SourceRange()) {
2021 auto *A = new (Ctx) CapabilityAttr(Loc, Ctx, Name, S);
2022 A->setImplicit(true);
2023 return A;
2024 }
2025
2026 CapabilityAttr(SourceRange R, ASTContext &Ctx
2027 , llvm::StringRef Name
2028 , unsigned SI
2029 )
2030 : InheritableAttr(attr::Capability, R, SI, false, false)
2031 , nameLength(Name.size()),name(new (Ctx, 1) char[nameLength])
2032 {
2033 if (!Name.empty())
2034 std::memcpy(name, Name.data(), nameLength);
2035 }
2036
2037 CapabilityAttr *clone(ASTContext &C) const;
2038 void printPretty(raw_ostream &OS,
2039 const PrintingPolicy &Policy) const;
2040 const char *getSpelling() const;
2041 Spelling getSemanticSpelling() const {
2042 switch (SpellingListIndex) {
2043 default: llvm_unreachable("Unknown spelling list index")::llvm::llvm_unreachable_internal("Unknown spelling list index"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 2043)
;
2044 case 0: return GNU_capability;
2045 case 1: return CXX11_clang_capability;
2046 case 2: return GNU_shared_capability;
2047 case 3: return CXX11_clang_shared_capability;
2048 }
2049 }
2050 bool isShared() const { return SpellingListIndex == 2 ||
2051 SpellingListIndex == 3; }
2052 llvm::StringRef getName() const {
2053 return llvm::StringRef(name, nameLength);
2054 }
2055 unsigned getNameLength() const {
2056 return nameLength;
2057 }
2058 void setName(ASTContext &C, llvm::StringRef S) {
2059 nameLength = S.size();
2060 this->name = new (C, 1) char [nameLength];
2061 if (!S.empty())
2062 std::memcpy(this->name, S.data(), nameLength);
2063 }
2064
2065
2066 bool isMutex() const { return getName().equals_lower("mutex"); }
2067 bool isRole() const { return getName().equals_lower("role"); }
2068
2069
2070 static bool classof(const Attr *A) { return A->getKind() == attr::Capability; }
2071};
2072
2073class CapturedRecordAttr : public InheritableAttr {
2074public:
2075 static CapturedRecordAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
2076 auto *A = new (Ctx) CapturedRecordAttr(Loc, Ctx, 0);
2077 A->setImplicit(true);
2078 return A;
2079 }
2080
2081 CapturedRecordAttr(SourceRange R, ASTContext &Ctx
2082 , unsigned SI
2083 )
2084 : InheritableAttr(attr::CapturedRecord, R, SI, false, false)
2085 {
2086 }
2087
2088 CapturedRecordAttr *clone(ASTContext &C) const;
2089 void printPretty(raw_ostream &OS,
2090 const PrintingPolicy &Policy) const;
2091 const char *getSpelling() const;
2092
2093
2094 static bool classof(const Attr *A) { return A->getKind() == attr::CapturedRecord; }
2095};
2096
2097class CarriesDependencyAttr : public InheritableParamAttr {
2098public:
2099 static CarriesDependencyAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
2100 auto *A = new (Ctx) CarriesDependencyAttr(Loc, Ctx, 0);
2101 A->setImplicit(true);
2102 return A;
2103 }
2104
2105 CarriesDependencyAttr(SourceRange R, ASTContext &Ctx
2106 , unsigned SI
2107 )
2108 : InheritableParamAttr(attr::CarriesDependency, R, SI, false, false)
2109 {
2110 }
2111
2112 CarriesDependencyAttr *clone(ASTContext &C) const;
2113 void printPretty(raw_ostream &OS,
2114 const PrintingPolicy &Policy) const;
2115 const char *getSpelling() const;
2116
2117
2118 static bool classof(const Attr *A) { return A->getKind() == attr::CarriesDependency; }
2119};
2120
2121class CleanupAttr : public InheritableAttr {
2122FunctionDecl * functionDecl;
2123
2124public:
2125 static CleanupAttr *CreateImplicit(ASTContext &Ctx, FunctionDecl * FunctionDecl, SourceRange Loc = SourceRange()) {
2126 auto *A = new (Ctx) CleanupAttr(Loc, Ctx, FunctionDecl, 0);
2127 A->setImplicit(true);
2128 return A;
2129 }
2130
2131 CleanupAttr(SourceRange R, ASTContext &Ctx
2132 , FunctionDecl * FunctionDecl
2133 , unsigned SI
2134 )
2135 : InheritableAttr(attr::Cleanup, R, SI, false, false)
2136 , functionDecl(FunctionDecl)
2137 {
2138 }
2139
2140 CleanupAttr *clone(ASTContext &C) const;
2141 void printPretty(raw_ostream &OS,
2142 const PrintingPolicy &Policy) const;
2143 const char *getSpelling() const;
2144 FunctionDecl * getFunctionDecl() const {
2145 return functionDecl;
2146 }
2147
2148
2149
2150 static bool classof(const Attr *A) { return A->getKind() == attr::Cleanup; }
2151};
2152
2153class ColdAttr : public InheritableAttr {
2154public:
2155 static ColdAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
2156 auto *A = new (Ctx) ColdAttr(Loc, Ctx, 0);
2157 A->setImplicit(true);
2158 return A;
2159 }
2160
2161 ColdAttr(SourceRange R, ASTContext &Ctx
2162 , unsigned SI
2163 )
2164 : InheritableAttr(attr::Cold, R, SI, false, false)
2165 {
2166 }
2167
2168 ColdAttr *clone(ASTContext &C) const;
2169 void printPretty(raw_ostream &OS,
2170 const PrintingPolicy &Policy) const;
2171 const char *getSpelling() const;
2172
2173
2174 static bool classof(const Attr *A) { return A->getKind() == attr::Cold; }
2175};
2176
2177class CommonAttr : public InheritableAttr {
2178public:
2179 static CommonAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
2180 auto *A = new (Ctx) CommonAttr(Loc, Ctx, 0);
2181 A->setImplicit(true);
2182 return A;
2183 }
2184
2185 CommonAttr(SourceRange R, ASTContext &Ctx
2186 , unsigned SI
2187 )
2188 : InheritableAttr(attr::Common, R, SI, false, false)
2189 {
2190 }
2191
2192 CommonAttr *clone(ASTContext &C) const;
2193 void printPretty(raw_ostream &OS,
2194 const PrintingPolicy &Policy) const;
2195 const char *getSpelling() const;
2196
2197
2198 static bool classof(const Attr *A) { return A->getKind() == attr::Common; }
2199};
2200
2201class ConstAttr : public InheritableAttr {
2202public:
2203 static ConstAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
2204 auto *A = new (Ctx) ConstAttr(Loc, Ctx, 0);
2205 A->setImplicit(true);
2206 return A;
2207 }
2208
2209 ConstAttr(SourceRange R, ASTContext &Ctx
2210 , unsigned SI
2211 )
2212 : InheritableAttr(attr::Const, R, SI, false, false)
2213 {
2214 }
2215
2216 ConstAttr *clone(ASTContext &C) const;
2217 void printPretty(raw_ostream &OS,
2218 const PrintingPolicy &Policy) const;
2219 const char *getSpelling() const;
2220
2221
2222 static bool classof(const Attr *A) { return A->getKind() == attr::Const; }
2223};
2224
2225class ConstructorAttr : public InheritableAttr {
2226int priority;
2227
2228public:
2229 static ConstructorAttr *CreateImplicit(ASTContext &Ctx, int Priority, SourceRange Loc = SourceRange()) {
2230 auto *A = new (Ctx) ConstructorAttr(Loc, Ctx, Priority, 0);
2231 A->setImplicit(true);
2232 return A;
2233 }
2234
2235 ConstructorAttr(SourceRange R, ASTContext &Ctx
2236 , int Priority
2237 , unsigned SI
2238 )
2239 : InheritableAttr(attr::Constructor, R, SI, false, false)
2240 , priority(Priority)
2241 {
2242 }
2243
2244 ConstructorAttr(SourceRange R, ASTContext &Ctx
2245 , unsigned SI
2246 )
2247 : InheritableAttr(attr::Constructor, R, SI, false, false)
2248 , priority()
2249 {
2250 }
2251
2252 ConstructorAttr *clone(ASTContext &C) const;
2253 void printPretty(raw_ostream &OS,
2254 const PrintingPolicy &Policy) const;
2255 const char *getSpelling() const;
2256 int getPriority() const {
2257 return priority;
2258 }
2259
2260 static const int DefaultPriority = 65535;
2261
2262
2263
2264 static bool classof(const Attr *A) { return A->getKind() == attr::Constructor; }
2265};
2266
2267class ConsumableAttr : public InheritableAttr {
2268public:
2269 enum ConsumedState {
2270 Unknown,
2271 Consumed,
2272 Unconsumed
2273 };
2274private:
2275 ConsumedState defaultState;
2276
2277public:
2278 static ConsumableAttr *CreateImplicit(ASTContext &Ctx, ConsumedState DefaultState, SourceRange Loc = SourceRange()) {
2279 auto *A = new (Ctx) ConsumableAttr(Loc, Ctx, DefaultState, 0);
2280 A->setImplicit(true);
2281 return A;
2282 }
2283
2284 ConsumableAttr(SourceRange R, ASTContext &Ctx
2285 , ConsumedState DefaultState
2286 , unsigned SI
2287 )
2288 : InheritableAttr(attr::Consumable, R, SI, false, false)
2289 , defaultState(DefaultState)
2290 {
2291 }
2292
2293 ConsumableAttr *clone(ASTContext &C) const;
2294 void printPretty(raw_ostream &OS,
2295 const PrintingPolicy &Policy) const;
2296 const char *getSpelling() const;
2297 ConsumedState getDefaultState() const {
2298 return defaultState;
2299 }
2300
2301 static bool ConvertStrToConsumedState(StringRef Val, ConsumedState &Out) {
2302 Optional<ConsumedState> R = llvm::StringSwitch<Optional<ConsumedState>>(Val)
2303 .Case("unknown", ConsumableAttr::Unknown)
2304 .Case("consumed", ConsumableAttr::Consumed)
2305 .Case("unconsumed", ConsumableAttr::Unconsumed)
2306 .Default(Optional<ConsumedState>());
2307 if (R) {
2308 Out = *R;
2309 return true;
2310 }
2311 return false;
2312 }
2313
2314 static const char *ConvertConsumedStateToStr(ConsumedState Val) {
2315 switch(Val) {
2316 case ConsumableAttr::Unknown: return "unknown";
2317 case ConsumableAttr::Consumed: return "consumed";
2318 case ConsumableAttr::Unconsumed: return "unconsumed";
2319 }
2320 llvm_unreachable("No enumerator with that value")::llvm::llvm_unreachable_internal("No enumerator with that value"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 2320)
;
2321 }
2322
2323
2324 static bool classof(const Attr *A) { return A->getKind() == attr::Consumable; }
2325};
2326
2327class ConsumableAutoCastAttr : public InheritableAttr {
2328public:
2329 static ConsumableAutoCastAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
2330 auto *A = new (Ctx) ConsumableAutoCastAttr(Loc, Ctx, 0);
2331 A->setImplicit(true);
2332 return A;
2333 }
2334
2335 ConsumableAutoCastAttr(SourceRange R, ASTContext &Ctx
2336 , unsigned SI
2337 )
2338 : InheritableAttr(attr::ConsumableAutoCast, R, SI, false, false)
2339 {
2340 }
2341
2342 ConsumableAutoCastAttr *clone(ASTContext &C) const;
2343 void printPretty(raw_ostream &OS,
2344 const PrintingPolicy &Policy) const;
2345 const char *getSpelling() const;
2346
2347
2348 static bool classof(const Attr *A) { return A->getKind() == attr::ConsumableAutoCast; }
2349};
2350
2351class ConsumableSetOnReadAttr : public InheritableAttr {
2352public:
2353 static ConsumableSetOnReadAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
2354 auto *A = new (Ctx) ConsumableSetOnReadAttr(Loc, Ctx, 0);
2355 A->setImplicit(true);
2356 return A;
2357 }
2358
2359 ConsumableSetOnReadAttr(SourceRange R, ASTContext &Ctx
2360 , unsigned SI
2361 )
2362 : InheritableAttr(attr::ConsumableSetOnRead, R, SI, false, false)
2363 {
2364 }
2365
2366 ConsumableSetOnReadAttr *clone(ASTContext &C) const;
2367 void printPretty(raw_ostream &OS,
2368 const PrintingPolicy &Policy) const;
2369 const char *getSpelling() const;
2370
2371
2372 static bool classof(const Attr *A) { return A->getKind() == attr::ConsumableSetOnRead; }
2373};
2374
2375class ConvergentAttr : public InheritableAttr {
2376public:
2377 static ConvergentAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
2378 auto *A = new (Ctx) ConvergentAttr(Loc, Ctx, 0);
2379 A->setImplicit(true);
2380 return A;
2381 }
2382
2383 ConvergentAttr(SourceRange R, ASTContext &Ctx
2384 , unsigned SI
2385 )
2386 : InheritableAttr(attr::Convergent, R, SI, false, false)
2387 {
2388 }
2389
2390 ConvergentAttr *clone(ASTContext &C) const;
2391 void printPretty(raw_ostream &OS,
2392 const PrintingPolicy &Policy) const;
2393 const char *getSpelling() const;
2394
2395
2396 static bool classof(const Attr *A) { return A->getKind() == attr::Convergent; }
2397};
2398
2399class DLLExportAttr : public InheritableAttr {
2400public:
2401 static DLLExportAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
2402 auto *A = new (Ctx) DLLExportAttr(Loc, Ctx, 0);
2403 A->setImplicit(true);
2404 return A;
2405 }
2406
2407 DLLExportAttr(SourceRange R, ASTContext &Ctx
2408 , unsigned SI
2409 )
2410 : InheritableAttr(attr::DLLExport, R, SI, false, false)
2411 {
2412 }
2413
2414 DLLExportAttr *clone(ASTContext &C) const;
2415 void printPretty(raw_ostream &OS,
2416 const PrintingPolicy &Policy) const;
2417 const char *getSpelling() const;
2418
2419
2420 static bool classof(const Attr *A) { return A->getKind() == attr::DLLExport; }
2421};
2422
2423class DLLImportAttr : public InheritableAttr {
2424public:
2425 static DLLImportAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
2426 auto *A = new (Ctx) DLLImportAttr(Loc, Ctx, 0);
2427 A->setImplicit(true);
2428 return A;
2429 }
2430
2431 DLLImportAttr(SourceRange R, ASTContext &Ctx
2432 , unsigned SI
2433 )
2434 : InheritableAttr(attr::DLLImport, R, SI, false, false)
2435 {
2436 }
2437
2438 DLLImportAttr *clone(ASTContext &C) const;
2439 void printPretty(raw_ostream &OS,
2440 const PrintingPolicy &Policy) const;
2441 const char *getSpelling() const;
2442
2443
2444 static bool classof(const Attr *A) { return A->getKind() == attr::DLLImport; }
2445};
2446
2447class DeprecatedAttr : public InheritableAttr {
2448unsigned messageLength;
2449char *message;
2450
2451unsigned replacementLength;
2452char *replacement;
2453
2454public:
2455 static DeprecatedAttr *CreateImplicit(ASTContext &Ctx, llvm::StringRef Message, llvm::StringRef Replacement, SourceRange Loc = SourceRange()) {
2456 auto *A = new (Ctx) DeprecatedAttr(Loc, Ctx, Message, Replacement, 0);
2457 A->setImplicit(true);
2458 return A;
2459 }
2460
2461 DeprecatedAttr(SourceRange R, ASTContext &Ctx
2462 , llvm::StringRef Message
2463 , llvm::StringRef Replacement
2464 , unsigned SI
2465 )
2466 : InheritableAttr(attr::Deprecated, R, SI, false, false)
2467 , messageLength(Message.size()),message(new (Ctx, 1) char[messageLength])
2468 , replacementLength(Replacement.size()),replacement(new (Ctx, 1) char[replacementLength])
2469 {
2470 if (!Message.empty())
2471 std::memcpy(message, Message.data(), messageLength);
2472 if (!Replacement.empty())
2473 std::memcpy(replacement, Replacement.data(), replacementLength);
2474 }
2475
2476 DeprecatedAttr(SourceRange R, ASTContext &Ctx
2477 , unsigned SI
2478 )
2479 : InheritableAttr(attr::Deprecated, R, SI, false, false)
2480 , messageLength(0),message(nullptr)
2481 , replacementLength(0),replacement(nullptr)
2482 {
2483 }
2484
2485 DeprecatedAttr *clone(ASTContext &C) const;
2486 void printPretty(raw_ostream &OS,
2487 const PrintingPolicy &Policy) const;
2488 const char *getSpelling() const;
2489 llvm::StringRef getMessage() const {
2490 return llvm::StringRef(message, messageLength);
2491 }
2492 unsigned getMessageLength() const {
2493 return messageLength;
2494 }
2495 void setMessage(ASTContext &C, llvm::StringRef S) {
2496 messageLength = S.size();
2497 this->message = new (C, 1) char [messageLength];
2498 if (!S.empty())
2499 std::memcpy(this->message, S.data(), messageLength);
2500 }
2501
2502 llvm::StringRef getReplacement() const {
2503 return llvm::StringRef(replacement, replacementLength);
2504 }
2505 unsigned getReplacementLength() const {
2506 return replacementLength;
2507 }
2508 void setReplacement(ASTContext &C, llvm::StringRef S) {
2509 replacementLength = S.size();
2510 this->replacement = new (C, 1) char [replacementLength];
2511 if (!S.empty())
2512 std::memcpy(this->replacement, S.data(), replacementLength);
2513 }
2514
2515
2516
2517 static bool classof(const Attr *A) { return A->getKind() == attr::Deprecated; }
2518};
2519
2520class DestructorAttr : public InheritableAttr {
2521int priority;
2522
2523public:
2524 static DestructorAttr *CreateImplicit(ASTContext &Ctx, int Priority, SourceRange Loc = SourceRange()) {
2525 auto *A = new (Ctx) DestructorAttr(Loc, Ctx, Priority, 0);
2526 A->setImplicit(true);
2527 return A;
2528 }
2529
2530 DestructorAttr(SourceRange R, ASTContext &Ctx
2531 , int Priority
2532 , unsigned SI
2533 )
2534 : InheritableAttr(attr::Destructor, R, SI, false, false)
2535 , priority(Priority)
2536 {
2537 }
2538
2539 DestructorAttr(SourceRange R, ASTContext &Ctx
2540 , unsigned SI
2541 )
2542 : InheritableAttr(attr::Destructor, R, SI, false, false)
2543 , priority()
2544 {
2545 }
2546
2547 DestructorAttr *clone(ASTContext &C) const;
2548 void printPretty(raw_ostream &OS,
2549 const PrintingPolicy &Policy) const;
2550 const char *getSpelling() const;
2551 int getPriority() const {
2552 return priority;
2553 }
2554
2555 static const int DefaultPriority = 65535;
2556
2557
2558
2559 static bool classof(const Attr *A) { return A->getKind() == attr::Destructor; }
2560};
2561
2562class DiagnoseIfAttr : public InheritableAttr {
2563Expr * cond;
2564
2565unsigned messageLength;
2566char *message;
2567
2568public:
2569 enum DiagnosticType {
2570 DT_Error,
2571 DT_Warning
2572 };
2573private:
2574 DiagnosticType diagnosticType;
2575
2576bool argDependent;
2577
2578NamedDecl * parent;
2579
2580public:
2581 static DiagnoseIfAttr *CreateImplicit(ASTContext &Ctx, Expr * Cond, llvm::StringRef Message, DiagnosticType DiagnosticType, bool ArgDependent, NamedDecl * Parent, SourceRange Loc = SourceRange()) {
2582 auto *A = new (Ctx) DiagnoseIfAttr(Loc, Ctx, Cond, Message, DiagnosticType, ArgDependent, Parent, 0);
2583 A->setImplicit(true);
2584 return A;
2585 }
2586
2587 static DiagnoseIfAttr *CreateImplicit(ASTContext &Ctx, Expr * Cond, llvm::StringRef Message, DiagnosticType DiagnosticType, SourceRange Loc = SourceRange()) {
2588 auto *A = new (Ctx) DiagnoseIfAttr(Loc, Ctx, Cond, Message, DiagnosticType, 0);
2589 A->setImplicit(true);
2590 return A;
2591 }
2592
2593 DiagnoseIfAttr(SourceRange R, ASTContext &Ctx
2594 , Expr * Cond
2595 , llvm::StringRef Message
2596 , DiagnosticType DiagnosticType
2597 , bool ArgDependent
2598 , NamedDecl * Parent
2599 , unsigned SI
2600 )
2601 : InheritableAttr(attr::DiagnoseIf, R, SI, true, true)
2602 , cond(Cond)
2603 , messageLength(Message.size()),message(new (Ctx, 1) char[messageLength])
2604 , diagnosticType(DiagnosticType)
2605 , argDependent(ArgDependent)
2606 , parent(Parent)
2607 {
2608 if (!Message.empty())
2609 std::memcpy(message, Message.data(), messageLength);
2610 }
2611
2612 DiagnoseIfAttr(SourceRange R, ASTContext &Ctx
2613 , Expr * Cond
2614 , llvm::StringRef Message
2615 , DiagnosticType DiagnosticType
2616 , unsigned SI
2617 )
2618 : InheritableAttr(attr::DiagnoseIf, R, SI, true, true)
2619 , cond(Cond)
2620 , messageLength(Message.size()),message(new (Ctx, 1) char[messageLength])
2621 , diagnosticType(DiagnosticType)
2622 , argDependent()
2623 , parent()
2624 {
2625 if (!Message.empty())
2626 std::memcpy(message, Message.data(), messageLength);
2627 }
2628
2629 DiagnoseIfAttr *clone(ASTContext &C) const;
2630 void printPretty(raw_ostream &OS,
2631 const PrintingPolicy &Policy) const;
2632 const char *getSpelling() const;
2633 Expr * getCond() const {
2634 return cond;
2635 }
2636
2637 llvm::StringRef getMessage() const {
2638 return llvm::StringRef(message, messageLength);
2639 }
2640 unsigned getMessageLength() const {
2641 return messageLength;
2642 }
2643 void setMessage(ASTContext &C, llvm::StringRef S) {
2644 messageLength = S.size();
2645 this->message = new (C, 1) char [messageLength];
2646 if (!S.empty())
2647 std::memcpy(this->message, S.data(), messageLength);
2648 }
2649
2650 DiagnosticType getDiagnosticType() const {
2651 return diagnosticType;
2652 }
2653
2654 static bool ConvertStrToDiagnosticType(StringRef Val, DiagnosticType &Out) {
2655 Optional<DiagnosticType> R = llvm::StringSwitch<Optional<DiagnosticType>>(Val)
2656 .Case("error", DiagnoseIfAttr::DT_Error)
2657 .Case("warning", DiagnoseIfAttr::DT_Warning)
2658 .Default(Optional<DiagnosticType>());
2659 if (R) {
2660 Out = *R;
2661 return true;
2662 }
2663 return false;
2664 }
2665
2666 static const char *ConvertDiagnosticTypeToStr(DiagnosticType Val) {
2667 switch(Val) {
2668 case DiagnoseIfAttr::DT_Error: return "error";
2669 case DiagnoseIfAttr::DT_Warning: return "warning";
2670 }
2671 llvm_unreachable("No enumerator with that value")::llvm::llvm_unreachable_internal("No enumerator with that value"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 2671)
;
2672 }
2673 bool getArgDependent() const {
2674 return argDependent;
2675 }
2676
2677 NamedDecl * getParent() const {
2678 return parent;
2679 }
2680
2681
2682 bool isError() const { return diagnosticType == DT_Error; }
2683 bool isWarning() const { return diagnosticType == DT_Warning; }
2684
2685
2686 static bool classof(const Attr *A) { return A->getKind() == attr::DiagnoseIf; }
2687};
2688
2689class DisableTailCallsAttr : public InheritableAttr {
2690public:
2691 static DisableTailCallsAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
2692 auto *A = new (Ctx) DisableTailCallsAttr(Loc, Ctx, 0);
2693 A->setImplicit(true);
2694 return A;
2695 }
2696
2697 DisableTailCallsAttr(SourceRange R, ASTContext &Ctx
2698 , unsigned SI
2699 )
2700 : InheritableAttr(attr::DisableTailCalls, R, SI, false, false)
2701 {
2702 }
2703
2704 DisableTailCallsAttr *clone(ASTContext &C) const;
2705 void printPretty(raw_ostream &OS,
2706 const PrintingPolicy &Policy) const;
2707 const char *getSpelling() const;
2708
2709
2710 static bool classof(const Attr *A) { return A->getKind() == attr::DisableTailCalls; }
2711};
2712
2713class EmptyBasesAttr : public InheritableAttr {
2714public:
2715 static EmptyBasesAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
2716 auto *A = new (Ctx) EmptyBasesAttr(Loc, Ctx, 0);
2717 A->setImplicit(true);
2718 return A;
2719 }
2720
2721 EmptyBasesAttr(SourceRange R, ASTContext &Ctx
2722 , unsigned SI
2723 )
2724 : InheritableAttr(attr::EmptyBases, R, SI, false, false)
2725 {
2726 }
2727
2728 EmptyBasesAttr *clone(ASTContext &C) const;
2729 void printPretty(raw_ostream &OS,
2730 const PrintingPolicy &Policy) const;
2731 const char *getSpelling() const;
2732
2733
2734 static bool classof(const Attr *A) { return A->getKind() == attr::EmptyBases; }
2735};
2736
2737class EnableIfAttr : public InheritableAttr {
2738Expr * cond;
2739
2740unsigned messageLength;
2741char *message;
2742
2743public:
2744 static EnableIfAttr *CreateImplicit(ASTContext &Ctx, Expr * Cond, llvm::StringRef Message, SourceRange Loc = SourceRange()) {
2745 auto *A = new (Ctx) EnableIfAttr(Loc, Ctx, Cond, Message, 0);
2746 A->setImplicit(true);
2747 return A;
2748 }
2749
2750 EnableIfAttr(SourceRange R, ASTContext &Ctx
2751 , Expr * Cond
2752 , llvm::StringRef Message
2753 , unsigned SI
2754 )
2755 : InheritableAttr(attr::EnableIf, R, SI, false, false)
2756 , cond(Cond)
2757 , messageLength(Message.size()),message(new (Ctx, 1) char[messageLength])
2758 {
2759 if (!Message.empty())
2760 std::memcpy(message, Message.data(), messageLength);
2761 }
2762
2763 EnableIfAttr *clone(ASTContext &C) const;
2764 void printPretty(raw_ostream &OS,
2765 const PrintingPolicy &Policy) const;
2766 const char *getSpelling() const;
2767 Expr * getCond() const {
2768 return cond;
2769 }
2770
2771 llvm::StringRef getMessage() const {
2772 return llvm::StringRef(message, messageLength);
2773 }
2774 unsigned getMessageLength() const {
2775 return messageLength;
2776 }
2777 void setMessage(ASTContext &C, llvm::StringRef S) {
2778 messageLength = S.size();
2779 this->message = new (C, 1) char [messageLength];
2780 if (!S.empty())
2781 std::memcpy(this->message, S.data(), messageLength);
2782 }
2783
2784
2785
2786 static bool classof(const Attr *A) { return A->getKind() == attr::EnableIf; }
2787};
2788
2789class EnumExtensibilityAttr : public InheritableAttr {
2790public:
2791 enum Kind {
2792 Closed,
2793 Open
2794 };
2795private:
2796 Kind extensibility;
2797
2798public:
2799 static EnumExtensibilityAttr *CreateImplicit(ASTContext &Ctx, Kind Extensibility, SourceRange Loc = SourceRange()) {
2800 auto *A = new (Ctx) EnumExtensibilityAttr(Loc, Ctx, Extensibility, 0);
2801 A->setImplicit(true);
2802 return A;
2803 }
2804
2805 EnumExtensibilityAttr(SourceRange R, ASTContext &Ctx
2806 , Kind Extensibility
2807 , unsigned SI
2808 )
2809 : InheritableAttr(attr::EnumExtensibility, R, SI, false, false)
2810 , extensibility(Extensibility)
2811 {
2812 }
2813
2814 EnumExtensibilityAttr *clone(ASTContext &C) const;
2815 void printPretty(raw_ostream &OS,
2816 const PrintingPolicy &Policy) const;
2817 const char *getSpelling() const;
2818 Kind getExtensibility() const {
2819 return extensibility;
2820 }
2821
2822 static bool ConvertStrToKind(StringRef Val, Kind &Out) {
2823 Optional<Kind> R = llvm::StringSwitch<Optional<Kind>>(Val)
2824 .Case("closed", EnumExtensibilityAttr::Closed)
2825 .Case("open", EnumExtensibilityAttr::Open)
2826 .Default(Optional<Kind>());
2827 if (R) {
2828 Out = *R;
2829 return true;
2830 }
2831 return false;
2832 }
2833
2834 static const char *ConvertKindToStr(Kind Val) {
2835 switch(Val) {
2836 case EnumExtensibilityAttr::Closed: return "closed";
2837 case EnumExtensibilityAttr::Open: return "open";
2838 }
2839 llvm_unreachable("No enumerator with that value")::llvm::llvm_unreachable_internal("No enumerator with that value"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 2839)
;
2840 }
2841
2842
2843 static bool classof(const Attr *A) { return A->getKind() == attr::EnumExtensibility; }
2844};
2845
2846class ExclusiveTrylockFunctionAttr : public InheritableAttr {
2847Expr * successValue;
2848
2849 unsigned args_Size;
2850 Expr * *args_;
2851
2852public:
2853 static ExclusiveTrylockFunctionAttr *CreateImplicit(ASTContext &Ctx, Expr * SuccessValue, Expr * *Args, unsigned ArgsSize, SourceRange Loc = SourceRange()) {
2854 auto *A = new (Ctx) ExclusiveTrylockFunctionAttr(Loc, Ctx, SuccessValue, Args, ArgsSize, 0);
2855 A->setImplicit(true);
2856 return A;
2857 }
2858
2859 ExclusiveTrylockFunctionAttr(SourceRange R, ASTContext &Ctx
2860 , Expr * SuccessValue
2861 , Expr * *Args, unsigned ArgsSize
2862 , unsigned SI
2863 )
2864 : InheritableAttr(attr::ExclusiveTrylockFunction, R, SI, true, true)
2865 , successValue(SuccessValue)
2866 , args_Size(ArgsSize), args_(new (Ctx, 16) Expr *[args_Size])
2867 {
2868 std::copy(Args, Args + args_Size, args_);
2869 }
2870
2871 ExclusiveTrylockFunctionAttr(SourceRange R, ASTContext &Ctx
2872 , Expr * SuccessValue
2873 , unsigned SI
2874 )
2875 : InheritableAttr(attr::ExclusiveTrylockFunction, R, SI, true, true)
2876 , successValue(SuccessValue)
2877 , args_Size(0), args_(nullptr)
2878 {
2879 }
2880
2881 ExclusiveTrylockFunctionAttr *clone(ASTContext &C) const;
2882 void printPretty(raw_ostream &OS,
2883 const PrintingPolicy &Policy) const;
2884 const char *getSpelling() const;
2885 Expr * getSuccessValue() const {
2886 return successValue;
2887 }
2888
2889 typedef Expr ** args_iterator;
2890 args_iterator args_begin() const { return args_; }
2891 args_iterator args_end() const { return args_ + args_Size; }
2892 unsigned args_size() const { return args_Size; }
2893 llvm::iterator_range<args_iterator> args() const { return llvm::make_range(args_begin(), args_end()); }
2894
2895
2896
2897
2898 static bool classof(const Attr *A) { return A->getKind() == attr::ExclusiveTrylockFunction; }
2899};
2900
2901class ExternalSourceSymbolAttr : public InheritableAttr {
2902unsigned languageLength;
2903char *language;
2904
2905unsigned definedInLength;
2906char *definedIn;
2907
2908bool generatedDeclaration;
2909
2910public:
2911 static ExternalSourceSymbolAttr *CreateImplicit(ASTContext &Ctx, llvm::StringRef Language, llvm::StringRef DefinedIn, bool GeneratedDeclaration, SourceRange Loc = SourceRange()) {
2912 auto *A = new (Ctx) ExternalSourceSymbolAttr(Loc, Ctx, Language, DefinedIn, GeneratedDeclaration, 0);
2913 A->setImplicit(true);
2914 return A;
2915 }
2916
2917 ExternalSourceSymbolAttr(SourceRange R, ASTContext &Ctx
2918 , llvm::StringRef Language
2919 , llvm::StringRef DefinedIn
2920 , bool GeneratedDeclaration
2921 , unsigned SI
2922 )
2923 : InheritableAttr(attr::ExternalSourceSymbol, R, SI, false, false)
2924 , languageLength(Language.size()),language(new (Ctx, 1) char[languageLength])
2925 , definedInLength(DefinedIn.size()),definedIn(new (Ctx, 1) char[definedInLength])
2926 , generatedDeclaration(GeneratedDeclaration)
2927 {
2928 if (!Language.empty())
2929 std::memcpy(language, Language.data(), languageLength);
2930 if (!DefinedIn.empty())
2931 std::memcpy(definedIn, DefinedIn.data(), definedInLength);
2932 }
2933
2934 ExternalSourceSymbolAttr(SourceRange R, ASTContext &Ctx
2935 , unsigned SI
2936 )
2937 : InheritableAttr(attr::ExternalSourceSymbol, R, SI, false, false)
2938 , languageLength(0),language(nullptr)
2939 , definedInLength(0),definedIn(nullptr)
2940 , generatedDeclaration()
2941 {
2942 }
2943
2944 ExternalSourceSymbolAttr *clone(ASTContext &C) const;
2945 void printPretty(raw_ostream &OS,
2946 const PrintingPolicy &Policy) const;
2947 const char *getSpelling() const;
2948 llvm::StringRef getLanguage() const {
2949 return llvm::StringRef(language, languageLength);
2950 }
2951 unsigned getLanguageLength() const {
2952 return languageLength;
2953 }
2954 void setLanguage(ASTContext &C, llvm::StringRef S) {
2955 languageLength = S.size();
2956 this->language = new (C, 1) char [languageLength];
2957 if (!S.empty())
2958 std::memcpy(this->language, S.data(), languageLength);
2959 }
2960
2961 llvm::StringRef getDefinedIn() const {
2962 return llvm::StringRef(definedIn, definedInLength);
2963 }
2964 unsigned getDefinedInLength() const {
2965 return definedInLength;
2966 }
2967 void setDefinedIn(ASTContext &C, llvm::StringRef S) {
2968 definedInLength = S.size();
2969 this->definedIn = new (C, 1) char [definedInLength];
2970 if (!S.empty())
2971 std::memcpy(this->definedIn, S.data(), definedInLength);
2972 }
2973
2974 bool getGeneratedDeclaration() const {
2975 return generatedDeclaration;
2976 }
2977
2978
2979
2980 static bool classof(const Attr *A) { return A->getKind() == attr::ExternalSourceSymbol; }
2981};
2982
2983class FallThroughAttr : public StmtAttr {
2984public:
2985 static FallThroughAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
2986 auto *A = new (Ctx) FallThroughAttr(Loc, Ctx, 0);
2987 A->setImplicit(true);
2988 return A;
2989 }
2990
2991 FallThroughAttr(SourceRange R, ASTContext &Ctx
2992 , unsigned SI
2993 )
2994 : StmtAttr(attr::FallThrough, R, SI, false)
2995 {
2996 }
2997
2998 FallThroughAttr *clone(ASTContext &C) const;
2999 void printPretty(raw_ostream &OS,
3000 const PrintingPolicy &Policy) const;
3001 const char *getSpelling() const;
3002
3003
3004 static bool classof(const Attr *A) { return A->getKind() == attr::FallThrough; }
3005};
3006
3007class FastCallAttr : public InheritableAttr {
3008public:
3009 static FastCallAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
3010 auto *A = new (Ctx) FastCallAttr(Loc, Ctx, 0);
3011 A->setImplicit(true);
3012 return A;
3013 }
3014
3015 FastCallAttr(SourceRange R, ASTContext &Ctx
3016 , unsigned SI
3017 )
3018 : InheritableAttr(attr::FastCall, R, SI, false, false)
3019 {
3020 }
3021
3022 FastCallAttr *clone(ASTContext &C) const;
3023 void printPretty(raw_ostream &OS,
3024 const PrintingPolicy &Policy) const;
3025 const char *getSpelling() const;
3026
3027
3028 static bool classof(const Attr *A) { return A->getKind() == attr::FastCall; }
3029};
3030
3031class FinalAttr : public InheritableAttr {
3032public:
3033 enum Spelling {
3034 Keyword_final = 0,
3035 Keyword_sealed = 1
3036 };
3037
3038 static FinalAttr *CreateImplicit(ASTContext &Ctx, Spelling S, SourceRange Loc = SourceRange()) {
3039 auto *A = new (Ctx) FinalAttr(Loc, Ctx, S);
3040 A->setImplicit(true);
3041 return A;
3042 }
3043
3044 FinalAttr(SourceRange R, ASTContext &Ctx
3045 , unsigned SI
3046 )
3047 : InheritableAttr(attr::Final, R, SI, false, false)
3048 {
3049 }
3050
3051 FinalAttr *clone(ASTContext &C) const;
3052 void printPretty(raw_ostream &OS,
3053 const PrintingPolicy &Policy) const;
3054 const char *getSpelling() const;
3055 Spelling getSemanticSpelling() const {
3056 switch (SpellingListIndex) {
3057 default: llvm_unreachable("Unknown spelling list index")::llvm::llvm_unreachable_internal("Unknown spelling list index"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 3057)
;
3058 case 0: return Keyword_final;
3059 case 1: return Keyword_sealed;
3060 }
3061 }
3062 bool isSpelledAsSealed() const { return SpellingListIndex == 1; }
3063
3064
3065 static bool classof(const Attr *A) { return A->getKind() == attr::Final; }
3066};
3067
3068class FlagEnumAttr : public InheritableAttr {
3069public:
3070 static FlagEnumAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
3071 auto *A = new (Ctx) FlagEnumAttr(Loc, Ctx, 0);
3072 A->setImplicit(true);
3073 return A;
3074 }
3075
3076 FlagEnumAttr(SourceRange R, ASTContext &Ctx
3077 , unsigned SI
3078 )
3079 : InheritableAttr(attr::FlagEnum, R, SI, false, false)
3080 {
3081 }
3082
3083 FlagEnumAttr *clone(ASTContext &C) const;
3084 void printPretty(raw_ostream &OS,
3085 const PrintingPolicy &Policy) const;
3086 const char *getSpelling() const;
3087
3088
3089 static bool classof(const Attr *A) { return A->getKind() == attr::FlagEnum; }
3090};
3091
3092class FlattenAttr : public InheritableAttr {
3093public:
3094 static FlattenAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
3095 auto *A = new (Ctx) FlattenAttr(Loc, Ctx, 0);
3096 A->setImplicit(true);
3097 return A;
3098 }
3099
3100 FlattenAttr(SourceRange R, ASTContext &Ctx
3101 , unsigned SI
3102 )
3103 : InheritableAttr(attr::Flatten, R, SI, false, false)
3104 {
3105 }
3106
3107 FlattenAttr *clone(ASTContext &C) const;
3108 void printPretty(raw_ostream &OS,
3109 const PrintingPolicy &Policy) const;
3110 const char *getSpelling() const;
3111
3112
3113 static bool classof(const Attr *A) { return A->getKind() == attr::Flatten; }
3114};
3115
3116class FormatAttr : public InheritableAttr {
3117IdentifierInfo * type;
3118
3119int formatIdx;
3120
3121int firstArg;
3122
3123public:
3124 static FormatAttr *CreateImplicit(ASTContext &Ctx, IdentifierInfo * Type, int FormatIdx, int FirstArg, SourceRange Loc = SourceRange()) {
3125 auto *A = new (Ctx) FormatAttr(Loc, Ctx, Type, FormatIdx, FirstArg, 0);
3126 A->setImplicit(true);
3127 return A;
3128 }
3129
3130 FormatAttr(SourceRange R, ASTContext &Ctx
3131 , IdentifierInfo * Type
3132 , int FormatIdx
3133 , int FirstArg
3134 , unsigned SI
3135 )
3136 : InheritableAttr(attr::Format, R, SI, false, false)
3137 , type(Type)
3138 , formatIdx(FormatIdx)
3139 , firstArg(FirstArg)
3140 {
3141 }
3142
3143 FormatAttr *clone(ASTContext &C) const;
3144 void printPretty(raw_ostream &OS,
3145 const PrintingPolicy &Policy) const;
3146 const char *getSpelling() const;
3147 IdentifierInfo * getType() const {
3148 return type;
3149 }
3150
3151 int getFormatIdx() const {
3152 return formatIdx;
3153 }
3154
3155 int getFirstArg() const {
3156 return firstArg;
3157 }
3158
3159
3160
3161 static bool classof(const Attr *A) { return A->getKind() == attr::Format; }
3162};
3163
3164class FormatArgAttr : public InheritableAttr {
3165ParamIdx formatIdx;
3166
3167public:
3168 static FormatArgAttr *CreateImplicit(ASTContext &Ctx, ParamIdx FormatIdx, SourceRange Loc = SourceRange()) {
3169 auto *A = new (Ctx) FormatArgAttr(Loc, Ctx, FormatIdx, 0);
3170 A->setImplicit(true);
3171 return A;
3172 }
3173
3174 FormatArgAttr(SourceRange R, ASTContext &Ctx
3175 , ParamIdx FormatIdx
3176 , unsigned SI
3177 )
3178 : InheritableAttr(attr::FormatArg, R, SI, false, false)
3179 , formatIdx(FormatIdx)
3180 {
3181 }
3182
3183 FormatArgAttr *clone(ASTContext &C) const;
3184 void printPretty(raw_ostream &OS,
3185 const PrintingPolicy &Policy) const;
3186 const char *getSpelling() const;
3187 ParamIdx getFormatIdx() const {
3188 return formatIdx;
3189 }
3190
3191
3192
3193 static bool classof(const Attr *A) { return A->getKind() == attr::FormatArg; }
3194};
3195
3196class GNUInlineAttr : public InheritableAttr {
3197public:
3198 static GNUInlineAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
3199 auto *A = new (Ctx) GNUInlineAttr(Loc, Ctx, 0);
3200 A->setImplicit(true);
3201 return A;
3202 }
3203
3204 GNUInlineAttr(SourceRange R, ASTContext &Ctx
3205 , unsigned SI
3206 )
3207 : InheritableAttr(attr::GNUInline, R, SI, false, false)
3208 {
3209 }
3210
3211 GNUInlineAttr *clone(ASTContext &C) const;
3212 void printPretty(raw_ostream &OS,
3213 const PrintingPolicy &Policy) const;
3214 const char *getSpelling() const;
3215
3216
3217 static bool classof(const Attr *A) { return A->getKind() == attr::GNUInline; }
3218};
3219
3220class GuardedByAttr : public InheritableAttr {
3221Expr * arg;
3222
3223public:
3224 static GuardedByAttr *CreateImplicit(ASTContext &Ctx, Expr * Arg, SourceRange Loc = SourceRange()) {
3225 auto *A = new (Ctx) GuardedByAttr(Loc, Ctx, Arg, 0);
3226 A->setImplicit(true);
3227 return A;
3228 }
3229
3230 GuardedByAttr(SourceRange R, ASTContext &Ctx
3231 , Expr * Arg
3232 , unsigned SI
3233 )
3234 : InheritableAttr(attr::GuardedBy, R, SI, true, true)
3235 , arg(Arg)
3236 {
3237 }
3238
3239 GuardedByAttr *clone(ASTContext &C) const;
3240 void printPretty(raw_ostream &OS,
3241 const PrintingPolicy &Policy) const;
3242 const char *getSpelling() const;
3243 Expr * getArg() const {
3244 return arg;
3245 }
3246
3247
3248
3249 static bool classof(const Attr *A) { return A->getKind() == attr::GuardedBy; }
3250};
3251
3252class GuardedVarAttr : public InheritableAttr {
3253public:
3254 static GuardedVarAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
3255 auto *A = new (Ctx) GuardedVarAttr(Loc, Ctx, 0);
3256 A->setImplicit(true);
3257 return A;
3258 }
3259
3260 GuardedVarAttr(SourceRange R, ASTContext &Ctx
3261 , unsigned SI
3262 )
3263 : InheritableAttr(attr::GuardedVar, R, SI, false, false)
3264 {
3265 }
3266
3267 GuardedVarAttr *clone(ASTContext &C) const;
3268 void printPretty(raw_ostream &OS,
3269 const PrintingPolicy &Policy) const;
3270 const char *getSpelling() const;
3271
3272
3273 static bool classof(const Attr *A) { return A->getKind() == attr::GuardedVar; }
3274};
3275
3276class HotAttr : public InheritableAttr {
3277public:
3278 static HotAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
3279 auto *A = new (Ctx) HotAttr(Loc, Ctx, 0);
3280 A->setImplicit(true);
3281 return A;
3282 }
3283
3284 HotAttr(SourceRange R, ASTContext &Ctx
3285 , unsigned SI
3286 )
3287 : InheritableAttr(attr::Hot, R, SI, false, false)
3288 {
3289 }
3290
3291 HotAttr *clone(ASTContext &C) const;
3292 void printPretty(raw_ostream &OS,
3293 const PrintingPolicy &Policy) const;
3294 const char *getSpelling() const;
3295
3296
3297 static bool classof(const Attr *A) { return A->getKind() == attr::Hot; }
3298};
3299
3300class IBActionAttr : public InheritableAttr {
3301public:
3302 static IBActionAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
3303 auto *A = new (Ctx) IBActionAttr(Loc, Ctx, 0);
3304 A->setImplicit(true);
3305 return A;
3306 }
3307
3308 IBActionAttr(SourceRange R, ASTContext &Ctx
3309 , unsigned SI
3310 )
3311 : InheritableAttr(attr::IBAction, R, SI, false, false)
3312 {
3313 }
3314
3315 IBActionAttr *clone(ASTContext &C) const;
3316 void printPretty(raw_ostream &OS,
3317 const PrintingPolicy &Policy) const;
3318 const char *getSpelling() const;
3319
3320
3321 static bool classof(const Attr *A) { return A->getKind() == attr::IBAction; }
3322};
3323
3324class IBOutletAttr : public InheritableAttr {
3325public:
3326 static IBOutletAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
3327 auto *A = new (Ctx) IBOutletAttr(Loc, Ctx, 0);
3328 A->setImplicit(true);
3329 return A;
3330 }
3331
3332 IBOutletAttr(SourceRange R, ASTContext &Ctx
3333 , unsigned SI
3334 )
3335 : InheritableAttr(attr::IBOutlet, R, SI, false, false)
3336 {
3337 }
3338
3339 IBOutletAttr *clone(ASTContext &C) const;
3340 void printPretty(raw_ostream &OS,
3341 const PrintingPolicy &Policy) const;
3342 const char *getSpelling() const;
3343
3344
3345 static bool classof(const Attr *A) { return A->getKind() == attr::IBOutlet; }
3346};
3347
3348class IBOutletCollectionAttr : public InheritableAttr {
3349TypeSourceInfo * interface_;
3350
3351public:
3352 static IBOutletCollectionAttr *CreateImplicit(ASTContext &Ctx, TypeSourceInfo * Interface, SourceRange Loc = SourceRange()) {
3353 auto *A = new (Ctx) IBOutletCollectionAttr(Loc, Ctx, Interface, 0);
3354 A->setImplicit(true);
3355 return A;
3356 }
3357
3358 IBOutletCollectionAttr(SourceRange R, ASTContext &Ctx
3359 , TypeSourceInfo * Interface
3360 , unsigned SI
3361 )
3362 : InheritableAttr(attr::IBOutletCollection, R, SI, false, false)
3363 , interface_(Interface)
3364 {
3365 }
3366
3367 IBOutletCollectionAttr(SourceRange R, ASTContext &Ctx
3368 , unsigned SI
3369 )
3370 : InheritableAttr(attr::IBOutletCollection, R, SI, false, false)
3371 , interface_()
3372 {
3373 }
3374
3375 IBOutletCollectionAttr *clone(ASTContext &C) const;
3376 void printPretty(raw_ostream &OS,
3377 const PrintingPolicy &Policy) const;
3378 const char *getSpelling() const;
3379 QualType getInterface() const {
3380 return interface_->getType();
3381 } TypeSourceInfo * getInterfaceLoc() const {
3382 return interface_;
3383 }
3384
3385
3386
3387 static bool classof(const Attr *A) { return A->getKind() == attr::IBOutletCollection; }
3388};
3389
3390class IFuncAttr : public Attr {
3391unsigned resolverLength;
3392char *resolver;
3393
3394public:
3395 static IFuncAttr *CreateImplicit(ASTContext &Ctx, llvm::StringRef Resolver, SourceRange Loc = SourceRange()) {
3396 auto *A = new (Ctx) IFuncAttr(Loc, Ctx, Resolver, 0);
3397 A->setImplicit(true);
3398 return A;
3399 }
3400
3401 IFuncAttr(SourceRange R, ASTContext &Ctx
3402 , llvm::StringRef Resolver
3403 , unsigned SI
3404 )
3405 : Attr(attr::IFunc, R, SI, false)
3406 , resolverLength(Resolver.size()),resolver(new (Ctx, 1) char[resolverLength])
3407 {
3408 if (!Resolver.empty())
3409 std::memcpy(resolver, Resolver.data(), resolverLength);
3410 }
3411
3412 IFuncAttr *clone(ASTContext &C) const;
3413 void printPretty(raw_ostream &OS,
3414 const PrintingPolicy &Policy) const;
3415 const char *getSpelling() const;
3416 llvm::StringRef getResolver() const {
3417 return llvm::StringRef(resolver, resolverLength);
3418 }
3419 unsigned getResolverLength() const {
3420 return resolverLength;
3421 }
3422 void setResolver(ASTContext &C, llvm::StringRef S) {
3423 resolverLength = S.size();
3424 this->resolver = new (C, 1) char [resolverLength];
3425 if (!S.empty())
3426 std::memcpy(this->resolver, S.data(), resolverLength);
3427 }
3428
3429
3430
3431 static bool classof(const Attr *A) { return A->getKind() == attr::IFunc; }
3432};
3433
3434class InitPriorityAttr : public InheritableAttr {
3435unsigned priority;
3436
3437public:
3438 static InitPriorityAttr *CreateImplicit(ASTContext &Ctx, unsigned Priority, SourceRange Loc = SourceRange()) {
3439 auto *A = new (Ctx) InitPriorityAttr(Loc, Ctx, Priority, 0);
3440 A->setImplicit(true);
3441 return A;
3442 }
3443
3444 InitPriorityAttr(SourceRange R, ASTContext &Ctx
3445 , unsigned Priority
3446 , unsigned SI
3447 )
3448 : InheritableAttr(attr::InitPriority, R, SI, false, false)
3449 , priority(Priority)
3450 {
3451 }
3452
3453 InitPriorityAttr *clone(ASTContext &C) const;
3454 void printPretty(raw_ostream &OS,
3455 const PrintingPolicy &Policy) const;
3456 const char *getSpelling() const;
3457 unsigned getPriority() const {
3458 return priority;
3459 }
3460
3461
3462
3463 static bool classof(const Attr *A) { return A->getKind() == attr::InitPriority; }
3464};
3465
3466class InitSegAttr : public Attr {
3467unsigned sectionLength;
3468char *section;
3469
3470public:
3471 static InitSegAttr *CreateImplicit(ASTContext &Ctx, llvm::StringRef Section, SourceRange Loc = SourceRange()) {
3472 auto *A = new (Ctx) InitSegAttr(Loc, Ctx, Section, 0);
3473 A->setImplicit(true);
3474 return A;
3475 }
3476
3477 InitSegAttr(SourceRange R, ASTContext &Ctx
3478 , llvm::StringRef Section
3479 , unsigned SI
3480 )
3481 : Attr(attr::InitSeg, R, SI, false)
3482 , sectionLength(Section.size()),section(new (Ctx, 1) char[sectionLength])
3483 {
3484 if (!Section.empty())
3485 std::memcpy(section, Section.data(), sectionLength);
3486 }
3487
3488 InitSegAttr *clone(ASTContext &C) const;
3489 void printPretty(raw_ostream &OS,
3490 const PrintingPolicy &Policy) const;
3491 const char *getSpelling() const;
3492 llvm::StringRef getSection() const {
3493 return llvm::StringRef(section, sectionLength);
3494 }
3495 unsigned getSectionLength() const {
3496 return sectionLength;
3497 }
3498 void setSection(ASTContext &C, llvm::StringRef S) {
3499 sectionLength = S.size();
3500 this->section = new (C, 1) char [sectionLength];
3501 if (!S.empty())
3502 std::memcpy(this->section, S.data(), sectionLength);
3503 }
3504
3505
3506 void printPrettyPragma(raw_ostream &OS, const PrintingPolicy &Policy) const {
3507 OS << " (" << getSection() << ')';
3508 }
3509
3510
3511 static bool classof(const Attr *A) { return A->getKind() == attr::InitSeg; }
3512};
3513
3514class IntelOclBiccAttr : public InheritableAttr {
3515public:
3516 static IntelOclBiccAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
3517 auto *A = new (Ctx) IntelOclBiccAttr(Loc, Ctx, 0);
3518 A->setImplicit(true);
3519 return A;
3520 }
3521
3522 IntelOclBiccAttr(SourceRange R, ASTContext &Ctx
3523 , unsigned SI
3524 )
3525 : InheritableAttr(attr::IntelOclBicc, R, SI, false, false)
3526 {
3527 }
3528
3529 IntelOclBiccAttr *clone(ASTContext &C) const;
3530 void printPretty(raw_ostream &OS,
3531 const PrintingPolicy &Policy) const;
3532 const char *getSpelling() const;
3533
3534
3535 static bool classof(const Attr *A) { return A->getKind() == attr::IntelOclBicc; }
3536};
3537
3538class InternalLinkageAttr : public InheritableAttr {
3539public:
3540 static InternalLinkageAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
3541 auto *A = new (Ctx) InternalLinkageAttr(Loc, Ctx, 0);
3542 A->setImplicit(true);
3543 return A;
3544 }
3545
3546 InternalLinkageAttr(SourceRange R, ASTContext &Ctx
3547 , unsigned SI
3548 )
3549 : InheritableAttr(attr::InternalLinkage, R, SI, false, false)
3550 {
3551 }
3552
3553 InternalLinkageAttr *clone(ASTContext &C) const;
3554 void printPretty(raw_ostream &OS,
3555 const PrintingPolicy &Policy) const;
3556 const char *getSpelling() const;
3557
3558
3559 static bool classof(const Attr *A) { return A->getKind() == attr::InternalLinkage; }
3560};
3561
3562class LTOVisibilityPublicAttr : public InheritableAttr {
3563public:
3564 static LTOVisibilityPublicAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
3565 auto *A = new (Ctx) LTOVisibilityPublicAttr(Loc, Ctx, 0);
3566 A->setImplicit(true);
3567 return A;
3568 }
3569
3570 LTOVisibilityPublicAttr(SourceRange R, ASTContext &Ctx
3571 , unsigned SI
3572 )
3573 : InheritableAttr(attr::LTOVisibilityPublic, R, SI, false, false)
3574 {
3575 }
3576
3577 LTOVisibilityPublicAttr *clone(ASTContext &C) const;
3578 void printPretty(raw_ostream &OS,
3579 const PrintingPolicy &Policy) const;
3580 const char *getSpelling() const;
3581
3582
3583 static bool classof(const Attr *A) { return A->getKind() == attr::LTOVisibilityPublic; }
3584};
3585
3586class LayoutVersionAttr : public InheritableAttr {
3587unsigned version;
3588
3589public:
3590 static LayoutVersionAttr *CreateImplicit(ASTContext &Ctx, unsigned Version, SourceRange Loc = SourceRange()) {
3591 auto *A = new (Ctx) LayoutVersionAttr(Loc, Ctx, Version, 0);
3592 A->setImplicit(true);
3593 return A;
3594 }
3595
3596 LayoutVersionAttr(SourceRange R, ASTContext &Ctx
3597 , unsigned Version
3598 , unsigned SI
3599 )
3600 : InheritableAttr(attr::LayoutVersion, R, SI, false, false)
3601 , version(Version)
3602 {
3603 }
3604
3605 LayoutVersionAttr *clone(ASTContext &C) const;
3606 void printPretty(raw_ostream &OS,
3607 const PrintingPolicy &Policy) const;
3608 const char *getSpelling() const;
3609 unsigned getVersion() const {
3610 return version;
3611 }
3612
3613
3614
3615 static bool classof(const Attr *A) { return A->getKind() == attr::LayoutVersion; }
3616};
3617
3618class LockReturnedAttr : public InheritableAttr {
3619Expr * arg;
3620
3621public:
3622 static LockReturnedAttr *CreateImplicit(ASTContext &Ctx, Expr * Arg, SourceRange Loc = SourceRange()) {
3623 auto *A = new (Ctx) LockReturnedAttr(Loc, Ctx, Arg, 0);
3624 A->setImplicit(true);
3625 return A;
3626 }
3627
3628 LockReturnedAttr(SourceRange R, ASTContext &Ctx
3629 , Expr * Arg
3630 , unsigned SI
3631 )
3632 : InheritableAttr(attr::LockReturned, R, SI, true, false)
3633 , arg(Arg)
3634 {
3635 }
3636
3637 LockReturnedAttr *clone(ASTContext &C) const;
3638 void printPretty(raw_ostream &OS,
3639 const PrintingPolicy &Policy) const;
3640 const char *getSpelling() const;
3641 Expr * getArg() const {
3642 return arg;
3643 }
3644
3645
3646
3647 static bool classof(const Attr *A) { return A->getKind() == attr::LockReturned; }
3648};
3649
3650class LocksExcludedAttr : public InheritableAttr {
3651 unsigned args_Size;
3652 Expr * *args_;
3653
3654public:
3655 static LocksExcludedAttr *CreateImplicit(ASTContext &Ctx, Expr * *Args, unsigned ArgsSize, SourceRange Loc = SourceRange()) {
3656 auto *A = new (Ctx) LocksExcludedAttr(Loc, Ctx, Args, ArgsSize, 0);
3657 A->setImplicit(true);
3658 return A;
3659 }
3660
3661 LocksExcludedAttr(SourceRange R, ASTContext &Ctx
3662 , Expr * *Args, unsigned ArgsSize
3663 , unsigned SI
3664 )
3665 : InheritableAttr(attr::LocksExcluded, R, SI, true, true)
3666 , args_Size(ArgsSize), args_(new (Ctx, 16) Expr *[args_Size])
3667 {
3668 std::copy(Args, Args + args_Size, args_);
3669 }
3670
3671 LocksExcludedAttr(SourceRange R, ASTContext &Ctx
3672 , unsigned SI
3673 )
3674 : InheritableAttr(attr::LocksExcluded, R, SI, true, true)
3675 , args_Size(0), args_(nullptr)
3676 {
3677 }
3678
3679 LocksExcludedAttr *clone(ASTContext &C) const;
3680 void printPretty(raw_ostream &OS,
3681 const PrintingPolicy &Policy) const;
3682 const char *getSpelling() const;
3683 typedef Expr ** args_iterator;
3684 args_iterator args_begin() const { return args_; }
3685 args_iterator args_end() const { return args_ + args_Size; }
3686 unsigned args_size() const { return args_Size; }
3687 llvm::iterator_range<args_iterator> args() const { return llvm::make_range(args_begin(), args_end()); }
3688
3689
3690
3691
3692 static bool classof(const Attr *A) { return A->getKind() == attr::LocksExcluded; }
3693};
3694
3695class LoopHintAttr : public Attr {
3696public:
3697 enum OptionType {
3698 Vectorize,
3699 VectorizeWidth,
3700 Interleave,
3701 InterleaveCount,
3702 Unroll,
3703 UnrollCount,
3704 Distribute
3705 };
3706private:
3707 OptionType option;
3708
3709public:
3710 enum LoopHintState {
3711 Enable,
3712 Disable,
3713 Numeric,
3714 AssumeSafety,
3715 Full
3716 };
3717private:
3718 LoopHintState state;
3719
3720Expr * value;
3721
3722public:
3723 enum Spelling {
3724 Pragma_clang_loop = 0,
3725 Pragma_unroll = 1,
3726 Pragma_nounroll = 2
3727 };
3728
3729 static LoopHintAttr *CreateImplicit(ASTContext &Ctx, Spelling S, OptionType Option, LoopHintState State, Expr * Value, SourceRange Loc = SourceRange()) {
3730 auto *A = new (Ctx) LoopHintAttr(Loc, Ctx, Option, State, Value, S);
3731 A->setImplicit(true);
3732 return A;
3733 }
3734
3735 LoopHintAttr(SourceRange R, ASTContext &Ctx
3736 , OptionType Option
3737 , LoopHintState State
3738 , Expr * Value
3739 , unsigned SI
3740 )
3741 : Attr(attr::LoopHint, R, SI, false)
3742 , option(Option)
3743 , state(State)
3744 , value(Value)
3745 {
3746 }
3747
3748 LoopHintAttr *clone(ASTContext &C) const;
3749 void printPretty(raw_ostream &OS,
3750 const PrintingPolicy &Policy) const;
3751 const char *getSpelling() const;
3752 Spelling getSemanticSpelling() const {
3753 switch (SpellingListIndex) {
3754 default: llvm_unreachable("Unknown spelling list index")::llvm::llvm_unreachable_internal("Unknown spelling list index"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 3754)
;
3755 case 0: return Pragma_clang_loop;
3756 case 1: return Pragma_unroll;
3757 case 2: return Pragma_nounroll;
3758 }
3759 }
3760 OptionType getOption() const {
3761 return option;
3762 }
3763
3764 static bool ConvertStrToOptionType(StringRef Val, OptionType &Out) {
3765 Optional<OptionType> R = llvm::StringSwitch<Optional<OptionType>>(Val)
3766 .Case("vectorize", LoopHintAttr::Vectorize)
3767 .Case("vectorize_width", LoopHintAttr::VectorizeWidth)
3768 .Case("interleave", LoopHintAttr::Interleave)
3769 .Case("interleave_count", LoopHintAttr::InterleaveCount)
3770 .Case("unroll", LoopHintAttr::Unroll)
3771 .Case("unroll_count", LoopHintAttr::UnrollCount)
3772 .Case("distribute", LoopHintAttr::Distribute)
3773 .Default(Optional<OptionType>());
3774 if (R) {
3775 Out = *R;
3776 return true;
3777 }
3778 return false;
3779 }
3780
3781 static const char *ConvertOptionTypeToStr(OptionType Val) {
3782 switch(Val) {
3783 case LoopHintAttr::Vectorize: return "vectorize";
3784 case LoopHintAttr::VectorizeWidth: return "vectorize_width";
3785 case LoopHintAttr::Interleave: return "interleave";
3786 case LoopHintAttr::InterleaveCount: return "interleave_count";
3787 case LoopHintAttr::Unroll: return "unroll";
3788 case LoopHintAttr::UnrollCount: return "unroll_count";
3789 case LoopHintAttr::Distribute: return "distribute";
3790 }
3791 llvm_unreachable("No enumerator with that value")::llvm::llvm_unreachable_internal("No enumerator with that value"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 3791)
;
3792 }
3793 LoopHintState getState() const {
3794 return state;
3795 }
3796
3797 static bool ConvertStrToLoopHintState(StringRef Val, LoopHintState &Out) {
3798 Optional<LoopHintState> R = llvm::StringSwitch<Optional<LoopHintState>>(Val)
3799 .Case("enable", LoopHintAttr::Enable)
3800 .Case("disable", LoopHintAttr::Disable)
3801 .Case("numeric", LoopHintAttr::Numeric)
3802 .Case("assume_safety", LoopHintAttr::AssumeSafety)
3803 .Case("full", LoopHintAttr::Full)
3804 .Default(Optional<LoopHintState>());
3805 if (R) {
3806 Out = *R;
3807 return true;
3808 }
3809 return false;
3810 }
3811
3812 static const char *ConvertLoopHintStateToStr(LoopHintState Val) {
3813 switch(Val) {
3814 case LoopHintAttr::Enable: return "enable";
3815 case LoopHintAttr::Disable: return "disable";
3816 case LoopHintAttr::Numeric: return "numeric";
3817 case LoopHintAttr::AssumeSafety: return "assume_safety";
3818 case LoopHintAttr::Full: return "full";
3819 }
3820 llvm_unreachable("No enumerator with that value")::llvm::llvm_unreachable_internal("No enumerator with that value"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 3820)
;
3821 }
3822 Expr * getValue() const {
3823 return value;
3824 }
3825
3826
3827 static const char *getOptionName(int Option) {
3828 switch(Option) {
3829 case Vectorize: return "vectorize";
3830 case VectorizeWidth: return "vectorize_width";
3831 case Interleave: return "interleave";
3832 case InterleaveCount: return "interleave_count";
3833 case Unroll: return "unroll";
3834 case UnrollCount: return "unroll_count";
3835 case Distribute: return "distribute";
3836 }
3837 llvm_unreachable("Unhandled LoopHint option.")::llvm::llvm_unreachable_internal("Unhandled LoopHint option."
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 3837)
;
3838 }
3839
3840 void printPrettyPragma(raw_ostream &OS, const PrintingPolicy &Policy) const {
3841 unsigned SpellingIndex = getSpellingListIndex();
3842 // For "#pragma unroll" and "#pragma nounroll" the string "unroll" or
3843 // "nounroll" is already emitted as the pragma name.
3844 if (SpellingIndex == Pragma_nounroll)
3845 return;
3846 else if (SpellingIndex == Pragma_unroll) {
3847 OS << ' ' << getValueString(Policy);
3848 return;
3849 }
3850
3851 assert(SpellingIndex == Pragma_clang_loop && "Unexpected spelling")(static_cast <bool> (SpellingIndex == Pragma_clang_loop
&& "Unexpected spelling") ? void (0) : __assert_fail
("SpellingIndex == Pragma_clang_loop && \"Unexpected spelling\""
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 3851, __extension__ __PRETTY_FUNCTION__))
;
3852 OS << ' ' << getOptionName(option) << getValueString(Policy);
3853 }
3854
3855 // Return a string containing the loop hint argument including the
3856 // enclosing parentheses.
3857 std::string getValueString(const PrintingPolicy &Policy) const {
3858 std::string ValueName;
3859 llvm::raw_string_ostream OS(ValueName);
3860 OS << "(";
3861 if (state == Numeric)
3862 value->printPretty(OS, nullptr, Policy);
3863 else if (state == Enable)
3864 OS << "enable";
3865 else if (state == Full)
3866 OS << "full";
3867 else if (state == AssumeSafety)
3868 OS << "assume_safety";
3869 else
3870 OS << "disable";
3871 OS << ")";
3872 return OS.str();
3873 }
3874
3875 // Return a string suitable for identifying this attribute in diagnostics.
3876 std::string getDiagnosticName(const PrintingPolicy &Policy) const {
3877 unsigned SpellingIndex = getSpellingListIndex();
3878 if (SpellingIndex == Pragma_nounroll)
3879 return "#pragma nounroll";
3880 else if (SpellingIndex == Pragma_unroll)
3881 return "#pragma unroll" + (option == UnrollCount ? getValueString(Policy) : "");
3882
3883 assert(SpellingIndex == Pragma_clang_loop && "Unexpected spelling")(static_cast <bool> (SpellingIndex == Pragma_clang_loop
&& "Unexpected spelling") ? void (0) : __assert_fail
("SpellingIndex == Pragma_clang_loop && \"Unexpected spelling\""
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 3883, __extension__ __PRETTY_FUNCTION__))
;
3884 return getOptionName(option) + getValueString(Policy);
3885 }
3886
3887
3888 static bool classof(const Attr *A) { return A->getKind() == attr::LoopHint; }
3889};
3890
3891class MSABIAttr : public InheritableAttr {
3892public:
3893 static MSABIAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
3894 auto *A = new (Ctx) MSABIAttr(Loc, Ctx, 0);
3895 A->setImplicit(true);
3896 return A;
3897 }
3898
3899 MSABIAttr(SourceRange R, ASTContext &Ctx
3900 , unsigned SI
3901 )
3902 : InheritableAttr(attr::MSABI, R, SI, false, false)
3903 {
3904 }
3905
3906 MSABIAttr *clone(ASTContext &C) const;
3907 void printPretty(raw_ostream &OS,
3908 const PrintingPolicy &Policy) const;
3909 const char *getSpelling() const;
3910
3911
3912 static bool classof(const Attr *A) { return A->getKind() == attr::MSABI; }
3913};
3914
3915class MSInheritanceAttr : public InheritableAttr {
3916bool bestCase;
3917
3918public:
3919 enum Spelling {
3920 Keyword_single_inheritance = 0,
3921 Keyword_multiple_inheritance = 1,
3922 Keyword_virtual_inheritance = 2,
3923 Keyword_unspecified_inheritance = 3
3924 };
3925
3926 static MSInheritanceAttr *CreateImplicit(ASTContext &Ctx, Spelling S, bool BestCase, SourceRange Loc = SourceRange()) {
3927 auto *A = new (Ctx) MSInheritanceAttr(Loc, Ctx, BestCase, S);
3928 A->setImplicit(true);
3929 return A;
3930 }
3931
3932 MSInheritanceAttr(SourceRange R, ASTContext &Ctx
3933 , bool BestCase
3934 , unsigned SI
3935 )
3936 : InheritableAttr(attr::MSInheritance, R, SI, false, false)
3937 , bestCase(BestCase)
3938 {
3939 }
3940
3941 MSInheritanceAttr(SourceRange R, ASTContext &Ctx
3942 , unsigned SI
3943 )
3944 : InheritableAttr(attr::MSInheritance, R, SI, false, false)
3945 , bestCase()
3946 {
3947 }
3948
3949 MSInheritanceAttr *clone(ASTContext &C) const;
3950 void printPretty(raw_ostream &OS,
3951 const PrintingPolicy &Policy) const;
3952 const char *getSpelling() const;
3953 Spelling getSemanticSpelling() const {
3954 switch (SpellingListIndex) {
3955 default: llvm_unreachable("Unknown spelling list index")::llvm::llvm_unreachable_internal("Unknown spelling list index"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 3955)
;
3956 case 0: return Keyword_single_inheritance;
3957 case 1: return Keyword_multiple_inheritance;
3958 case 2: return Keyword_virtual_inheritance;
3959 case 3: return Keyword_unspecified_inheritance;
3960 }
3961 }
3962 bool getBestCase() const {
3963 return bestCase;
3964 }
3965
3966 static const bool DefaultBestCase = true;
3967
3968
3969 static bool hasVBPtrOffsetField(Spelling Inheritance) {
3970 return Inheritance == Keyword_unspecified_inheritance;
3971 }
3972
3973 // Only member pointers to functions need a this adjustment, since it can be
3974 // combined with the field offset for data pointers.
3975 static bool hasNVOffsetField(bool IsMemberFunction, Spelling Inheritance) {
3976 return IsMemberFunction && Inheritance >= Keyword_multiple_inheritance;
3977 }
3978
3979 static bool hasVBTableOffsetField(Spelling Inheritance) {
3980 return Inheritance >= Keyword_virtual_inheritance;
3981 }
3982
3983 static bool hasOnlyOneField(bool IsMemberFunction,
3984 Spelling Inheritance) {
3985 if (IsMemberFunction)
3986 return Inheritance <= Keyword_single_inheritance;
3987 return Inheritance <= Keyword_multiple_inheritance;
3988 }
3989
3990
3991 static bool classof(const Attr *A) { return A->getKind() == attr::MSInheritance; }
3992};
3993
3994class MSNoVTableAttr : public InheritableAttr {
3995public:
3996 static MSNoVTableAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
3997 auto *A = new (Ctx) MSNoVTableAttr(Loc, Ctx, 0);
3998 A->setImplicit(true);
3999 return A;
4000 }
4001
4002 MSNoVTableAttr(SourceRange R, ASTContext &Ctx
4003 , unsigned SI
4004 )
4005 : InheritableAttr(attr::MSNoVTable, R, SI, false, false)
4006 {
4007 }
4008
4009 MSNoVTableAttr *clone(ASTContext &C) const;
4010 void printPretty(raw_ostream &OS,
4011 const PrintingPolicy &Policy) const;
4012 const char *getSpelling() const;
4013
4014
4015 static bool classof(const Attr *A) { return A->getKind() == attr::MSNoVTable; }
4016};
4017
4018class MSP430InterruptAttr : public InheritableAttr {
4019unsigned number;
4020
4021public:
4022 static MSP430InterruptAttr *CreateImplicit(ASTContext &Ctx, unsigned Number, SourceRange Loc = SourceRange()) {
4023 auto *A = new (Ctx) MSP430InterruptAttr(Loc, Ctx, Number, 0);
4024 A->setImplicit(true);
4025 return A;
4026 }
4027
4028 MSP430InterruptAttr(SourceRange R, ASTContext &Ctx
4029 , unsigned Number
4030 , unsigned SI
4031 )
4032 : InheritableAttr(attr::MSP430Interrupt, R, SI, false, false)
4033 , number(Number)
4034 {
4035 }
4036
4037 MSP430InterruptAttr *clone(ASTContext &C) const;
4038 void printPretty(raw_ostream &OS,
4039 const PrintingPolicy &Policy) const;
4040 const char *getSpelling() const;
4041 unsigned getNumber() const {
4042 return number;
4043 }
4044
4045
4046
4047 static bool classof(const Attr *A) { return A->getKind() == attr::MSP430Interrupt; }
4048};
4049
4050class MSStructAttr : public InheritableAttr {
4051public:
4052 static MSStructAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
4053 auto *A = new (Ctx) MSStructAttr(Loc, Ctx, 0);
4054 A->setImplicit(true);
4055 return A;
4056 }
4057
4058 MSStructAttr(SourceRange R, ASTContext &Ctx
4059 , unsigned SI
4060 )
4061 : InheritableAttr(attr::MSStruct, R, SI, false, false)
4062 {
4063 }
4064
4065 MSStructAttr *clone(ASTContext &C) const;
4066 void printPretty(raw_ostream &OS,
4067 const PrintingPolicy &Policy) const;
4068 const char *getSpelling() const;
4069
4070
4071 static bool classof(const Attr *A) { return A->getKind() == attr::MSStruct; }
4072};
4073
4074class MSVtorDispAttr : public InheritableAttr {
4075unsigned vdm;
4076
4077public:
4078 static MSVtorDispAttr *CreateImplicit(ASTContext &Ctx, unsigned Vdm, SourceRange Loc = SourceRange()) {
4079 auto *A = new (Ctx) MSVtorDispAttr(Loc, Ctx, Vdm, 0);
4080 A->setImplicit(true);
4081 return A;
4082 }
4083
4084 MSVtorDispAttr(SourceRange R, ASTContext &Ctx
4085 , unsigned Vdm
4086 , unsigned SI
4087 )
4088 : InheritableAttr(attr::MSVtorDisp, R, SI, false, false)
4089 , vdm(Vdm)
4090 {
4091 }
4092
4093 MSVtorDispAttr *clone(ASTContext &C) const;
4094 void printPretty(raw_ostream &OS,
4095 const PrintingPolicy &Policy) const;
4096 const char *getSpelling() const;
4097 unsigned getVdm() const {
4098 return vdm;
4099 }
4100
4101
4102 enum Mode {
4103 Never,
4104 ForVBaseOverride,
4105 ForVFTable
4106 };
4107
4108 Mode getVtorDispMode() const { return Mode(vdm); }
4109
4110
4111 static bool classof(const Attr *A) { return A->getKind() == attr::MSVtorDisp; }
4112};
4113
4114class MaxFieldAlignmentAttr : public InheritableAttr {
4115unsigned alignment;
4116
4117public:
4118 static MaxFieldAlignmentAttr *CreateImplicit(ASTContext &Ctx, unsigned Alignment, SourceRange Loc = SourceRange()) {
4119 auto *A = new (Ctx) MaxFieldAlignmentAttr(Loc, Ctx, Alignment, 0);
4120 A->setImplicit(true);
4121 return A;
4122 }
4123
4124 MaxFieldAlignmentAttr(SourceRange R, ASTContext &Ctx
4125 , unsigned Alignment
4126 , unsigned SI
4127 )
4128 : InheritableAttr(attr::MaxFieldAlignment, R, SI, false, false)
4129 , alignment(Alignment)
4130 {
4131 }
4132
4133 MaxFieldAlignmentAttr *clone(ASTContext &C) const;
4134 void printPretty(raw_ostream &OS,
4135 const PrintingPolicy &Policy) const;
4136 const char *getSpelling() const;
4137 unsigned getAlignment() const {
4138 return alignment;
4139 }
4140
4141
4142
4143 static bool classof(const Attr *A) { return A->getKind() == attr::MaxFieldAlignment; }
4144};
4145
4146class MayAliasAttr : public InheritableAttr {
4147public:
4148 static MayAliasAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
4149 auto *A = new (Ctx) MayAliasAttr(Loc, Ctx, 0);
4150 A->setImplicit(true);
4151 return A;
4152 }
4153
4154 MayAliasAttr(SourceRange R, ASTContext &Ctx
4155 , unsigned SI
4156 )
4157 : InheritableAttr(attr::MayAlias, R, SI, false, false)
4158 {
4159 }
4160
4161 MayAliasAttr *clone(ASTContext &C) const;
4162 void printPretty(raw_ostream &OS,
4163 const PrintingPolicy &Policy) const;
4164 const char *getSpelling() const;
4165
4166
4167 static bool classof(const Attr *A) { return A->getKind() == attr::MayAlias; }
4168};
4169
4170class MicroMipsAttr : public InheritableAttr {
4171public:
4172 static MicroMipsAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
4173 auto *A = new (Ctx) MicroMipsAttr(Loc, Ctx, 0);
4174 A->setImplicit(true);
4175 return A;
4176 }
4177
4178 MicroMipsAttr(SourceRange R, ASTContext &Ctx
4179 , unsigned SI
4180 )
4181 : InheritableAttr(attr::MicroMips, R, SI, false, false)
4182 {
4183 }
4184
4185 MicroMipsAttr *clone(ASTContext &C) const;
4186 void printPretty(raw_ostream &OS,
4187 const PrintingPolicy &Policy) const;
4188 const char *getSpelling() const;
4189
4190
4191 static bool classof(const Attr *A) { return A->getKind() == attr::MicroMips; }
4192};
4193
4194class MinSizeAttr : public InheritableAttr {
4195public:
4196 static MinSizeAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
4197 auto *A = new (Ctx) MinSizeAttr(Loc, Ctx, 0);
4198 A->setImplicit(true);
4199 return A;
4200 }
4201
4202 MinSizeAttr(SourceRange R, ASTContext &Ctx
4203 , unsigned SI
4204 )
4205 : InheritableAttr(attr::MinSize, R, SI, false, false)
4206 {
4207 }
4208
4209 MinSizeAttr *clone(ASTContext &C) const;
4210 void printPretty(raw_ostream &OS,
4211 const PrintingPolicy &Policy) const;
4212 const char *getSpelling() const;
4213
4214
4215 static bool classof(const Attr *A) { return A->getKind() == attr::MinSize; }
4216};
4217
4218class Mips16Attr : public InheritableAttr {
4219public:
4220 static Mips16Attr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
4221 auto *A = new (Ctx) Mips16Attr(Loc, Ctx, 0);
4222 A->setImplicit(true);
4223 return A;
4224 }
4225
4226 Mips16Attr(SourceRange R, ASTContext &Ctx
4227 , unsigned SI
4228 )
4229 : InheritableAttr(attr::Mips16, R, SI, false, false)
4230 {
4231 }
4232
4233 Mips16Attr *clone(ASTContext &C) const;
4234 void printPretty(raw_ostream &OS,
4235 const PrintingPolicy &Policy) const;
4236 const char *getSpelling() const;
4237
4238
4239 static bool classof(const Attr *A) { return A->getKind() == attr::Mips16; }
4240};
4241
4242class MipsInterruptAttr : public InheritableAttr {
4243public:
4244 enum InterruptType {
4245 sw0,
4246 sw1,
4247 hw0,
4248 hw1,
4249 hw2,
4250 hw3,
4251 hw4,
4252 hw5,
4253 eic
4254 };
4255private:
4256 InterruptType interrupt;
4257
4258public:
4259 static MipsInterruptAttr *CreateImplicit(ASTContext &Ctx, InterruptType Interrupt, SourceRange Loc = SourceRange()) {
4260 auto *A = new (Ctx) MipsInterruptAttr(Loc, Ctx, Interrupt, 0);
4261 A->setImplicit(true);
4262 return A;
4263 }
4264
4265 MipsInterruptAttr(SourceRange R, ASTContext &Ctx
4266 , InterruptType Interrupt
4267 , unsigned SI
4268 )
4269 : InheritableAttr(attr::MipsInterrupt, R, SI, false, false)
4270 , interrupt(Interrupt)
4271 {
4272 }
4273
4274 MipsInterruptAttr *clone(ASTContext &C) const;
4275 void printPretty(raw_ostream &OS,
4276 const PrintingPolicy &Policy) const;
4277 const char *getSpelling() const;
4278 InterruptType getInterrupt() const {
4279 return interrupt;
4280 }
4281
4282 static bool ConvertStrToInterruptType(StringRef Val, InterruptType &Out) {
4283 Optional<InterruptType> R = llvm::StringSwitch<Optional<InterruptType>>(Val)
4284 .Case("vector=sw0", MipsInterruptAttr::sw0)
4285 .Case("vector=sw1", MipsInterruptAttr::sw1)
4286 .Case("vector=hw0", MipsInterruptAttr::hw0)
4287 .Case("vector=hw1", MipsInterruptAttr::hw1)
4288 .Case("vector=hw2", MipsInterruptAttr::hw2)
4289 .Case("vector=hw3", MipsInterruptAttr::hw3)
4290 .Case("vector=hw4", MipsInterruptAttr::hw4)
4291 .Case("vector=hw5", MipsInterruptAttr::hw5)
4292 .Case("eic", MipsInterruptAttr::eic)
4293 .Case("", MipsInterruptAttr::eic)
4294 .Default(Optional<InterruptType>());
4295 if (R) {
4296 Out = *R;
4297 return true;
4298 }
4299 return false;
4300 }
4301
4302 static const char *ConvertInterruptTypeToStr(InterruptType Val) {
4303 switch(Val) {
4304 case MipsInterruptAttr::sw0: return "vector=sw0";
4305 case MipsInterruptAttr::sw1: return "vector=sw1";
4306 case MipsInterruptAttr::hw0: return "vector=hw0";
4307 case MipsInterruptAttr::hw1: return "vector=hw1";
4308 case MipsInterruptAttr::hw2: return "vector=hw2";
4309 case MipsInterruptAttr::hw3: return "vector=hw3";
4310 case MipsInterruptAttr::hw4: return "vector=hw4";
4311 case MipsInterruptAttr::hw5: return "vector=hw5";
4312 case MipsInterruptAttr::eic: return "eic";
4313 }
4314 llvm_unreachable("No enumerator with that value")::llvm::llvm_unreachable_internal("No enumerator with that value"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 4314)
;
4315 }
4316
4317
4318 static bool classof(const Attr *A) { return A->getKind() == attr::MipsInterrupt; }
4319};
4320
4321class MipsLongCallAttr : public InheritableAttr {
4322public:
4323 enum Spelling {
4324 GNU_long_call = 0,
4325 CXX11_gnu_long_call = 1,
4326 GNU_far = 2,
4327 CXX11_gnu_far = 3
4328 };
4329
4330 static MipsLongCallAttr *CreateImplicit(ASTContext &Ctx, Spelling S, SourceRange Loc = SourceRange()) {
4331 auto *A = new (Ctx) MipsLongCallAttr(Loc, Ctx, S);
4332 A->setImplicit(true);
4333 return A;
4334 }
4335
4336 MipsLongCallAttr(SourceRange R, ASTContext &Ctx
4337 , unsigned SI
4338 )
4339 : InheritableAttr(attr::MipsLongCall, R, SI, false, false)
4340 {
4341 }
4342
4343 MipsLongCallAttr *clone(ASTContext &C) const;
4344 void printPretty(raw_ostream &OS,
4345 const PrintingPolicy &Policy) const;
4346 const char *getSpelling() const;
4347 Spelling getSemanticSpelling() const {
4348 switch (SpellingListIndex) {
4349 default: llvm_unreachable("Unknown spelling list index")::llvm::llvm_unreachable_internal("Unknown spelling list index"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 4349)
;
4350 case 0: return GNU_long_call;
4351 case 1: return CXX11_gnu_long_call;
4352 case 2: return GNU_far;
4353 case 3: return CXX11_gnu_far;
4354 }
4355 }
4356
4357
4358 static bool classof(const Attr *A) { return A->getKind() == attr::MipsLongCall; }
4359};
4360
4361class MipsShortCallAttr : public InheritableAttr {
4362public:
4363 enum Spelling {
4364 GNU_short_call = 0,
4365 CXX11_gnu_short_call = 1,
4366 GNU_near = 2,
4367 CXX11_gnu_near = 3
4368 };
4369
4370 static MipsShortCallAttr *CreateImplicit(ASTContext &Ctx, Spelling S, SourceRange Loc = SourceRange()) {
4371 auto *A = new (Ctx) MipsShortCallAttr(Loc, Ctx, S);
4372 A->setImplicit(true);
4373 return A;
4374 }
4375
4376 MipsShortCallAttr(SourceRange R, ASTContext &Ctx
4377 , unsigned SI
4378 )
4379 : InheritableAttr(attr::MipsShortCall, R, SI, false, false)
4380 {
4381 }
4382
4383 MipsShortCallAttr *clone(ASTContext &C) const;
4384 void printPretty(raw_ostream &OS,
4385 const PrintingPolicy &Policy) const;
4386 const char *getSpelling() const;
4387 Spelling getSemanticSpelling() const {
4388 switch (SpellingListIndex) {
4389 default: llvm_unreachable("Unknown spelling list index")::llvm::llvm_unreachable_internal("Unknown spelling list index"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 4389)
;
4390 case 0: return GNU_short_call;
4391 case 1: return CXX11_gnu_short_call;
4392 case 2: return GNU_near;
4393 case 3: return CXX11_gnu_near;
4394 }
4395 }
4396
4397
4398 static bool classof(const Attr *A) { return A->getKind() == attr::MipsShortCall; }
4399};
4400
4401class ModeAttr : public Attr {
4402IdentifierInfo * mode;
4403
4404public:
4405 static ModeAttr *CreateImplicit(ASTContext &Ctx, IdentifierInfo * Mode, SourceRange Loc = SourceRange()) {
4406 auto *A = new (Ctx) ModeAttr(Loc, Ctx, Mode, 0);
4407 A->setImplicit(true);
4408 return A;
4409 }
4410
4411 ModeAttr(SourceRange R, ASTContext &Ctx
4412 , IdentifierInfo * Mode
4413 , unsigned SI
4414 )
4415 : Attr(attr::Mode, R, SI, false)
4416 , mode(Mode)
4417 {
4418 }
4419
4420 ModeAttr *clone(ASTContext &C) const;
4421 void printPretty(raw_ostream &OS,
4422 const PrintingPolicy &Policy) const;
4423 const char *getSpelling() const;
4424 IdentifierInfo * getMode() const {
4425 return mode;
4426 }
4427
4428
4429
4430 static bool classof(const Attr *A) { return A->getKind() == attr::Mode; }
4431};
4432
4433class NSConsumedAttr : public InheritableParamAttr {
4434public:
4435 static NSConsumedAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
4436 auto *A = new (Ctx) NSConsumedAttr(Loc, Ctx, 0);
4437 A->setImplicit(true);
4438 return A;
4439 }
4440
4441 NSConsumedAttr(SourceRange R, ASTContext &Ctx
4442 , unsigned SI
4443 )
4444 : InheritableParamAttr(attr::NSConsumed, R, SI, false, false)
4445 {
4446 }
4447
4448 NSConsumedAttr *clone(ASTContext &C) const;
4449 void printPretty(raw_ostream &OS,
4450 const PrintingPolicy &Policy) const;
4451 const char *getSpelling() const;
4452
4453
4454 static bool classof(const Attr *A) { return A->getKind() == attr::NSConsumed; }
4455};
4456
4457class NSConsumesSelfAttr : public InheritableAttr {
4458public:
4459 static NSConsumesSelfAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
4460 auto *A = new (Ctx) NSConsumesSelfAttr(Loc, Ctx, 0);
4461 A->setImplicit(true);
4462 return A;
4463 }
4464
4465 NSConsumesSelfAttr(SourceRange R, ASTContext &Ctx
4466 , unsigned SI
4467 )
4468 : InheritableAttr(attr::NSConsumesSelf, R, SI, false, false)
4469 {
4470 }
4471
4472 NSConsumesSelfAttr *clone(ASTContext &C) const;
4473 void printPretty(raw_ostream &OS,
4474 const PrintingPolicy &Policy) const;
4475 const char *getSpelling() const;
4476
4477
4478 static bool classof(const Attr *A) { return A->getKind() == attr::NSConsumesSelf; }
4479};
4480
4481class NSReturnsAutoreleasedAttr : public InheritableAttr {
4482public:
4483 static NSReturnsAutoreleasedAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
4484 auto *A = new (Ctx) NSReturnsAutoreleasedAttr(Loc, Ctx, 0);
4485 A->setImplicit(true);
4486 return A;
4487 }
4488
4489 NSReturnsAutoreleasedAttr(SourceRange R, ASTContext &Ctx
4490 , unsigned SI
4491 )
4492 : InheritableAttr(attr::NSReturnsAutoreleased, R, SI, false, false)
4493 {
4494 }
4495
4496 NSReturnsAutoreleasedAttr *clone(ASTContext &C) const;
4497 void printPretty(raw_ostream &OS,
4498 const PrintingPolicy &Policy) const;
4499 const char *getSpelling() const;
4500
4501
4502 static bool classof(const Attr *A) { return A->getKind() == attr::NSReturnsAutoreleased; }
4503};
4504
4505class NSReturnsNotRetainedAttr : public InheritableAttr {
4506public:
4507 static NSReturnsNotRetainedAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
4508 auto *A = new (Ctx) NSReturnsNotRetainedAttr(Loc, Ctx, 0);
4509 A->setImplicit(true);
4510 return A;
4511 }
4512
4513 NSReturnsNotRetainedAttr(SourceRange R, ASTContext &Ctx
4514 , unsigned SI
4515 )
4516 : InheritableAttr(attr::NSReturnsNotRetained, R, SI, false, false)
4517 {
4518 }
4519
4520 NSReturnsNotRetainedAttr *clone(ASTContext &C) const;
4521 void printPretty(raw_ostream &OS,
4522 const PrintingPolicy &Policy) const;
4523 const char *getSpelling() const;
4524
4525
4526 static bool classof(const Attr *A) { return A->getKind() == attr::NSReturnsNotRetained; }
4527};
4528
4529class NSReturnsRetainedAttr : public InheritableAttr {
4530public:
4531 static NSReturnsRetainedAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
4532 auto *A = new (Ctx) NSReturnsRetainedAttr(Loc, Ctx, 0);
4533 A->setImplicit(true);
4534 return A;
4535 }
4536
4537 NSReturnsRetainedAttr(SourceRange R, ASTContext &Ctx
4538 , unsigned SI
4539 )
4540 : InheritableAttr(attr::NSReturnsRetained, R, SI, false, false)
4541 {
4542 }
4543
4544 NSReturnsRetainedAttr *clone(ASTContext &C) const;
4545 void printPretty(raw_ostream &OS,
4546 const PrintingPolicy &Policy) const;
4547 const char *getSpelling() const;
4548
4549
4550 static bool classof(const Attr *A) { return A->getKind() == attr::NSReturnsRetained; }
4551};
4552
4553class NakedAttr : public InheritableAttr {
4554public:
4555 static NakedAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
4556 auto *A = new (Ctx) NakedAttr(Loc, Ctx, 0);
4557 A->setImplicit(true);
4558 return A;
4559 }
4560
4561 NakedAttr(SourceRange R, ASTContext &Ctx
4562 , unsigned SI
4563 )
4564 : InheritableAttr(attr::Naked, R, SI, false, false)
4565 {
4566 }
4567
4568 NakedAttr *clone(ASTContext &C) const;
4569 void printPretty(raw_ostream &OS,
4570 const PrintingPolicy &Policy) const;
4571 const char *getSpelling() const;
4572
4573
4574 static bool classof(const Attr *A) { return A->getKind() == attr::Naked; }
4575};
4576
4577class NoAliasAttr : public InheritableAttr {
4578public:
4579 static NoAliasAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
4580 auto *A = new (Ctx) NoAliasAttr(Loc, Ctx, 0);
4581 A->setImplicit(true);
4582 return A;
4583 }
4584
4585 NoAliasAttr(SourceRange R, ASTContext &Ctx
4586 , unsigned SI
4587 )
4588 : InheritableAttr(attr::NoAlias, R, SI, false, false)
4589 {
4590 }
4591
4592 NoAliasAttr *clone(ASTContext &C) const;
4593 void printPretty(raw_ostream &OS,
4594 const PrintingPolicy &Policy) const;
4595 const char *getSpelling() const;
4596
4597
4598 static bool classof(const Attr *A) { return A->getKind() == attr::NoAlias; }
4599};
4600
4601class NoCommonAttr : public InheritableAttr {
4602public:
4603 static NoCommonAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
4604 auto *A = new (Ctx) NoCommonAttr(Loc, Ctx, 0);
4605 A->setImplicit(true);
4606 return A;
4607 }
4608
4609 NoCommonAttr(SourceRange R, ASTContext &Ctx
4610 , unsigned SI
4611 )
4612 : InheritableAttr(attr::NoCommon, R, SI, false, false)
4613 {
4614 }
4615
4616 NoCommonAttr *clone(ASTContext &C) const;
4617 void printPretty(raw_ostream &OS,
4618 const PrintingPolicy &Policy) const;
4619 const char *getSpelling() const;
4620
4621
4622 static bool classof(const Attr *A) { return A->getKind() == attr::NoCommon; }
4623};
4624
4625class NoDebugAttr : public InheritableAttr {
4626public:
4627 static NoDebugAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
4628 auto *A = new (Ctx) NoDebugAttr(Loc, Ctx, 0);
4629 A->setImplicit(true);
4630 return A;
4631 }
4632
4633 NoDebugAttr(SourceRange R, ASTContext &Ctx
4634 , unsigned SI
4635 )
4636 : InheritableAttr(attr::NoDebug, R, SI, false, false)
4637 {
4638 }
4639
4640 NoDebugAttr *clone(ASTContext &C) const;
4641 void printPretty(raw_ostream &OS,
4642 const PrintingPolicy &Policy) const;
4643 const char *getSpelling() const;
4644
4645
4646 static bool classof(const Attr *A) { return A->getKind() == attr::NoDebug; }
4647};
4648
4649class NoDuplicateAttr : public InheritableAttr {
4650public:
4651 static NoDuplicateAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
4652 auto *A = new (Ctx) NoDuplicateAttr(Loc, Ctx, 0);
4653 A->setImplicit(true);
4654 return A;
4655 }
4656
4657 NoDuplicateAttr(SourceRange R, ASTContext &Ctx
4658 , unsigned SI
4659 )
4660 : InheritableAttr(attr::NoDuplicate, R, SI, false, false)
4661 {
4662 }
4663
4664 NoDuplicateAttr *clone(ASTContext &C) const;
4665 void printPretty(raw_ostream &OS,
4666 const PrintingPolicy &Policy) const;
4667 const char *getSpelling() const;
4668
4669
4670 static bool classof(const Attr *A) { return A->getKind() == attr::NoDuplicate; }
4671};
4672
4673class NoEscapeAttr : public Attr {
4674public:
4675 static NoEscapeAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
4676 auto *A = new (Ctx) NoEscapeAttr(Loc, Ctx, 0);
4677 A->setImplicit(true);
4678 return A;
4679 }
4680
4681 NoEscapeAttr(SourceRange R, ASTContext &Ctx
4682 , unsigned SI
4683 )
4684 : Attr(attr::NoEscape, R, SI, false)
4685 {
4686 }
4687
4688 NoEscapeAttr *clone(ASTContext &C) const;
4689 void printPretty(raw_ostream &OS,
4690 const PrintingPolicy &Policy) const;
4691 const char *getSpelling() const;
4692
4693
4694 static bool classof(const Attr *A) { return A->getKind() == attr::NoEscape; }
4695};
4696
4697class NoInlineAttr : public InheritableAttr {
4698public:
4699 static NoInlineAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
4700 auto *A = new (Ctx) NoInlineAttr(Loc, Ctx, 0);
4701 A->setImplicit(true);
4702 return A;
4703 }
4704
4705 NoInlineAttr(SourceRange R, ASTContext &Ctx
4706 , unsigned SI
4707 )
4708 : InheritableAttr(attr::NoInline, R, SI, false, false)
4709 {
4710 }
4711
4712 NoInlineAttr *clone(ASTContext &C) const;
4713 void printPretty(raw_ostream &OS,
4714 const PrintingPolicy &Policy) const;
4715 const char *getSpelling() const;
4716
4717
4718 static bool classof(const Attr *A) { return A->getKind() == attr::NoInline; }
4719};
4720
4721class NoInstrumentFunctionAttr : public InheritableAttr {
4722public:
4723 static NoInstrumentFunctionAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
4724 auto *A = new (Ctx) NoInstrumentFunctionAttr(Loc, Ctx, 0);
4725 A->setImplicit(true);
4726 return A;
4727 }
4728
4729 NoInstrumentFunctionAttr(SourceRange R, ASTContext &Ctx
4730 , unsigned SI
4731 )
4732 : InheritableAttr(attr::NoInstrumentFunction, R, SI, false, false)
4733 {
4734 }
4735
4736 NoInstrumentFunctionAttr *clone(ASTContext &C) const;
4737 void printPretty(raw_ostream &OS,
4738 const PrintingPolicy &Policy) const;
4739 const char *getSpelling() const;
4740
4741
4742 static bool classof(const Attr *A) { return A->getKind() == attr::NoInstrumentFunction; }
4743};
4744
4745class NoMicroMipsAttr : public InheritableAttr {
4746public:
4747 static NoMicroMipsAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
4748 auto *A = new (Ctx) NoMicroMipsAttr(Loc, Ctx, 0);
4749 A->setImplicit(true);
4750 return A;
4751 }
4752
4753 NoMicroMipsAttr(SourceRange R, ASTContext &Ctx
4754 , unsigned SI
4755 )
4756 : InheritableAttr(attr::NoMicroMips, R, SI, false, false)
4757 {
4758 }
4759
4760 NoMicroMipsAttr *clone(ASTContext &C) const;
4761 void printPretty(raw_ostream &OS,
4762 const PrintingPolicy &Policy) const;
4763 const char *getSpelling() const;
4764
4765
4766 static bool classof(const Attr *A) { return A->getKind() == attr::NoMicroMips; }
4767};
4768
4769class NoMips16Attr : public InheritableAttr {
4770public:
4771 static NoMips16Attr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
4772 auto *A = new (Ctx) NoMips16Attr(Loc, Ctx, 0);
4773 A->setImplicit(true);
4774 return A;
4775 }
4776
4777 NoMips16Attr(SourceRange R, ASTContext &Ctx
4778 , unsigned SI
4779 )
4780 : InheritableAttr(attr::NoMips16, R, SI, false, false)
4781 {
4782 }
4783
4784 NoMips16Attr *clone(ASTContext &C) const;
4785 void printPretty(raw_ostream &OS,
4786 const PrintingPolicy &Policy) const;
4787 const char *getSpelling() const;
4788
4789
4790 static bool classof(const Attr *A) { return A->getKind() == attr::NoMips16; }
4791};
4792
4793class NoReturnAttr : public InheritableAttr {
4794public:
4795 static NoReturnAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
4796 auto *A = new (Ctx) NoReturnAttr(Loc, Ctx, 0);
4797 A->setImplicit(true);
4798 return A;
4799 }
4800
4801 NoReturnAttr(SourceRange R, ASTContext &Ctx
4802 , unsigned SI
4803 )
4804 : InheritableAttr(attr::NoReturn, R, SI, false, false)
4805 {
4806 }
4807
4808 NoReturnAttr *clone(ASTContext &C) const;
4809 void printPretty(raw_ostream &OS,
4810 const PrintingPolicy &Policy) const;
4811 const char *getSpelling() const;
4812
4813
4814 static bool classof(const Attr *A) { return A->getKind() == attr::NoReturn; }
4815};
4816
4817class NoSanitizeAttr : public InheritableAttr {
4818 unsigned sanitizers_Size;
4819 StringRef *sanitizers_;
4820
4821public:
4822 static NoSanitizeAttr *CreateImplicit(ASTContext &Ctx, StringRef *Sanitizers, unsigned SanitizersSize, SourceRange Loc = SourceRange()) {
4823 auto *A = new (Ctx) NoSanitizeAttr(Loc, Ctx, Sanitizers, SanitizersSize, 0);
4824 A->setImplicit(true);
4825 return A;
4826 }
4827
4828 NoSanitizeAttr(SourceRange R, ASTContext &Ctx
4829 , StringRef *Sanitizers, unsigned SanitizersSize
4830 , unsigned SI
4831 )
4832 : InheritableAttr(attr::NoSanitize, R, SI, false, false)
4833 , sanitizers_Size(SanitizersSize), sanitizers_(new (Ctx, 16) StringRef[sanitizers_Size])
4834 {
4835 for (size_t I = 0, E = sanitizers_Size; I != E;
4836 ++I) {
4837 StringRef Ref = Sanitizers[I];
4838 if (!Ref.empty()) {
4839 char *Mem = new (Ctx, 1) char[Ref.size()];
4840 std::memcpy(Mem, Ref.data(), Ref.size());
4841 sanitizers_[I] = StringRef(Mem, Ref.size());
4842 }
4843 }
4844 }
4845
4846 NoSanitizeAttr(SourceRange R, ASTContext &Ctx
4847 , unsigned SI
4848 )
4849 : InheritableAttr(attr::NoSanitize, R, SI, false, false)
4850 , sanitizers_Size(0), sanitizers_(nullptr)
4851 {
4852 }
4853
4854 NoSanitizeAttr *clone(ASTContext &C) const;
4855 void printPretty(raw_ostream &OS,
4856 const PrintingPolicy &Policy) const;
4857 const char *getSpelling() const;
4858 typedef StringRef* sanitizers_iterator;
4859 sanitizers_iterator sanitizers_begin() const { return sanitizers_; }
4860 sanitizers_iterator sanitizers_end() const { return sanitizers_ + sanitizers_Size; }
4861 unsigned sanitizers_size() const { return sanitizers_Size; }
4862 llvm::iterator_range<sanitizers_iterator> sanitizers() const { return llvm::make_range(sanitizers_begin(), sanitizers_end()); }
4863
4864
4865
4866 SanitizerMask getMask() const {
4867 SanitizerMask Mask = 0;
4868 for (auto SanitizerName : sanitizers()) {
4869 SanitizerMask ParsedMask =
4870 parseSanitizerValue(SanitizerName, /*AllowGroups=*/true);
4871 Mask |= expandSanitizerGroups(ParsedMask);
4872 }
4873 return Mask;
4874 }
4875
4876
4877 static bool classof(const Attr *A) { return A->getKind() == attr::NoSanitize; }
4878};
4879
4880class NoSplitStackAttr : public InheritableAttr {
4881public:
4882 static NoSplitStackAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
4883 auto *A = new (Ctx) NoSplitStackAttr(Loc, Ctx, 0);
4884 A->setImplicit(true);
4885 return A;
4886 }
4887
4888 NoSplitStackAttr(SourceRange R, ASTContext &Ctx
4889 , unsigned SI
4890 )
4891 : InheritableAttr(attr::NoSplitStack, R, SI, false, false)
4892 {
4893 }
4894
4895 NoSplitStackAttr *clone(ASTContext &C) const;
4896 void printPretty(raw_ostream &OS,
4897 const PrintingPolicy &Policy) const;
4898 const char *getSpelling() const;
4899
4900
4901 static bool classof(const Attr *A) { return A->getKind() == attr::NoSplitStack; }
4902};
4903
4904class NoThreadSafetyAnalysisAttr : public InheritableAttr {
4905public:
4906 static NoThreadSafetyAnalysisAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
4907 auto *A = new (Ctx) NoThreadSafetyAnalysisAttr(Loc, Ctx, 0);
4908 A->setImplicit(true);
4909 return A;
4910 }
4911
4912 NoThreadSafetyAnalysisAttr(SourceRange R, ASTContext &Ctx
4913 , unsigned SI
4914 )
4915 : InheritableAttr(attr::NoThreadSafetyAnalysis, R, SI, false, false)
4916 {
4917 }
4918
4919 NoThreadSafetyAnalysisAttr *clone(ASTContext &C) const;
4920 void printPretty(raw_ostream &OS,
4921 const PrintingPolicy &Policy) const;
4922 const char *getSpelling() const;
4923
4924
4925 static bool classof(const Attr *A) { return A->getKind() == attr::NoThreadSafetyAnalysis; }
4926};
4927
4928class NoThrowAttr : public InheritableAttr {
4929public:
4930 static NoThrowAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
4931 auto *A = new (Ctx) NoThrowAttr(Loc, Ctx, 0);
4932 A->setImplicit(true);
4933 return A;
4934 }
4935
4936 NoThrowAttr(SourceRange R, ASTContext &Ctx
4937 , unsigned SI
4938 )
4939 : InheritableAttr(attr::NoThrow, R, SI, false, false)
4940 {
4941 }
4942
4943 NoThrowAttr *clone(ASTContext &C) const;
4944 void printPretty(raw_ostream &OS,
4945 const PrintingPolicy &Policy) const;
4946 const char *getSpelling() const;
4947
4948
4949 static bool classof(const Attr *A) { return A->getKind() == attr::NoThrow; }
4950};
4951
4952class NonNullAttr : public InheritableParamAttr {
4953 unsigned args_Size;
4954 ParamIdx *args_;
4955
4956public:
4957 static NonNullAttr *CreateImplicit(ASTContext &Ctx, ParamIdx *Args, unsigned ArgsSize, SourceRange Loc = SourceRange()) {
4958 auto *A = new (Ctx) NonNullAttr(Loc, Ctx, Args, ArgsSize, 0);
4959 A->setImplicit(true);
4960 return A;
4961 }
4962
4963 NonNullAttr(SourceRange R, ASTContext &Ctx
4964 , ParamIdx *Args, unsigned ArgsSize
4965 , unsigned SI
4966 )
4967 : InheritableParamAttr(attr::NonNull, R, SI, false, true)
4968 , args_Size(ArgsSize), args_(new (Ctx, 16) ParamIdx[args_Size])
4969 {
4970 std::copy(Args, Args + args_Size, args_);
4971 }
4972
4973 NonNullAttr(SourceRange R, ASTContext &Ctx
4974 , unsigned SI
4975 )
4976 : InheritableParamAttr(attr::NonNull, R, SI, false, true)
4977 , args_Size(0), args_(nullptr)
4978 {
4979 }
4980
4981 NonNullAttr *clone(ASTContext &C) const;
4982 void printPretty(raw_ostream &OS,
4983 const PrintingPolicy &Policy) const;
4984 const char *getSpelling() const;
4985 typedef ParamIdx* args_iterator;
4986 args_iterator args_begin() const { return args_; }
4987 args_iterator args_end() const { return args_ + args_Size; }
4988 unsigned args_size() const { return args_Size; }
4989 llvm::iterator_range<args_iterator> args() const { return llvm::make_range(args_begin(), args_end()); }
4990
4991
4992
4993 bool isNonNull(unsigned IdxAST) const {
4994 if (!args_size())
4995 return true;
4996 return args_end() != std::find_if(
4997 args_begin(), args_end(),
4998 [=](const ParamIdx &Idx) { return Idx.getASTIndex() == IdxAST; });
4999 }
5000
5001
5002 static bool classof(const Attr *A) { return A->getKind() == attr::NonNull; }
5003};
5004
5005class NotTailCalledAttr : public InheritableAttr {
5006public:
5007 static NotTailCalledAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
5008 auto *A = new (Ctx) NotTailCalledAttr(Loc, Ctx, 0);
5009 A->setImplicit(true);
5010 return A;
5011 }
5012
5013 NotTailCalledAttr(SourceRange R, ASTContext &Ctx
5014 , unsigned SI
5015 )
5016 : InheritableAttr(attr::NotTailCalled, R, SI, false, false)
5017 {
5018 }
5019
5020 NotTailCalledAttr *clone(ASTContext &C) const;
5021 void printPretty(raw_ostream &OS,
5022 const PrintingPolicy &Policy) const;
5023 const char *getSpelling() const;
5024
5025
5026 static bool classof(const Attr *A) { return A->getKind() == attr::NotTailCalled; }
5027};
5028
5029class OMPCaptureKindAttr : public Attr {
5030unsigned captureKind;
5031
5032public:
5033 static OMPCaptureKindAttr *CreateImplicit(ASTContext &Ctx, unsigned CaptureKind, SourceRange Loc = SourceRange()) {
5034 auto *A = new (Ctx) OMPCaptureKindAttr(Loc, Ctx, CaptureKind, 0);
5035 A->setImplicit(true);
5036 return A;
5037 }
5038
5039 OMPCaptureKindAttr(SourceRange R, ASTContext &Ctx
5040 , unsigned CaptureKind
5041 , unsigned SI
5042 )
5043 : Attr(attr::OMPCaptureKind, R, SI, false)
5044 , captureKind(CaptureKind)
5045 {
5046 }
5047
5048 OMPCaptureKindAttr *clone(ASTContext &C) const;
5049 void printPretty(raw_ostream &OS,
5050 const PrintingPolicy &Policy) const;
5051 const char *getSpelling() const;
5052 unsigned getCaptureKind() const {
5053 return captureKind;
5054 }
5055
5056
5057
5058 static bool classof(const Attr *A) { return A->getKind() == attr::OMPCaptureKind; }
5059};
5060
5061class OMPCaptureNoInitAttr : public InheritableAttr {
5062public:
5063 static OMPCaptureNoInitAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
5064 auto *A = new (Ctx) OMPCaptureNoInitAttr(Loc, Ctx, 0);
5065 A->setImplicit(true);
5066 return A;
5067 }
5068
5069 OMPCaptureNoInitAttr(SourceRange R, ASTContext &Ctx
5070 , unsigned SI
5071 )
5072 : InheritableAttr(attr::OMPCaptureNoInit, R, SI, false, false)
5073 {
5074 }
5075
5076 OMPCaptureNoInitAttr *clone(ASTContext &C) const;
5077 void printPretty(raw_ostream &OS,
5078 const PrintingPolicy &Policy) const;
5079 const char *getSpelling() const;
5080
5081
5082 static bool classof(const Attr *A) { return A->getKind() == attr::OMPCaptureNoInit; }
5083};
5084
5085class OMPDeclareSimdDeclAttr : public Attr {
5086public:
5087 enum BranchStateTy {
5088 BS_Undefined,
5089 BS_Inbranch,
5090 BS_Notinbranch
5091 };
5092private:
5093 BranchStateTy branchState;
5094
5095Expr * simdlen;
5096
5097 unsigned uniforms_Size;
5098 Expr * *uniforms_;
5099
5100 unsigned aligneds_Size;
5101 Expr * *aligneds_;
5102
5103 unsigned alignments_Size;
5104 Expr * *alignments_;
5105
5106 unsigned linears_Size;
5107 Expr * *linears_;
5108
5109 unsigned modifiers_Size;
5110 unsigned *modifiers_;
5111
5112 unsigned steps_Size;
5113 Expr * *steps_;
5114
5115public:
5116 static OMPDeclareSimdDeclAttr *CreateImplicit(ASTContext &Ctx, BranchStateTy BranchState, Expr * Simdlen, Expr * *Uniforms, unsigned UniformsSize, Expr * *Aligneds, unsigned AlignedsSize, Expr * *Alignments, unsigned AlignmentsSize, Expr * *Linears, unsigned LinearsSize, unsigned *Modifiers, unsigned ModifiersSize, Expr * *Steps, unsigned StepsSize, SourceRange Loc = SourceRange()) {
5117 auto *A = new (Ctx) OMPDeclareSimdDeclAttr(Loc, Ctx, BranchState, Simdlen, Uniforms, UniformsSize, Aligneds, AlignedsSize, Alignments, AlignmentsSize, Linears, LinearsSize, Modifiers, ModifiersSize, Steps, StepsSize, 0);
5118 A->setImplicit(true);
5119 return A;
5120 }
5121
5122 OMPDeclareSimdDeclAttr(SourceRange R, ASTContext &Ctx
5123 , BranchStateTy BranchState
5124 , Expr * Simdlen
5125 , Expr * *Uniforms, unsigned UniformsSize
5126 , Expr * *Aligneds, unsigned AlignedsSize
5127 , Expr * *Alignments, unsigned AlignmentsSize
5128 , Expr * *Linears, unsigned LinearsSize
5129 , unsigned *Modifiers, unsigned ModifiersSize
5130 , Expr * *Steps, unsigned StepsSize
5131 , unsigned SI
5132 )
5133 : Attr(attr::OMPDeclareSimdDecl, R, SI, false)
5134 , branchState(BranchState)
5135 , simdlen(Simdlen)
5136 , uniforms_Size(UniformsSize), uniforms_(new (Ctx, 16) Expr *[uniforms_Size])
5137 , aligneds_Size(AlignedsSize), aligneds_(new (Ctx, 16) Expr *[aligneds_Size])
5138 , alignments_Size(AlignmentsSize), alignments_(new (Ctx, 16) Expr *[alignments_Size])
5139 , linears_Size(LinearsSize), linears_(new (Ctx, 16) Expr *[linears_Size])
5140 , modifiers_Size(ModifiersSize), modifiers_(new (Ctx, 16) unsigned[modifiers_Size])
5141 , steps_Size(StepsSize), steps_(new (Ctx, 16) Expr *[steps_Size])
5142 {
5143 std::copy(Uniforms, Uniforms + uniforms_Size, uniforms_);
5144 std::copy(Aligneds, Aligneds + aligneds_Size, aligneds_);
5145 std::copy(Alignments, Alignments + alignments_Size, alignments_);
5146 std::copy(Linears, Linears + linears_Size, linears_);
5147 std::copy(Modifiers, Modifiers + modifiers_Size, modifiers_);
5148 std::copy(Steps, Steps + steps_Size, steps_);
5149 }
5150
5151 OMPDeclareSimdDeclAttr(SourceRange R, ASTContext &Ctx
5152 , BranchStateTy BranchState
5153 , Expr * Simdlen
5154 , unsigned SI
5155 )
5156 : Attr(attr::OMPDeclareSimdDecl, R, SI, false)
5157 , branchState(BranchState)
5158 , simdlen(Simdlen)
5159 , uniforms_Size(0), uniforms_(nullptr)
5160 , aligneds_Size(0), aligneds_(nullptr)
5161 , alignments_Size(0), alignments_(nullptr)
5162 , linears_Size(0), linears_(nullptr)
5163 , modifiers_Size(0), modifiers_(nullptr)
5164 , steps_Size(0), steps_(nullptr)
5165 {
5166 }
5167
5168 OMPDeclareSimdDeclAttr *clone(ASTContext &C) const;
5169 void printPretty(raw_ostream &OS,
5170 const PrintingPolicy &Policy) const;
5171 const char *getSpelling() const;
5172 BranchStateTy getBranchState() const {
5173 return branchState;
5174 }
5175
5176 static bool ConvertStrToBranchStateTy(StringRef Val, BranchStateTy &Out) {
5177 Optional<BranchStateTy> R = llvm::StringSwitch<Optional<BranchStateTy>>(Val)
5178 .Case("", OMPDeclareSimdDeclAttr::BS_Undefined)
5179 .Case("inbranch", OMPDeclareSimdDeclAttr::BS_Inbranch)
5180 .Case("notinbranch", OMPDeclareSimdDeclAttr::BS_Notinbranch)
5181 .Default(Optional<BranchStateTy>());
5182 if (R) {
5183 Out = *R;
5184 return true;
5185 }
5186 return false;
5187 }
5188
5189 static const char *ConvertBranchStateTyToStr(BranchStateTy Val) {
5190 switch(Val) {
5191 case OMPDeclareSimdDeclAttr::BS_Undefined: return "";
5192 case OMPDeclareSimdDeclAttr::BS_Inbranch: return "inbranch";
5193 case OMPDeclareSimdDeclAttr::BS_Notinbranch: return "notinbranch";
5194 }
5195 llvm_unreachable("No enumerator with that value")::llvm::llvm_unreachable_internal("No enumerator with that value"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 5195)
;
5196 }
5197 Expr * getSimdlen() const {
5198 return simdlen;
5199 }
5200
5201 typedef Expr ** uniforms_iterator;
5202 uniforms_iterator uniforms_begin() const { return uniforms_; }
5203 uniforms_iterator uniforms_end() const { return uniforms_ + uniforms_Size; }
5204 unsigned uniforms_size() const { return uniforms_Size; }
5205 llvm::iterator_range<uniforms_iterator> uniforms() const { return llvm::make_range(uniforms_begin(), uniforms_end()); }
5206
5207
5208 typedef Expr ** aligneds_iterator;
5209 aligneds_iterator aligneds_begin() const { return aligneds_; }
5210 aligneds_iterator aligneds_end() const { return aligneds_ + aligneds_Size; }
5211 unsigned aligneds_size() const { return aligneds_Size; }
5212 llvm::iterator_range<aligneds_iterator> aligneds() const { return llvm::make_range(aligneds_begin(), aligneds_end()); }
5213
5214
5215 typedef Expr ** alignments_iterator;
5216 alignments_iterator alignments_begin() const { return alignments_; }
5217 alignments_iterator alignments_end() const { return alignments_ + alignments_Size; }
5218 unsigned alignments_size() const { return alignments_Size; }
5219 llvm::iterator_range<alignments_iterator> alignments() const { return llvm::make_range(alignments_begin(), alignments_end()); }
5220
5221
5222 typedef Expr ** linears_iterator;
5223 linears_iterator linears_begin() const { return linears_; }
5224 linears_iterator linears_end() const { return linears_ + linears_Size; }
5225 unsigned linears_size() const { return linears_Size; }
5226 llvm::iterator_range<linears_iterator> linears() const { return llvm::make_range(linears_begin(), linears_end()); }
5227
5228
5229 typedef unsigned* modifiers_iterator;
5230 modifiers_iterator modifiers_begin() const { return modifiers_; }
5231 modifiers_iterator modifiers_end() const { return modifiers_ + modifiers_Size; }
5232 unsigned modifiers_size() const { return modifiers_Size; }
5233 llvm::iterator_range<modifiers_iterator> modifiers() const { return llvm::make_range(modifiers_begin(), modifiers_end()); }
5234
5235
5236 typedef Expr ** steps_iterator;
5237 steps_iterator steps_begin() const { return steps_; }
5238 steps_iterator steps_end() const { return steps_ + steps_Size; }
5239 unsigned steps_size() const { return steps_Size; }
5240 llvm::iterator_range<steps_iterator> steps() const { return llvm::make_range(steps_begin(), steps_end()); }
5241
5242
5243
5244 void printPrettyPragma(raw_ostream & OS, const PrintingPolicy &Policy)
5245 const {
5246 if (getBranchState() != BS_Undefined)
5247 OS << ' ' << ConvertBranchStateTyToStr(getBranchState());
5248 if (auto *E = getSimdlen()) {
5249 OS << " simdlen(";
5250 E->printPretty(OS, nullptr, Policy);
5251 OS << ")";
5252 }
5253 if (uniforms_size() > 0) {
5254 OS << " uniform";
5255 StringRef Sep = "(";
5256 for (auto *E : uniforms()) {
5257 OS << Sep;
5258 E->printPretty(OS, nullptr, Policy);
5259 Sep = ", ";
5260 }
5261 OS << ")";
5262 }
5263 alignments_iterator NI = alignments_begin();
5264 for (auto *E : aligneds()) {
5265 OS << " aligned(";
5266 E->printPretty(OS, nullptr, Policy);
5267 if (*NI) {
5268 OS << ": ";
5269 (*NI)->printPretty(OS, nullptr, Policy);
5270 }
5271 OS << ")";
5272 ++NI;
5273 }
5274 steps_iterator I = steps_begin();
5275 modifiers_iterator MI = modifiers_begin();
5276 for (auto *E : linears()) {
5277 OS << " linear(";
5278 if (*MI != OMPC_LINEAR_unknown)
5279 OS << getOpenMPSimpleClauseTypeName(OMPC_linear, *MI) << "(";
5280 E->printPretty(OS, nullptr, Policy);
5281 if (*MI != OMPC_LINEAR_unknown)
5282 OS << ")";
5283 if (*I) {
5284 OS << ": ";
5285 (*I)->printPretty(OS, nullptr, Policy);
5286 }
5287 OS << ")";
5288 ++I;
5289 ++MI;
5290 }
5291 }
5292
5293
5294 static bool classof(const Attr *A) { return A->getKind() == attr::OMPDeclareSimdDecl; }
5295};
5296
5297class OMPDeclareTargetDeclAttr : public Attr {
5298public:
5299 enum MapTypeTy {
5300 MT_To,
5301 MT_Link
5302 };
5303private:
5304 MapTypeTy mapType;
5305
5306public:
5307 static OMPDeclareTargetDeclAttr *CreateImplicit(ASTContext &Ctx, MapTypeTy MapType, SourceRange Loc = SourceRange()) {
5308 auto *A = new (Ctx) OMPDeclareTargetDeclAttr(Loc, Ctx, MapType, 0);
5309 A->setImplicit(true);
5310 return A;
5311 }
5312
5313 OMPDeclareTargetDeclAttr(SourceRange R, ASTContext &Ctx
5314 , MapTypeTy MapType
5315 , unsigned SI
5316 )
5317 : Attr(attr::OMPDeclareTargetDecl, R, SI, false)
5318 , mapType(MapType)
5319 {
5320 }
5321
5322 OMPDeclareTargetDeclAttr *clone(ASTContext &C) const;
5323 void printPretty(raw_ostream &OS,
5324 const PrintingPolicy &Policy) const;
5325 const char *getSpelling() const;
5326 MapTypeTy getMapType() const {
5327 return mapType;
5328 }
5329
5330 static bool ConvertStrToMapTypeTy(StringRef Val, MapTypeTy &Out) {
5331 Optional<MapTypeTy> R = llvm::StringSwitch<Optional<MapTypeTy>>(Val)
5332 .Case("to", OMPDeclareTargetDeclAttr::MT_To)
5333 .Case("link", OMPDeclareTargetDeclAttr::MT_Link)
5334 .Default(Optional<MapTypeTy>());
5335 if (R) {
5336 Out = *R;
5337 return true;
5338 }
5339 return false;
5340 }
5341
5342 static const char *ConvertMapTypeTyToStr(MapTypeTy Val) {
5343 switch(Val) {
5344 case OMPDeclareTargetDeclAttr::MT_To: return "to";
5345 case OMPDeclareTargetDeclAttr::MT_Link: return "link";
5346 }
5347 llvm_unreachable("No enumerator with that value")::llvm::llvm_unreachable_internal("No enumerator with that value"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 5347)
;
5348 }
5349
5350 void printPrettyPragma(raw_ostream &OS, const PrintingPolicy &Policy) const {
5351 // Use fake syntax because it is for testing and debugging purpose only.
5352 if (getMapType() != MT_To)
5353 OS << ' ' << ConvertMapTypeTyToStr(getMapType());
5354 }
5355
5356
5357 static bool classof(const Attr *A) { return A->getKind() == attr::OMPDeclareTargetDecl; }
5358};
5359
5360class OMPReferencedVarAttr : public Attr {
5361Expr * ref;
5362
5363public:
5364 static OMPReferencedVarAttr *CreateImplicit(ASTContext &Ctx, Expr * Ref, SourceRange Loc = SourceRange()) {
5365 auto *A = new (Ctx) OMPReferencedVarAttr(Loc, Ctx, Ref, 0);
5366 A->setImplicit(true);
5367 return A;
5368 }
5369
5370 OMPReferencedVarAttr(SourceRange R, ASTContext &Ctx
5371 , Expr * Ref
5372 , unsigned SI
5373 )
5374 : Attr(attr::OMPReferencedVar, R, SI, false)
5375 , ref(Ref)
5376 {
5377 }
5378
5379 OMPReferencedVarAttr *clone(ASTContext &C) const;
5380 void printPretty(raw_ostream &OS,
5381 const PrintingPolicy &Policy) const;
5382 const char *getSpelling() const;
5383 Expr * getRef() const {
5384 return ref;
5385 }
5386
5387
5388
5389 static bool classof(const Attr *A) { return A->getKind() == attr::OMPReferencedVar; }
5390};
5391
5392class OMPThreadPrivateDeclAttr : public InheritableAttr {
5393public:
5394 static OMPThreadPrivateDeclAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
5395 auto *A = new (Ctx) OMPThreadPrivateDeclAttr(Loc, Ctx, 0);
5396 A->setImplicit(true);
5397 return A;
5398 }
5399
5400 OMPThreadPrivateDeclAttr(SourceRange R, ASTContext &Ctx
5401 , unsigned SI
5402 )
5403 : InheritableAttr(attr::OMPThreadPrivateDecl, R, SI, false, false)
5404 {
5405 }
5406
5407 OMPThreadPrivateDeclAttr *clone(ASTContext &C) const;
5408 void printPretty(raw_ostream &OS,
5409 const PrintingPolicy &Policy) const;
5410 const char *getSpelling() const;
5411
5412
5413 static bool classof(const Attr *A) { return A->getKind() == attr::OMPThreadPrivateDecl; }
5414};
5415
5416class ObjCBoxableAttr : public Attr {
5417public:
5418 static ObjCBoxableAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
5419 auto *A = new (Ctx) ObjCBoxableAttr(Loc, Ctx, 0);
5420 A->setImplicit(true);
5421 return A;
5422 }
5423
5424 ObjCBoxableAttr(SourceRange R, ASTContext &Ctx
5425 , unsigned SI
5426 )
5427 : Attr(attr::ObjCBoxable, R, SI, false)
5428 {
5429 }
5430
5431 ObjCBoxableAttr *clone(ASTContext &C) const;
5432 void printPretty(raw_ostream &OS,
5433 const PrintingPolicy &Policy) const;
5434 const char *getSpelling() const;
5435
5436
5437 static bool classof(const Attr *A) { return A->getKind() == attr::ObjCBoxable; }
5438};
5439
5440class ObjCBridgeAttr : public InheritableAttr {
5441IdentifierInfo * bridgedType;
5442
5443public:
5444 static ObjCBridgeAttr *CreateImplicit(ASTContext &Ctx, IdentifierInfo * BridgedType, SourceRange Loc = SourceRange()) {
5445 auto *A = new (Ctx) ObjCBridgeAttr(Loc, Ctx, BridgedType, 0);
5446 A->setImplicit(true);
5447 return A;
5448 }
5449
5450 ObjCBridgeAttr(SourceRange R, ASTContext &Ctx
5451 , IdentifierInfo * BridgedType
5452 , unsigned SI
5453 )
5454 : InheritableAttr(attr::ObjCBridge, R, SI, false, false)
5455 , bridgedType(BridgedType)
5456 {
5457 }
5458
5459 ObjCBridgeAttr *clone(ASTContext &C) const;
5460 void printPretty(raw_ostream &OS,
5461 const PrintingPolicy &Policy) const;
5462 const char *getSpelling() const;
5463 IdentifierInfo * getBridgedType() const {
5464 return bridgedType;
5465 }
5466
5467
5468
5469 static bool classof(const Attr *A) { return A->getKind() == attr::ObjCBridge; }
5470};
5471
5472class ObjCBridgeMutableAttr : public InheritableAttr {
5473IdentifierInfo * bridgedType;
5474
5475public:
5476 static ObjCBridgeMutableAttr *CreateImplicit(ASTContext &Ctx, IdentifierInfo * BridgedType, SourceRange Loc = SourceRange()) {
5477 auto *A = new (Ctx) ObjCBridgeMutableAttr(Loc, Ctx, BridgedType, 0);
5478 A->setImplicit(true);
5479 return A;
5480 }
5481
5482 ObjCBridgeMutableAttr(SourceRange R, ASTContext &Ctx
5483 , IdentifierInfo * BridgedType
5484 , unsigned SI
5485 )
5486 : InheritableAttr(attr::ObjCBridgeMutable, R, SI, false, false)
5487 , bridgedType(BridgedType)
5488 {
5489 }
5490
5491 ObjCBridgeMutableAttr *clone(ASTContext &C) const;
5492 void printPretty(raw_ostream &OS,
5493 const PrintingPolicy &Policy) const;
5494 const char *getSpelling() const;
5495 IdentifierInfo * getBridgedType() const {
5496 return bridgedType;
5497 }
5498
5499
5500
5501 static bool classof(const Attr *A) { return A->getKind() == attr::ObjCBridgeMutable; }
5502};
5503
5504class ObjCBridgeRelatedAttr : public InheritableAttr {
5505IdentifierInfo * relatedClass;
5506
5507IdentifierInfo * classMethod;
5508
5509IdentifierInfo * instanceMethod;
5510
5511public:
5512 static ObjCBridgeRelatedAttr *CreateImplicit(ASTContext &Ctx, IdentifierInfo * RelatedClass, IdentifierInfo * ClassMethod, IdentifierInfo * InstanceMethod, SourceRange Loc = SourceRange()) {
5513 auto *A = new (Ctx) ObjCBridgeRelatedAttr(Loc, Ctx, RelatedClass, ClassMethod, InstanceMethod, 0);
5514 A->setImplicit(true);
5515 return A;
5516 }
5517
5518 ObjCBridgeRelatedAttr(SourceRange R, ASTContext &Ctx
5519 , IdentifierInfo * RelatedClass
5520 , IdentifierInfo * ClassMethod
5521 , IdentifierInfo * InstanceMethod
5522 , unsigned SI
5523 )
5524 : InheritableAttr(attr::ObjCBridgeRelated, R, SI, false, false)
5525 , relatedClass(RelatedClass)
5526 , classMethod(ClassMethod)
5527 , instanceMethod(InstanceMethod)
5528 {
5529 }
5530
5531 ObjCBridgeRelatedAttr *clone(ASTContext &C) const;
5532 void printPretty(raw_ostream &OS,
5533 const PrintingPolicy &Policy) const;
5534 const char *getSpelling() const;
5535 IdentifierInfo * getRelatedClass() const {
5536 return relatedClass;
5537 }
5538
5539 IdentifierInfo * getClassMethod() const {
5540 return classMethod;
5541 }
5542
5543 IdentifierInfo * getInstanceMethod() const {
5544 return instanceMethod;
5545 }
5546
5547
5548
5549 static bool classof(const Attr *A) { return A->getKind() == attr::ObjCBridgeRelated; }
5550};
5551
5552class ObjCDesignatedInitializerAttr : public Attr {
5553public:
5554 static ObjCDesignatedInitializerAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
5555 auto *A = new (Ctx) ObjCDesignatedInitializerAttr(Loc, Ctx, 0);
5556 A->setImplicit(true);
5557 return A;
5558 }
5559
5560 ObjCDesignatedInitializerAttr(SourceRange R, ASTContext &Ctx
5561 , unsigned SI
5562 )
5563 : Attr(attr::ObjCDesignatedInitializer, R, SI, false)
5564 {
5565 }
5566
5567 ObjCDesignatedInitializerAttr *clone(ASTContext &C) const;
5568 void printPretty(raw_ostream &OS,
5569 const PrintingPolicy &Policy) const;
5570 const char *getSpelling() const;
5571
5572
5573 static bool classof(const Attr *A) { return A->getKind() == attr::ObjCDesignatedInitializer; }
5574};
5575
5576class ObjCExceptionAttr : public InheritableAttr {
5577public:
5578 static ObjCExceptionAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
5579 auto *A = new (Ctx) ObjCExceptionAttr(Loc, Ctx, 0);
5580 A->setImplicit(true);
5581 return A;
5582 }
5583
5584 ObjCExceptionAttr(SourceRange R, ASTContext &Ctx
5585 , unsigned SI
5586 )
5587 : InheritableAttr(attr::ObjCException, R, SI, false, false)
5588 {
5589 }
5590
5591 ObjCExceptionAttr *clone(ASTContext &C) const;
5592 void printPretty(raw_ostream &OS,
5593 const PrintingPolicy &Policy) const;
5594 const char *getSpelling() const;
5595
5596
5597 static bool classof(const Attr *A) { return A->getKind() == attr::ObjCException; }
5598};
5599
5600class ObjCExplicitProtocolImplAttr : public InheritableAttr {
5601public:
5602 static ObjCExplicitProtocolImplAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
5603 auto *A = new (Ctx) ObjCExplicitProtocolImplAttr(Loc, Ctx, 0);
5604 A->setImplicit(true);
5605 return A;
5606 }
5607
5608 ObjCExplicitProtocolImplAttr(SourceRange R, ASTContext &Ctx
5609 , unsigned SI
5610 )
5611 : InheritableAttr(attr::ObjCExplicitProtocolImpl, R, SI, false, false)
5612 {
5613 }
5614
5615 ObjCExplicitProtocolImplAttr *clone(ASTContext &C) const;
5616 void printPretty(raw_ostream &OS,
5617 const PrintingPolicy &Policy) const;
5618 const char *getSpelling() const;
5619
5620
5621 static bool classof(const Attr *A) { return A->getKind() == attr::ObjCExplicitProtocolImpl; }
5622};
5623
5624class ObjCIndependentClassAttr : public InheritableAttr {
5625public:
5626 static ObjCIndependentClassAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
5627 auto *A = new (Ctx) ObjCIndependentClassAttr(Loc, Ctx, 0);
5628 A->setImplicit(true);
5629 return A;
5630 }
5631
5632 ObjCIndependentClassAttr(SourceRange R, ASTContext &Ctx
5633 , unsigned SI
5634 )
5635 : InheritableAttr(attr::ObjCIndependentClass, R, SI, false, false)
5636 {
5637 }
5638
5639 ObjCIndependentClassAttr *clone(ASTContext &C) const;
5640 void printPretty(raw_ostream &OS,
5641 const PrintingPolicy &Policy) const;
5642 const char *getSpelling() const;
5643
5644
5645 static bool classof(const Attr *A) { return A->getKind() == attr::ObjCIndependentClass; }
5646};
5647
5648class ObjCMethodFamilyAttr : public InheritableAttr {
5649public:
5650 enum FamilyKind {
5651 OMF_None,
5652 OMF_alloc,
5653 OMF_copy,
5654 OMF_init,
5655 OMF_mutableCopy,
5656 OMF_new
5657 };
5658private:
5659 FamilyKind family;
5660
5661public:
5662 static ObjCMethodFamilyAttr *CreateImplicit(ASTContext &Ctx, FamilyKind Family, SourceRange Loc = SourceRange()) {
5663 auto *A = new (Ctx) ObjCMethodFamilyAttr(Loc, Ctx, Family, 0);
5664 A->setImplicit(true);
5665 return A;
5666 }
5667
5668 ObjCMethodFamilyAttr(SourceRange R, ASTContext &Ctx
5669 , FamilyKind Family
5670 , unsigned SI
5671 )
5672 : InheritableAttr(attr::ObjCMethodFamily, R, SI, false, false)
5673 , family(Family)
5674 {
5675 }
5676
5677 ObjCMethodFamilyAttr *clone(ASTContext &C) const;
5678 void printPretty(raw_ostream &OS,
5679 const PrintingPolicy &Policy) const;
5680 const char *getSpelling() const;
5681 FamilyKind getFamily() const {
5682 return family;
5683 }
5684
5685 static bool ConvertStrToFamilyKind(StringRef Val, FamilyKind &Out) {
5686 Optional<FamilyKind> R = llvm::StringSwitch<Optional<FamilyKind>>(Val)
5687 .Case("none", ObjCMethodFamilyAttr::OMF_None)
5688 .Case("alloc", ObjCMethodFamilyAttr::OMF_alloc)
5689 .Case("copy", ObjCMethodFamilyAttr::OMF_copy)
5690 .Case("init", ObjCMethodFamilyAttr::OMF_init)
5691 .Case("mutableCopy", ObjCMethodFamilyAttr::OMF_mutableCopy)
5692 .Case("new", ObjCMethodFamilyAttr::OMF_new)
5693 .Default(Optional<FamilyKind>());
5694 if (R) {
5695 Out = *R;
5696 return true;
5697 }
5698 return false;
5699 }
5700
5701 static const char *ConvertFamilyKindToStr(FamilyKind Val) {
5702 switch(Val) {
5703 case ObjCMethodFamilyAttr::OMF_None: return "none";
5704 case ObjCMethodFamilyAttr::OMF_alloc: return "alloc";
5705 case ObjCMethodFamilyAttr::OMF_copy: return "copy";
5706 case ObjCMethodFamilyAttr::OMF_init: return "init";
5707 case ObjCMethodFamilyAttr::OMF_mutableCopy: return "mutableCopy";
5708 case ObjCMethodFamilyAttr::OMF_new: return "new";
5709 }
5710 llvm_unreachable("No enumerator with that value")::llvm::llvm_unreachable_internal("No enumerator with that value"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 5710)
;
5711 }
5712
5713
5714 static bool classof(const Attr *A) { return A->getKind() == attr::ObjCMethodFamily; }
5715};
5716
5717class ObjCNSObjectAttr : public InheritableAttr {
5718public:
5719 static ObjCNSObjectAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
5720 auto *A = new (Ctx) ObjCNSObjectAttr(Loc, Ctx, 0);
5721 A->setImplicit(true);
5722 return A;
5723 }
5724
5725 ObjCNSObjectAttr(SourceRange R, ASTContext &Ctx
5726 , unsigned SI
5727 )
5728 : InheritableAttr(attr::ObjCNSObject, R, SI, false, false)
5729 {
5730 }
5731
5732 ObjCNSObjectAttr *clone(ASTContext &C) const;
5733 void printPretty(raw_ostream &OS,
5734 const PrintingPolicy &Policy) const;
5735 const char *getSpelling() const;
5736
5737
5738 static bool classof(const Attr *A) { return A->getKind() == attr::ObjCNSObject; }
5739};
5740
5741class ObjCPreciseLifetimeAttr : public InheritableAttr {
5742public:
5743 static ObjCPreciseLifetimeAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
5744 auto *A = new (Ctx) ObjCPreciseLifetimeAttr(Loc, Ctx, 0);
5745 A->setImplicit(true);
5746 return A;
5747 }
5748
5749 ObjCPreciseLifetimeAttr(SourceRange R, ASTContext &Ctx
5750 , unsigned SI
5751 )
5752 : InheritableAttr(attr::ObjCPreciseLifetime, R, SI, false, false)
5753 {
5754 }
5755
5756 ObjCPreciseLifetimeAttr *clone(ASTContext &C) const;
5757 void printPretty(raw_ostream &OS,
5758 const PrintingPolicy &Policy) const;
5759 const char *getSpelling() const;
5760
5761
5762 static bool classof(const Attr *A) { return A->getKind() == attr::ObjCPreciseLifetime; }
5763};
5764
5765class ObjCRequiresPropertyDefsAttr : public InheritableAttr {
5766public:
5767 static ObjCRequiresPropertyDefsAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
5768 auto *A = new (Ctx) ObjCRequiresPropertyDefsAttr(Loc, Ctx, 0);
5769 A->setImplicit(true);
5770 return A;
5771 }
5772
5773 ObjCRequiresPropertyDefsAttr(SourceRange R, ASTContext &Ctx
5774 , unsigned SI
5775 )
5776 : InheritableAttr(attr::ObjCRequiresPropertyDefs, R, SI, false, false)
5777 {
5778 }
5779
5780 ObjCRequiresPropertyDefsAttr *clone(ASTContext &C) const;
5781 void printPretty(raw_ostream &OS,
5782 const PrintingPolicy &Policy) const;
5783 const char *getSpelling() const;
5784
5785
5786 static bool classof(const Attr *A) { return A->getKind() == attr::ObjCRequiresPropertyDefs; }
5787};
5788
5789class ObjCRequiresSuperAttr : public InheritableAttr {
5790public:
5791 static ObjCRequiresSuperAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
5792 auto *A = new (Ctx) ObjCRequiresSuperAttr(Loc, Ctx, 0);
5793 A->setImplicit(true);
5794 return A;
5795 }
5796
5797 ObjCRequiresSuperAttr(SourceRange R, ASTContext &Ctx
5798 , unsigned SI
5799 )
5800 : InheritableAttr(attr::ObjCRequiresSuper, R, SI, false, false)
5801 {
5802 }
5803
5804 ObjCRequiresSuperAttr *clone(ASTContext &C) const;
5805 void printPretty(raw_ostream &OS,
5806 const PrintingPolicy &Policy) const;
5807 const char *getSpelling() const;
5808
5809
5810 static bool classof(const Attr *A) { return A->getKind() == attr::ObjCRequiresSuper; }
5811};
5812
5813class ObjCReturnsInnerPointerAttr : public InheritableAttr {
5814public:
5815 static ObjCReturnsInnerPointerAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
5816 auto *A = new (Ctx) ObjCReturnsInnerPointerAttr(Loc, Ctx, 0);
5817 A->setImplicit(true);
5818 return A;
5819 }
5820
5821 ObjCReturnsInnerPointerAttr(SourceRange R, ASTContext &Ctx
5822 , unsigned SI
5823 )
5824 : InheritableAttr(attr::ObjCReturnsInnerPointer, R, SI, false, false)
5825 {
5826 }
5827
5828 ObjCReturnsInnerPointerAttr *clone(ASTContext &C) const;
5829 void printPretty(raw_ostream &OS,
5830 const PrintingPolicy &Policy) const;
5831 const char *getSpelling() const;
5832
5833
5834 static bool classof(const Attr *A) { return A->getKind() == attr::ObjCReturnsInnerPointer; }
5835};
5836
5837class ObjCRootClassAttr : public InheritableAttr {
5838public:
5839 static ObjCRootClassAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
5840 auto *A = new (Ctx) ObjCRootClassAttr(Loc, Ctx, 0);
5841 A->setImplicit(true);
5842 return A;
5843 }
5844
5845 ObjCRootClassAttr(SourceRange R, ASTContext &Ctx
5846 , unsigned SI
5847 )
5848 : InheritableAttr(attr::ObjCRootClass, R, SI, false, false)
5849 {
5850 }
5851
5852 ObjCRootClassAttr *clone(ASTContext &C) const;
5853 void printPretty(raw_ostream &OS,
5854 const PrintingPolicy &Policy) const;
5855 const char *getSpelling() const;
5856
5857
5858 static bool classof(const Attr *A) { return A->getKind() == attr::ObjCRootClass; }
5859};
5860
5861class ObjCRuntimeNameAttr : public Attr {
5862unsigned metadataNameLength;
5863char *metadataName;
5864
5865public:
5866 static ObjCRuntimeNameAttr *CreateImplicit(ASTContext &Ctx, llvm::StringRef MetadataName, SourceRange Loc = SourceRange()) {
5867 auto *A = new (Ctx) ObjCRuntimeNameAttr(Loc, Ctx, MetadataName, 0);
5868 A->setImplicit(true);
5869 return A;
5870 }
5871
5872 ObjCRuntimeNameAttr(SourceRange R, ASTContext &Ctx
5873 , llvm::StringRef MetadataName
5874 , unsigned SI
5875 )
5876 : Attr(attr::ObjCRuntimeName, R, SI, false)
5877 , metadataNameLength(MetadataName.size()),metadataName(new (Ctx, 1) char[metadataNameLength])
5878 {
5879 if (!MetadataName.empty())
5880 std::memcpy(metadataName, MetadataName.data(), metadataNameLength);
5881 }
5882
5883 ObjCRuntimeNameAttr *clone(ASTContext &C) const;
5884 void printPretty(raw_ostream &OS,
5885 const PrintingPolicy &Policy) const;
5886 const char *getSpelling() const;
5887 llvm::StringRef getMetadataName() const {
5888 return llvm::StringRef(metadataName, metadataNameLength);
5889 }
5890 unsigned getMetadataNameLength() const {
5891 return metadataNameLength;
5892 }
5893 void setMetadataName(ASTContext &C, llvm::StringRef S) {
5894 metadataNameLength = S.size();
5895 this->metadataName = new (C, 1) char [metadataNameLength];
5896 if (!S.empty())
5897 std::memcpy(this->metadataName, S.data(), metadataNameLength);
5898 }
5899
5900
5901
5902 static bool classof(const Attr *A) { return A->getKind() == attr::ObjCRuntimeName; }
5903};
5904
5905class ObjCRuntimeVisibleAttr : public Attr {
5906public:
5907 static ObjCRuntimeVisibleAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
5908 auto *A = new (Ctx) ObjCRuntimeVisibleAttr(Loc, Ctx, 0);
5909 A->setImplicit(true);
5910 return A;
5911 }
5912
5913 ObjCRuntimeVisibleAttr(SourceRange R, ASTContext &Ctx
5914 , unsigned SI
5915 )
5916 : Attr(attr::ObjCRuntimeVisible, R, SI, false)
5917 {
5918 }
5919
5920 ObjCRuntimeVisibleAttr *clone(ASTContext &C) const;
5921 void printPretty(raw_ostream &OS,
5922 const PrintingPolicy &Policy) const;
5923 const char *getSpelling() const;
5924
5925
5926 static bool classof(const Attr *A) { return A->getKind() == attr::ObjCRuntimeVisible; }
5927};
5928
5929class ObjCSubclassingRestrictedAttr : public InheritableAttr {
5930public:
5931 static ObjCSubclassingRestrictedAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
5932 auto *A = new (Ctx) ObjCSubclassingRestrictedAttr(Loc, Ctx, 0);
5933 A->setImplicit(true);
5934 return A;
5935 }
5936
5937 ObjCSubclassingRestrictedAttr(SourceRange R, ASTContext &Ctx
5938 , unsigned SI
5939 )
5940 : InheritableAttr(attr::ObjCSubclassingRestricted, R, SI, false, false)
5941 {
5942 }
5943
5944 ObjCSubclassingRestrictedAttr *clone(ASTContext &C) const;
5945 void printPretty(raw_ostream &OS,
5946 const PrintingPolicy &Policy) const;
5947 const char *getSpelling() const;
5948
5949
5950 static bool classof(const Attr *A) { return A->getKind() == attr::ObjCSubclassingRestricted; }
5951};
5952
5953class OpenCLAccessAttr : public Attr {
5954public:
5955 enum Spelling {
5956 Keyword_read_only = 0,
5957 Keyword_write_only = 2,
5958 Keyword_read_write = 4
5959 };
5960
5961 static OpenCLAccessAttr *CreateImplicit(ASTContext &Ctx, Spelling S, SourceRange Loc = SourceRange()) {
5962 auto *A = new (Ctx) OpenCLAccessAttr(Loc, Ctx, S);
5963 A->setImplicit(true);
5964 return A;
5965 }
5966
5967 OpenCLAccessAttr(SourceRange R, ASTContext &Ctx
5968 , unsigned SI
5969 )
5970 : Attr(attr::OpenCLAccess, R, SI, false)
5971 {
5972 }
5973
5974 OpenCLAccessAttr *clone(ASTContext &C) const;
5975 void printPretty(raw_ostream &OS,
5976 const PrintingPolicy &Policy) const;
5977 const char *getSpelling() const;
5978 Spelling getSemanticSpelling() const {
5979 switch (SpellingListIndex) {
5980 default: llvm_unreachable("Unknown spelling list index")::llvm::llvm_unreachable_internal("Unknown spelling list index"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 5980)
;
5981 case 0: return Keyword_read_only;
5982 case 1: return Keyword_read_only;
5983 case 2: return Keyword_write_only;
5984 case 3: return Keyword_write_only;
5985 case 4: return Keyword_read_write;
5986 case 5: return Keyword_read_write;
5987 }
5988 }
5989 bool isReadOnly() const { return SpellingListIndex == 0 ||
5990 SpellingListIndex == 1; }
5991 bool isReadWrite() const { return SpellingListIndex == 4 ||
5992 SpellingListIndex == 5; }
5993 bool isWriteOnly() const { return SpellingListIndex == 2 ||
5994 SpellingListIndex == 3; }
5995
5996
5997 static bool classof(const Attr *A) { return A->getKind() == attr::OpenCLAccess; }
5998};
5999
6000class OpenCLIntelReqdSubGroupSizeAttr : public InheritableAttr {
6001unsigned subGroupSize;
6002
6003public:
6004 static OpenCLIntelReqdSubGroupSizeAttr *CreateImplicit(ASTContext &Ctx, unsigned SubGroupSize, SourceRange Loc = SourceRange()) {
6005 auto *A = new (Ctx) OpenCLIntelReqdSubGroupSizeAttr(Loc, Ctx, SubGroupSize, 0);
6006 A->setImplicit(true);
6007 return A;
6008 }
6009
6010 OpenCLIntelReqdSubGroupSizeAttr(SourceRange R, ASTContext &Ctx
6011 , unsigned SubGroupSize
6012 , unsigned SI
6013 )
6014 : InheritableAttr(attr::OpenCLIntelReqdSubGroupSize, R, SI, false, false)
6015 , subGroupSize(SubGroupSize)
6016 {
6017 }
6018
6019 OpenCLIntelReqdSubGroupSizeAttr *clone(ASTContext &C) const;
6020 void printPretty(raw_ostream &OS,
6021 const PrintingPolicy &Policy) const;
6022 const char *getSpelling() const;
6023 unsigned getSubGroupSize() const {
6024 return subGroupSize;
6025 }
6026
6027
6028
6029 static bool classof(const Attr *A) { return A->getKind() == attr::OpenCLIntelReqdSubGroupSize; }
6030};
6031
6032class OpenCLKernelAttr : public InheritableAttr {
6033public:
6034 static OpenCLKernelAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
6035 auto *A = new (Ctx) OpenCLKernelAttr(Loc, Ctx, 0);
6036 A->setImplicit(true);
6037 return A;
6038 }
6039
6040 OpenCLKernelAttr(SourceRange R, ASTContext &Ctx
6041 , unsigned SI
6042 )
6043 : InheritableAttr(attr::OpenCLKernel, R, SI, false, false)
6044 {
6045 }
6046
6047 OpenCLKernelAttr *clone(ASTContext &C) const;
6048 void printPretty(raw_ostream &OS,
6049 const PrintingPolicy &Policy) const;
6050 const char *getSpelling() const;
6051
6052
6053 static bool classof(const Attr *A) { return A->getKind() == attr::OpenCLKernel; }
6054};
6055
6056class OpenCLUnrollHintAttr : public InheritableAttr {
6057unsigned unrollHint;
6058
6059public:
6060 static OpenCLUnrollHintAttr *CreateImplicit(ASTContext &Ctx, unsigned UnrollHint, SourceRange Loc = SourceRange()) {
6061 auto *A = new (Ctx) OpenCLUnrollHintAttr(Loc, Ctx, UnrollHint, 0);
6062 A->setImplicit(true);
6063 return A;
6064 }
6065
6066 OpenCLUnrollHintAttr(SourceRange R, ASTContext &Ctx
6067 , unsigned UnrollHint
6068 , unsigned SI
6069 )
6070 : InheritableAttr(attr::OpenCLUnrollHint, R, SI, false, false)
6071 , unrollHint(UnrollHint)
6072 {
6073 }
6074
6075 OpenCLUnrollHintAttr *clone(ASTContext &C) const;
6076 void printPretty(raw_ostream &OS,
6077 const PrintingPolicy &Policy) const;
6078 const char *getSpelling() const;
6079 unsigned getUnrollHint() const {
6080 return unrollHint;
6081 }
6082
6083
6084
6085 static bool classof(const Attr *A) { return A->getKind() == attr::OpenCLUnrollHint; }
6086};
6087
6088class OptimizeNoneAttr : public InheritableAttr {
6089public:
6090 static OptimizeNoneAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
6091 auto *A = new (Ctx) OptimizeNoneAttr(Loc, Ctx, 0);
6092 A->setImplicit(true);
6093 return A;
6094 }
6095
6096 OptimizeNoneAttr(SourceRange R, ASTContext &Ctx
6097 , unsigned SI
6098 )
6099 : InheritableAttr(attr::OptimizeNone, R, SI, false, false)
6100 {
6101 }
6102
6103 OptimizeNoneAttr *clone(ASTContext &C) const;
6104 void printPretty(raw_ostream &OS,
6105 const PrintingPolicy &Policy) const;
6106 const char *getSpelling() const;
6107
6108
6109 static bool classof(const Attr *A) { return A->getKind() == attr::OptimizeNone; }
6110};
6111
6112class OverloadableAttr : public Attr {
6113public:
6114 static OverloadableAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
6115 auto *A = new (Ctx) OverloadableAttr(Loc, Ctx, 0);
6116 A->setImplicit(true);
6117 return A;
6118 }
6119
6120 OverloadableAttr(SourceRange R, ASTContext &Ctx
6121 , unsigned SI
6122 )
6123 : Attr(attr::Overloadable, R, SI, false)
6124 {
6125 }
6126
6127 OverloadableAttr *clone(ASTContext &C) const;
6128 void printPretty(raw_ostream &OS,
6129 const PrintingPolicy &Policy) const;
6130 const char *getSpelling() const;
6131
6132
6133 static bool classof(const Attr *A) { return A->getKind() == attr::Overloadable; }
6134};
6135
6136class OverrideAttr : public InheritableAttr {
6137public:
6138 static OverrideAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
6139 auto *A = new (Ctx) OverrideAttr(Loc, Ctx, 0);
6140 A->setImplicit(true);
6141 return A;
6142 }
6143
6144 OverrideAttr(SourceRange R, ASTContext &Ctx
6145 , unsigned SI
6146 )
6147 : InheritableAttr(attr::Override, R, SI, false, false)
6148 {
6149 }
6150
6151 OverrideAttr *clone(ASTContext &C) const;
6152 void printPretty(raw_ostream &OS,
6153 const PrintingPolicy &Policy) const;
6154 const char *getSpelling() const;
6155
6156
6157 static bool classof(const Attr *A) { return A->getKind() == attr::Override; }
6158};
6159
6160class OwnershipAttr : public InheritableAttr {
6161IdentifierInfo * module;
6162
6163 unsigned args_Size;
6164 ParamIdx *args_;
6165
6166public:
6167 enum Spelling {
6168 GNU_ownership_holds = 0,
6169 CXX11_clang_ownership_holds = 1,
6170 C2x_clang_ownership_holds = 2,
6171 GNU_ownership_returns = 3,
6172 CXX11_clang_ownership_returns = 4,
6173 C2x_clang_ownership_returns = 5,
6174 GNU_ownership_takes = 6,
6175 CXX11_clang_ownership_takes = 7,
6176 C2x_clang_ownership_takes = 8
6177 };
6178
6179 static OwnershipAttr *CreateImplicit(ASTContext &Ctx, Spelling S, IdentifierInfo * Module, ParamIdx *Args, unsigned ArgsSize, SourceRange Loc = SourceRange()) {
6180 auto *A = new (Ctx) OwnershipAttr(Loc, Ctx, Module, Args, ArgsSize, S);
6181 A->setImplicit(true);
6182 return A;
6183 }
6184
6185 OwnershipAttr(SourceRange R, ASTContext &Ctx
6186 , IdentifierInfo * Module
6187 , ParamIdx *Args, unsigned ArgsSize
6188 , unsigned SI
6189 )
6190 : InheritableAttr(attr::Ownership, R, SI, false, false)
6191 , module(Module)
6192 , args_Size(ArgsSize), args_(new (Ctx, 16) ParamIdx[args_Size])
6193 {
6194 std::copy(Args, Args + args_Size, args_);
6195 }
6196
6197 OwnershipAttr(SourceRange R, ASTContext &Ctx
6198 , IdentifierInfo * Module
6199 , unsigned SI
6200 )
6201 : InheritableAttr(attr::Ownership, R, SI, false, false)
6202 , module(Module)
6203 , args_Size(0), args_(nullptr)
6204 {
6205 }
6206
6207 OwnershipAttr *clone(ASTContext &C) const;
6208 void printPretty(raw_ostream &OS,
6209 const PrintingPolicy &Policy) const;
6210 const char *getSpelling() const;
6211 Spelling getSemanticSpelling() const {
6212 switch (SpellingListIndex) {
6213 default: llvm_unreachable("Unknown spelling list index")::llvm::llvm_unreachable_internal("Unknown spelling list index"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 6213)
;
6214 case 0: return GNU_ownership_holds;
6215 case 1: return CXX11_clang_ownership_holds;
6216 case 2: return C2x_clang_ownership_holds;
6217 case 3: return GNU_ownership_returns;
6218 case 4: return CXX11_clang_ownership_returns;
6219 case 5: return C2x_clang_ownership_returns;
6220 case 6: return GNU_ownership_takes;
6221 case 7: return CXX11_clang_ownership_takes;
6222 case 8: return C2x_clang_ownership_takes;
6223 }
6224 }
6225 bool isHolds() const { return SpellingListIndex == 0 ||
6226 SpellingListIndex == 1 ||
6227 SpellingListIndex == 2; }
6228 bool isReturns() const { return SpellingListIndex == 3 ||
6229 SpellingListIndex == 4 ||
6230 SpellingListIndex == 5; }
6231 bool isTakes() const { return SpellingListIndex == 6 ||
6232 SpellingListIndex == 7 ||
6233 SpellingListIndex == 8; }
6234 IdentifierInfo * getModule() const {
6235 return module;
6236 }
6237
6238 typedef ParamIdx* args_iterator;
6239 args_iterator args_begin() const { return args_; }
6240 args_iterator args_end() const { return args_ + args_Size; }
6241 unsigned args_size() const { return args_Size; }
6242 llvm::iterator_range<args_iterator> args() const { return llvm::make_range(args_begin(), args_end()); }
6243
6244
6245
6246 enum OwnershipKind { Holds, Returns, Takes };
6247 OwnershipKind getOwnKind() const {
6248 return isHolds() ? Holds :
6249 isTakes() ? Takes :
6250 Returns;
6251 }
6252
6253
6254 static bool classof(const Attr *A) { return A->getKind() == attr::Ownership; }
6255};
6256
6257class PackedAttr : public InheritableAttr {
6258public:
6259 static PackedAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
6260 auto *A = new (Ctx) PackedAttr(Loc, Ctx, 0);
6261 A->setImplicit(true);
6262 return A;
6263 }
6264
6265 PackedAttr(SourceRange R, ASTContext &Ctx
6266 , unsigned SI
6267 )
6268 : InheritableAttr(attr::Packed, R, SI, false, false)
6269 {
6270 }
6271
6272 PackedAttr *clone(ASTContext &C) const;
6273 void printPretty(raw_ostream &OS,
6274 const PrintingPolicy &Policy) const;
6275 const char *getSpelling() const;
6276
6277
6278 static bool classof(const Attr *A) { return A->getKind() == attr::Packed; }
6279};
6280
6281class ParamTypestateAttr : public InheritableAttr {
6282public:
6283 enum ConsumedState {
6284 Unknown,
6285 Consumed,
6286 Unconsumed
6287 };
6288private:
6289 ConsumedState paramState;
6290
6291public:
6292 static ParamTypestateAttr *CreateImplicit(ASTContext &Ctx, ConsumedState ParamState, SourceRange Loc = SourceRange()) {
6293 auto *A = new (Ctx) ParamTypestateAttr(Loc, Ctx, ParamState, 0);
6294 A->setImplicit(true);
6295 return A;
6296 }
6297
6298 ParamTypestateAttr(SourceRange R, ASTContext &Ctx
6299 , ConsumedState ParamState
6300 , unsigned SI
6301 )
6302 : InheritableAttr(attr::ParamTypestate, R, SI, false, false)
6303 , paramState(ParamState)
6304 {
6305 }
6306
6307 ParamTypestateAttr *clone(ASTContext &C) const;
6308 void printPretty(raw_ostream &OS,
6309 const PrintingPolicy &Policy) const;
6310 const char *getSpelling() const;
6311 ConsumedState getParamState() const {
6312 return paramState;
6313 }
6314
6315 static bool ConvertStrToConsumedState(StringRef Val, ConsumedState &Out) {
6316 Optional<ConsumedState> R = llvm::StringSwitch<Optional<ConsumedState>>(Val)
6317 .Case("unknown", ParamTypestateAttr::Unknown)
6318 .Case("consumed", ParamTypestateAttr::Consumed)
6319 .Case("unconsumed", ParamTypestateAttr::Unconsumed)
6320 .Default(Optional<ConsumedState>());
6321 if (R) {
6322 Out = *R;
6323 return true;
6324 }
6325 return false;
6326 }
6327
6328 static const char *ConvertConsumedStateToStr(ConsumedState Val) {
6329 switch(Val) {
6330 case ParamTypestateAttr::Unknown: return "unknown";
6331 case ParamTypestateAttr::Consumed: return "consumed";
6332 case ParamTypestateAttr::Unconsumed: return "unconsumed";
6333 }
6334 llvm_unreachable("No enumerator with that value")::llvm::llvm_unreachable_internal("No enumerator with that value"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 6334)
;
6335 }
6336
6337
6338 static bool classof(const Attr *A) { return A->getKind() == attr::ParamTypestate; }
6339};
6340
6341class PascalAttr : public InheritableAttr {
6342public:
6343 static PascalAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
6344 auto *A = new (Ctx) PascalAttr(Loc, Ctx, 0);
6345 A->setImplicit(true);
6346 return A;
6347 }
6348
6349 PascalAttr(SourceRange R, ASTContext &Ctx
6350 , unsigned SI
6351 )
6352 : InheritableAttr(attr::Pascal, R, SI, false, false)
6353 {
6354 }
6355
6356 PascalAttr *clone(ASTContext &C) const;
6357 void printPretty(raw_ostream &OS,
6358 const PrintingPolicy &Policy) const;
6359 const char *getSpelling() const;
6360
6361
6362 static bool classof(const Attr *A) { return A->getKind() == attr::Pascal; }
6363};
6364
6365class PassObjectSizeAttr : public InheritableParamAttr {
6366int type;
6367
6368public:
6369 static PassObjectSizeAttr *CreateImplicit(ASTContext &Ctx, int Type, SourceRange Loc = SourceRange()) {
6370 auto *A = new (Ctx) PassObjectSizeAttr(Loc, Ctx, Type, 0);
6371 A->setImplicit(true);
6372 return A;
6373 }
6374
6375 PassObjectSizeAttr(SourceRange R, ASTContext &Ctx
6376 , int Type
6377 , unsigned SI
6378 )
6379 : InheritableParamAttr(attr::PassObjectSize, R, SI, false, false)
6380 , type(Type)
6381 {
6382 }
6383
6384 PassObjectSizeAttr *clone(ASTContext &C) const;
6385 void printPretty(raw_ostream &OS,
6386 const PrintingPolicy &Policy) const;
6387 const char *getSpelling() const;
6388 int getType() const {
6389 return type;
6390 }
6391
6392
6393
6394 static bool classof(const Attr *A) { return A->getKind() == attr::PassObjectSize; }
6395};
6396
6397class PcsAttr : public InheritableAttr {
6398public:
6399 enum PCSType {
6400 AAPCS,
6401 AAPCS_VFP
6402 };
6403private:
6404 PCSType pCS;
6405
6406public:
6407 static PcsAttr *CreateImplicit(ASTContext &Ctx, PCSType PCS, SourceRange Loc = SourceRange()) {
6408 auto *A = new (Ctx) PcsAttr(Loc, Ctx, PCS, 0);
6409 A->setImplicit(true);
6410 return A;
6411 }
6412
6413 PcsAttr(SourceRange R, ASTContext &Ctx
6414 , PCSType PCS
6415 , unsigned SI
6416 )
6417 : InheritableAttr(attr::Pcs, R, SI, false, false)
6418 , pCS(PCS)
6419 {
6420 }
6421
6422 PcsAttr *clone(ASTContext &C) const;
6423 void printPretty(raw_ostream &OS,
6424 const PrintingPolicy &Policy) const;
6425 const char *getSpelling() const;
6426 PCSType getPCS() const {
6427 return pCS;
6428 }
6429
6430 static bool ConvertStrToPCSType(StringRef Val, PCSType &Out) {
6431 Optional<PCSType> R = llvm::StringSwitch<Optional<PCSType>>(Val)
6432 .Case("aapcs", PcsAttr::AAPCS)
6433 .Case("aapcs-vfp", PcsAttr::AAPCS_VFP)
6434 .Default(Optional<PCSType>());
6435 if (R) {
6436 Out = *R;
6437 return true;
6438 }
6439 return false;
6440 }
6441
6442 static const char *ConvertPCSTypeToStr(PCSType Val) {
6443 switch(Val) {
6444 case PcsAttr::AAPCS: return "aapcs";
6445 case PcsAttr::AAPCS_VFP: return "aapcs-vfp";
6446 }
6447 llvm_unreachable("No enumerator with that value")::llvm::llvm_unreachable_internal("No enumerator with that value"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 6447)
;
6448 }
6449
6450
6451 static bool classof(const Attr *A) { return A->getKind() == attr::Pcs; }
6452};
6453
6454class PragmaClangBSSSectionAttr : public InheritableAttr {
6455unsigned nameLength;
6456char *name;
6457
6458public:
6459 static PragmaClangBSSSectionAttr *CreateImplicit(ASTContext &Ctx, llvm::StringRef Name, SourceRange Loc = SourceRange()) {
6460 auto *A = new (Ctx) PragmaClangBSSSectionAttr(Loc, Ctx, Name, 0);
6461 A->setImplicit(true);
6462 return A;
6463 }
6464
6465 PragmaClangBSSSectionAttr(SourceRange R, ASTContext &Ctx
6466 , llvm::StringRef Name
6467 , unsigned SI
6468 )
6469 : InheritableAttr(attr::PragmaClangBSSSection, R, SI, false, false)
6470 , nameLength(Name.size()),name(new (Ctx, 1) char[nameLength])
6471 {
6472 if (!Name.empty())
6473 std::memcpy(name, Name.data(), nameLength);
6474 }
6475
6476 PragmaClangBSSSectionAttr *clone(ASTContext &C) const;
6477 void printPretty(raw_ostream &OS,
6478 const PrintingPolicy &Policy) const;
6479 const char *getSpelling() const;
6480 llvm::StringRef getName() const {
6481 return llvm::StringRef(name, nameLength);
6482 }
6483 unsigned getNameLength() const {
6484 return nameLength;
6485 }
6486 void setName(ASTContext &C, llvm::StringRef S) {
6487 nameLength = S.size();
6488 this->name = new (C, 1) char [nameLength];
6489 if (!S.empty())
6490 std::memcpy(this->name, S.data(), nameLength);
6491 }
6492
6493
6494
6495 static bool classof(const Attr *A) { return A->getKind() == attr::PragmaClangBSSSection; }
6496};
6497
6498class PragmaClangDataSectionAttr : public InheritableAttr {
6499unsigned nameLength;
6500char *name;
6501
6502public:
6503 static PragmaClangDataSectionAttr *CreateImplicit(ASTContext &Ctx, llvm::StringRef Name, SourceRange Loc = SourceRange()) {
6504 auto *A = new (Ctx) PragmaClangDataSectionAttr(Loc, Ctx, Name, 0);
10
Calling constructor for 'PragmaClangDataSectionAttr'
6505 A->setImplicit(true);
6506 return A;
6507 }
6508
6509 PragmaClangDataSectionAttr(SourceRange R, ASTContext &Ctx
6510 , llvm::StringRef Name
6511 , unsigned SI
6512 )
6513 : InheritableAttr(attr::PragmaClangDataSection, R, SI, false, false)
6514 , nameLength(Name.size()),name(new (Ctx, 1) char[nameLength])
11
Null pointer value stored to field 'name'
6515 {
6516 if (!Name.empty())
12
Assuming the condition is true
13
Taking true branch
6517 std::memcpy(name, Name.data(), nameLength);
14
Null pointer passed as an argument to a 'nonnull' parameter
6518 }
6519
6520 PragmaClangDataSectionAttr *clone(ASTContext &C) const;
6521 void printPretty(raw_ostream &OS,
6522 const PrintingPolicy &Policy) const;
6523 const char *getSpelling() const;
6524 llvm::StringRef getName() const {
6525 return llvm::StringRef(name, nameLength);
6526 }
6527 unsigned getNameLength() const {
6528 return nameLength;
6529 }
6530 void setName(ASTContext &C, llvm::StringRef S) {
6531 nameLength = S.size();
6532 this->name = new (C, 1) char [nameLength];
6533 if (!S.empty())
6534 std::memcpy(this->name, S.data(), nameLength);
6535 }
6536
6537
6538
6539 static bool classof(const Attr *A) { return A->getKind() == attr::PragmaClangDataSection; }
6540};
6541
6542class PragmaClangRodataSectionAttr : public InheritableAttr {
6543unsigned nameLength;
6544char *name;
6545
6546public:
6547 static PragmaClangRodataSectionAttr *CreateImplicit(ASTContext &Ctx, llvm::StringRef Name, SourceRange Loc = SourceRange()) {
6548 auto *A = new (Ctx) PragmaClangRodataSectionAttr(Loc, Ctx, Name, 0);
6549 A->setImplicit(true);
6550 return A;
6551 }
6552
6553 PragmaClangRodataSectionAttr(SourceRange R, ASTContext &Ctx
6554 , llvm::StringRef Name
6555 , unsigned SI
6556 )
6557 : InheritableAttr(attr::PragmaClangRodataSection, R, SI, false, false)
6558 , nameLength(Name.size()),name(new (Ctx, 1) char[nameLength])
6559 {
6560 if (!Name.empty())
6561 std::memcpy(name, Name.data(), nameLength);
6562 }
6563
6564 PragmaClangRodataSectionAttr *clone(ASTContext &C) const;
6565 void printPretty(raw_ostream &OS,
6566 const PrintingPolicy &Policy) const;
6567 const char *getSpelling() const;
6568 llvm::StringRef getName() const {
6569 return llvm::StringRef(name, nameLength);
6570 }
6571 unsigned getNameLength() const {
6572 return nameLength;
6573 }
6574 void setName(ASTContext &C, llvm::StringRef S) {
6575 nameLength = S.size();
6576 this->name = new (C, 1) char [nameLength];
6577 if (!S.empty())
6578 std::memcpy(this->name, S.data(), nameLength);
6579 }
6580
6581
6582
6583 static bool classof(const Attr *A) { return A->getKind() == attr::PragmaClangRodataSection; }
6584};
6585
6586class PragmaClangTextSectionAttr : public InheritableAttr {
6587unsigned nameLength;
6588char *name;
6589
6590public:
6591 static PragmaClangTextSectionAttr *CreateImplicit(ASTContext &Ctx, llvm::StringRef Name, SourceRange Loc = SourceRange()) {
6592 auto *A = new (Ctx) PragmaClangTextSectionAttr(Loc, Ctx, Name, 0);
6593 A->setImplicit(true);
6594 return A;
6595 }
6596
6597 PragmaClangTextSectionAttr(SourceRange R, ASTContext &Ctx
6598 , llvm::StringRef Name
6599 , unsigned SI
6600 )
6601 : InheritableAttr(attr::PragmaClangTextSection, R, SI, false, false)
6602 , nameLength(Name.size()),name(new (Ctx, 1) char[nameLength])
6603 {
6604 if (!Name.empty())
6605 std::memcpy(name, Name.data(), nameLength);
6606 }
6607
6608 PragmaClangTextSectionAttr *clone(ASTContext &C) const;
6609 void printPretty(raw_ostream &OS,
6610 const PrintingPolicy &Policy) const;
6611 const char *getSpelling() const;
6612 llvm::StringRef getName() const {
6613 return llvm::StringRef(name, nameLength);
6614 }
6615 unsigned getNameLength() const {
6616 return nameLength;
6617 }
6618 void setName(ASTContext &C, llvm::StringRef S) {
6619 nameLength = S.size();
6620 this->name = new (C, 1) char [nameLength];
6621 if (!S.empty())
6622 std::memcpy(this->name, S.data(), nameLength);
6623 }
6624
6625
6626
6627 static bool classof(const Attr *A) { return A->getKind() == attr::PragmaClangTextSection; }
6628};
6629
6630class PreserveAllAttr : public InheritableAttr {
6631public:
6632 static PreserveAllAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
6633 auto *A = new (Ctx) PreserveAllAttr(Loc, Ctx, 0);
6634 A->setImplicit(true);
6635 return A;
6636 }
6637
6638 PreserveAllAttr(SourceRange R, ASTContext &Ctx
6639 , unsigned SI
6640 )
6641 : InheritableAttr(attr::PreserveAll, R, SI, false, false)
6642 {
6643 }
6644
6645 PreserveAllAttr *clone(ASTContext &C) const;
6646 void printPretty(raw_ostream &OS,
6647 const PrintingPolicy &Policy) const;
6648 const char *getSpelling() const;
6649
6650
6651 static bool classof(const Attr *A) { return A->getKind() == attr::PreserveAll; }
6652};
6653
6654class PreserveMostAttr : public InheritableAttr {
6655public:
6656 static PreserveMostAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
6657 auto *A = new (Ctx) PreserveMostAttr(Loc, Ctx, 0);
6658 A->setImplicit(true);
6659 return A;
6660 }
6661
6662 PreserveMostAttr(SourceRange R, ASTContext &Ctx
6663 , unsigned SI
6664 )
6665 : InheritableAttr(attr::PreserveMost, R, SI, false, false)
6666 {
6667 }
6668
6669 PreserveMostAttr *clone(ASTContext &C) const;
6670 void printPretty(raw_ostream &OS,
6671 const PrintingPolicy &Policy) const;
6672 const char *getSpelling() const;
6673
6674
6675 static bool classof(const Attr *A) { return A->getKind() == attr::PreserveMost; }
6676};
6677
6678class PtGuardedByAttr : public InheritableAttr {
6679Expr * arg;
6680
6681public:
6682 static PtGuardedByAttr *CreateImplicit(ASTContext &Ctx, Expr * Arg, SourceRange Loc = SourceRange()) {
6683 auto *A = new (Ctx) PtGuardedByAttr(Loc, Ctx, Arg, 0);
6684 A->setImplicit(true);
6685 return A;
6686 }
6687
6688 PtGuardedByAttr(SourceRange R, ASTContext &Ctx
6689 , Expr * Arg
6690 , unsigned SI
6691 )
6692 : InheritableAttr(attr::PtGuardedBy, R, SI, true, true)
6693 , arg(Arg)
6694 {
6695 }
6696
6697 PtGuardedByAttr *clone(ASTContext &C) const;
6698 void printPretty(raw_ostream &OS,
6699 const PrintingPolicy &Policy) const;
6700 const char *getSpelling() const;
6701 Expr * getArg() const {
6702 return arg;
6703 }
6704
6705
6706
6707 static bool classof(const Attr *A) { return A->getKind() == attr::PtGuardedBy; }
6708};
6709
6710class PtGuardedVarAttr : public InheritableAttr {
6711public:
6712 static PtGuardedVarAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
6713 auto *A = new (Ctx) PtGuardedVarAttr(Loc, Ctx, 0);
6714 A->setImplicit(true);
6715 return A;
6716 }
6717
6718 PtGuardedVarAttr(SourceRange R, ASTContext &Ctx
6719 , unsigned SI
6720 )
6721 : InheritableAttr(attr::PtGuardedVar, R, SI, false, false)
6722 {
6723 }
6724
6725 PtGuardedVarAttr *clone(ASTContext &C) const;
6726 void printPretty(raw_ostream &OS,
6727 const PrintingPolicy &Policy) const;
6728 const char *getSpelling() const;
6729
6730
6731 static bool classof(const Attr *A) { return A->getKind() == attr::PtGuardedVar; }
6732};
6733
6734class PureAttr : public InheritableAttr {
6735public:
6736 static PureAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
6737 auto *A = new (Ctx) PureAttr(Loc, Ctx, 0);
6738 A->setImplicit(true);
6739 return A;
6740 }
6741
6742 PureAttr(SourceRange R, ASTContext &Ctx
6743 , unsigned SI
6744 )
6745 : InheritableAttr(attr::Pure, R, SI, false, false)
6746 {
6747 }
6748
6749 PureAttr *clone(ASTContext &C) const;
6750 void printPretty(raw_ostream &OS,
6751 const PrintingPolicy &Policy) const;
6752 const char *getSpelling() const;
6753
6754
6755 static bool classof(const Attr *A) { return A->getKind() == attr::Pure; }
6756};
6757
6758class RegCallAttr : public InheritableAttr {
6759public:
6760 static RegCallAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
6761 auto *A = new (Ctx) RegCallAttr(Loc, Ctx, 0);
6762 A->setImplicit(true);
6763 return A;
6764 }
6765
6766 RegCallAttr(SourceRange R, ASTContext &Ctx
6767 , unsigned SI
6768 )
6769 : InheritableAttr(attr::RegCall, R, SI, false, false)
6770 {
6771 }
6772
6773 RegCallAttr *clone(ASTContext &C) const;
6774 void printPretty(raw_ostream &OS,
6775 const PrintingPolicy &Policy) const;
6776 const char *getSpelling() const;
6777
6778
6779 static bool classof(const Attr *A) { return A->getKind() == attr::RegCall; }
6780};
6781
6782class ReleaseCapabilityAttr : public InheritableAttr {
6783 unsigned args_Size;
6784 Expr * *args_;
6785
6786public:
6787 enum Spelling {
6788 GNU_release_capability = 0,
6789 CXX11_clang_release_capability = 1,
6790 GNU_release_shared_capability = 2,
6791 CXX11_clang_release_shared_capability = 3,
6792 GNU_release_generic_capability = 4,
6793 CXX11_clang_release_generic_capability = 5,
6794 GNU_unlock_function = 6,
6795 CXX11_clang_unlock_function = 7
6796 };
6797
6798 static ReleaseCapabilityAttr *CreateImplicit(ASTContext &Ctx, Spelling S, Expr * *Args, unsigned ArgsSize, SourceRange Loc = SourceRange()) {
6799 auto *A = new (Ctx) ReleaseCapabilityAttr(Loc, Ctx, Args, ArgsSize, S);
6800 A->setImplicit(true);
6801 return A;
6802 }
6803
6804 ReleaseCapabilityAttr(SourceRange R, ASTContext &Ctx
6805 , Expr * *Args, unsigned ArgsSize
6806 , unsigned SI
6807 )
6808 : InheritableAttr(attr::ReleaseCapability, R, SI, true, true)
6809 , args_Size(ArgsSize), args_(new (Ctx, 16) Expr *[args_Size])
6810 {
6811 std::copy(Args, Args + args_Size, args_);
6812 }
6813
6814 ReleaseCapabilityAttr(SourceRange R, ASTContext &Ctx
6815 , unsigned SI
6816 )
6817 : InheritableAttr(attr::ReleaseCapability, R, SI, true, true)
6818 , args_Size(0), args_(nullptr)
6819 {
6820 }
6821
6822 ReleaseCapabilityAttr *clone(ASTContext &C) const;
6823 void printPretty(raw_ostream &OS,
6824 const PrintingPolicy &Policy) const;
6825 const char *getSpelling() const;
6826 Spelling getSemanticSpelling() const {
6827 switch (SpellingListIndex) {
6828 default: llvm_unreachable("Unknown spelling list index")::llvm::llvm_unreachable_internal("Unknown spelling list index"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 6828)
;
6829 case 0: return GNU_release_capability;
6830 case 1: return CXX11_clang_release_capability;
6831 case 2: return GNU_release_shared_capability;
6832 case 3: return CXX11_clang_release_shared_capability;
6833 case 4: return GNU_release_generic_capability;
6834 case 5: return CXX11_clang_release_generic_capability;
6835 case 6: return GNU_unlock_function;
6836 case 7: return CXX11_clang_unlock_function;
6837 }
6838 }
6839 bool isShared() const { return SpellingListIndex == 2 ||
6840 SpellingListIndex == 3; }
6841 bool isGeneric() const { return SpellingListIndex == 4 ||
6842 SpellingListIndex == 5 ||
6843 SpellingListIndex == 6 ||
6844 SpellingListIndex == 7; }
6845 typedef Expr ** args_iterator;
6846 args_iterator args_begin() const { return args_; }
6847 args_iterator args_end() const { return args_ + args_Size; }
6848 unsigned args_size() const { return args_Size; }
6849 llvm::iterator_range<args_iterator> args() const { return llvm::make_range(args_begin(), args_end()); }
6850
6851
6852
6853
6854 static bool classof(const Attr *A) { return A->getKind() == attr::ReleaseCapability; }
6855};
6856
6857class RenderScriptKernelAttr : public Attr {
6858public:
6859 static RenderScriptKernelAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
6860 auto *A = new (Ctx) RenderScriptKernelAttr(Loc, Ctx, 0);
6861 A->setImplicit(true);
6862 return A;
6863 }
6864
6865 RenderScriptKernelAttr(SourceRange R, ASTContext &Ctx
6866 , unsigned SI
6867 )
6868 : Attr(attr::RenderScriptKernel, R, SI, false)
6869 {
6870 }
6871
6872 RenderScriptKernelAttr *clone(ASTContext &C) const;
6873 void printPretty(raw_ostream &OS,
6874 const PrintingPolicy &Policy) const;
6875 const char *getSpelling() const;
6876
6877
6878 static bool classof(const Attr *A) { return A->getKind() == attr::RenderScriptKernel; }
6879};
6880
6881class ReqdWorkGroupSizeAttr : public InheritableAttr {
6882unsigned xDim;
6883
6884unsigned yDim;
6885
6886unsigned zDim;
6887
6888public:
6889 static ReqdWorkGroupSizeAttr *CreateImplicit(ASTContext &Ctx, unsigned XDim, unsigned YDim, unsigned ZDim, SourceRange Loc = SourceRange()) {
6890 auto *A = new (Ctx) ReqdWorkGroupSizeAttr(Loc, Ctx, XDim, YDim, ZDim, 0);
6891 A->setImplicit(true);
6892 return A;
6893 }
6894
6895 ReqdWorkGroupSizeAttr(SourceRange R, ASTContext &Ctx
6896 , unsigned XDim
6897 , unsigned YDim
6898 , unsigned ZDim
6899 , unsigned SI
6900 )
6901 : InheritableAttr(attr::ReqdWorkGroupSize, R, SI, false, false)
6902 , xDim(XDim)
6903 , yDim(YDim)
6904 , zDim(ZDim)
6905 {
6906 }
6907
6908 ReqdWorkGroupSizeAttr *clone(ASTContext &C) const;
6909 void printPretty(raw_ostream &OS,
6910 const PrintingPolicy &Policy) const;
6911 const char *getSpelling() const;
6912 unsigned getXDim() const {
6913 return xDim;
6914 }
6915
6916 unsigned getYDim() const {
6917 return yDim;
6918 }
6919
6920 unsigned getZDim() const {
6921 return zDim;
6922 }
6923
6924
6925
6926 static bool classof(const Attr *A) { return A->getKind() == attr::ReqdWorkGroupSize; }
6927};
6928
6929class RequireConstantInitAttr : public InheritableAttr {
6930public:
6931 static RequireConstantInitAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
6932 auto *A = new (Ctx) RequireConstantInitAttr(Loc, Ctx, 0);
6933 A->setImplicit(true);
6934 return A;
6935 }
6936
6937 RequireConstantInitAttr(SourceRange R, ASTContext &Ctx
6938 , unsigned SI
6939 )
6940 : InheritableAttr(attr::RequireConstantInit, R, SI, false, false)
6941 {
6942 }
6943
6944 RequireConstantInitAttr *clone(ASTContext &C) const;
6945 void printPretty(raw_ostream &OS,
6946 const PrintingPolicy &Policy) const;
6947 const char *getSpelling() const;
6948
6949
6950 static bool classof(const Attr *A) { return A->getKind() == attr::RequireConstantInit; }
6951};
6952
6953class RequiresCapabilityAttr : public InheritableAttr {
6954 unsigned args_Size;
6955 Expr * *args_;
6956
6957public:
6958 enum Spelling {
6959 GNU_requires_capability = 0,
6960 CXX11_clang_requires_capability = 1,
6961 GNU_exclusive_locks_required = 2,
6962 CXX11_clang_exclusive_locks_required = 3,
6963 GNU_requires_shared_capability = 4,
6964 CXX11_clang_requires_shared_capability = 5,
6965 GNU_shared_locks_required = 6,
6966 CXX11_clang_shared_locks_required = 7
6967 };
6968
6969 static RequiresCapabilityAttr *CreateImplicit(ASTContext &Ctx, Spelling S, Expr * *Args, unsigned ArgsSize, SourceRange Loc = SourceRange()) {
6970 auto *A = new (Ctx) RequiresCapabilityAttr(Loc, Ctx, Args, ArgsSize, S);
6971 A->setImplicit(true);
6972 return A;
6973 }
6974
6975 RequiresCapabilityAttr(SourceRange R, ASTContext &Ctx
6976 , Expr * *Args, unsigned ArgsSize
6977 , unsigned SI
6978 )
6979 : InheritableAttr(attr::RequiresCapability, R, SI, true, true)
6980 , args_Size(ArgsSize), args_(new (Ctx, 16) Expr *[args_Size])
6981 {
6982 std::copy(Args, Args + args_Size, args_);
6983 }
6984
6985 RequiresCapabilityAttr(SourceRange R, ASTContext &Ctx
6986 , unsigned SI
6987 )
6988 : InheritableAttr(attr::RequiresCapability, R, SI, true, true)
6989 , args_Size(0), args_(nullptr)
6990 {
6991 }
6992
6993 RequiresCapabilityAttr *clone(ASTContext &C) const;
6994 void printPretty(raw_ostream &OS,
6995 const PrintingPolicy &Policy) const;
6996 const char *getSpelling() const;
6997 Spelling getSemanticSpelling() const {
6998 switch (SpellingListIndex) {
6999 default: llvm_unreachable("Unknown spelling list index")::llvm::llvm_unreachable_internal("Unknown spelling list index"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 6999)
;
7000 case 0: return GNU_requires_capability;
7001 case 1: return CXX11_clang_requires_capability;
7002 case 2: return GNU_exclusive_locks_required;
7003 case 3: return CXX11_clang_exclusive_locks_required;
7004 case 4: return GNU_requires_shared_capability;
7005 case 5: return CXX11_clang_requires_shared_capability;
7006 case 6: return GNU_shared_locks_required;
7007 case 7: return CXX11_clang_shared_locks_required;
7008 }
7009 }
7010 bool isShared() const { return SpellingListIndex == 4 ||
7011 SpellingListIndex == 5 ||
7012 SpellingListIndex == 6 ||
7013 SpellingListIndex == 7; }
7014 typedef Expr ** args_iterator;
7015 args_iterator args_begin() const { return args_; }
7016 args_iterator args_end() const { return args_ + args_Size; }
7017 unsigned args_size() const { return args_Size; }
7018 llvm::iterator_range<args_iterator> args() const { return llvm::make_range(args_begin(), args_end()); }
7019
7020
7021
7022
7023 static bool classof(const Attr *A) { return A->getKind() == attr::RequiresCapability; }
7024};
7025
7026class RestrictAttr : public InheritableAttr {
7027public:
7028 enum Spelling {
7029 Declspec_restrict = 0,
7030 GNU_malloc = 1,
7031 CXX11_gnu_malloc = 2
7032 };
7033
7034 static RestrictAttr *CreateImplicit(ASTContext &Ctx, Spelling S, SourceRange Loc = SourceRange()) {
7035 auto *A = new (Ctx) RestrictAttr(Loc, Ctx, S);
7036 A->setImplicit(true);
7037 return A;
7038 }
7039
7040 RestrictAttr(SourceRange R, ASTContext &Ctx
7041 , unsigned SI
7042 )
7043 : InheritableAttr(attr::Restrict, R, SI, false, false)
7044 {
7045 }
7046
7047 RestrictAttr *clone(ASTContext &C) const;
7048 void printPretty(raw_ostream &OS,
7049 const PrintingPolicy &Policy) const;
7050 const char *getSpelling() const;
7051 Spelling getSemanticSpelling() const {
7052 switch (SpellingListIndex) {
7053 default: llvm_unreachable("Unknown spelling list index")::llvm::llvm_unreachable_internal("Unknown spelling list index"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 7053)
;
7054 case 0: return Declspec_restrict;
7055 case 1: return GNU_malloc;
7056 case 2: return CXX11_gnu_malloc;
7057 }
7058 }
7059
7060
7061 static bool classof(const Attr *A) { return A->getKind() == attr::Restrict; }
7062};
7063
7064class ReturnTypestateAttr : public InheritableAttr {
7065public:
7066 enum ConsumedState {
7067 Unknown,
7068 Consumed,
7069 Unconsumed
7070 };
7071private:
7072 ConsumedState state;
7073
7074public:
7075 static ReturnTypestateAttr *CreateImplicit(ASTContext &Ctx, ConsumedState State, SourceRange Loc = SourceRange()) {
7076 auto *A = new (Ctx) ReturnTypestateAttr(Loc, Ctx, State, 0);
7077 A->setImplicit(true);
7078 return A;
7079 }
7080
7081 ReturnTypestateAttr(SourceRange R, ASTContext &Ctx
7082 , ConsumedState State
7083 , unsigned SI
7084 )
7085 : InheritableAttr(attr::ReturnTypestate, R, SI, false, false)
7086 , state(State)
7087 {
7088 }
7089
7090 ReturnTypestateAttr *clone(ASTContext &C) const;
7091 void printPretty(raw_ostream &OS,
7092 const PrintingPolicy &Policy) const;
7093 const char *getSpelling() const;
7094 ConsumedState getState() const {
7095 return state;
7096 }
7097
7098 static bool ConvertStrToConsumedState(StringRef Val, ConsumedState &Out) {
7099 Optional<ConsumedState> R = llvm::StringSwitch<Optional<ConsumedState>>(Val)
7100 .Case("unknown", ReturnTypestateAttr::Unknown)
7101 .Case("consumed", ReturnTypestateAttr::Consumed)
7102 .Case("unconsumed", ReturnTypestateAttr::Unconsumed)
7103 .Default(Optional<ConsumedState>());
7104 if (R) {
7105 Out = *R;
7106 return true;
7107 }
7108 return false;
7109 }
7110
7111 static const char *ConvertConsumedStateToStr(ConsumedState Val) {
7112 switch(Val) {
7113 case ReturnTypestateAttr::Unknown: return "unknown";
7114 case ReturnTypestateAttr::Consumed: return "consumed";
7115 case ReturnTypestateAttr::Unconsumed: return "unconsumed";
7116 }
7117 llvm_unreachable("No enumerator with that value")::llvm::llvm_unreachable_internal("No enumerator with that value"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 7117)
;
7118 }
7119
7120
7121 static bool classof(const Attr *A) { return A->getKind() == attr::ReturnTypestate; }
7122};
7123
7124class ReturnsNonNullAttr : public InheritableAttr {
7125public:
7126 static ReturnsNonNullAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
7127 auto *A = new (Ctx) ReturnsNonNullAttr(Loc, Ctx, 0);
7128 A->setImplicit(true);
7129 return A;
7130 }
7131
7132 ReturnsNonNullAttr(SourceRange R, ASTContext &Ctx
7133 , unsigned SI
7134 )
7135 : InheritableAttr(attr::ReturnsNonNull, R, SI, false, false)
7136 {
7137 }
7138
7139 ReturnsNonNullAttr *clone(ASTContext &C) const;
7140 void printPretty(raw_ostream &OS,
7141 const PrintingPolicy &Policy) const;
7142 const char *getSpelling() const;
7143
7144
7145 static bool classof(const Attr *A) { return A->getKind() == attr::ReturnsNonNull; }
7146};
7147
7148class ReturnsTwiceAttr : public InheritableAttr {
7149public:
7150 static ReturnsTwiceAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
7151 auto *A = new (Ctx) ReturnsTwiceAttr(Loc, Ctx, 0);
7152 A->setImplicit(true);
7153 return A;
7154 }
7155
7156 ReturnsTwiceAttr(SourceRange R, ASTContext &Ctx
7157 , unsigned SI
7158 )
7159 : InheritableAttr(attr::ReturnsTwice, R, SI, false, false)
7160 {
7161 }
7162
7163 ReturnsTwiceAttr *clone(ASTContext &C) const;
7164 void printPretty(raw_ostream &OS,
7165 const PrintingPolicy &Policy) const;
7166 const char *getSpelling() const;
7167
7168
7169 static bool classof(const Attr *A) { return A->getKind() == attr::ReturnsTwice; }
7170};
7171
7172class ScopedLockableAttr : public InheritableAttr {
7173public:
7174 static ScopedLockableAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
7175 auto *A = new (Ctx) ScopedLockableAttr(Loc, Ctx, 0);
7176 A->setImplicit(true);
7177 return A;
7178 }
7179
7180 ScopedLockableAttr(SourceRange R, ASTContext &Ctx
7181 , unsigned SI
7182 )
7183 : InheritableAttr(attr::ScopedLockable, R, SI, false, false)
7184 {
7185 }
7186
7187 ScopedLockableAttr *clone(ASTContext &C) const;
7188 void printPretty(raw_ostream &OS,
7189 const PrintingPolicy &Policy) const;
7190 const char *getSpelling() const;
7191
7192
7193 static bool classof(const Attr *A) { return A->getKind() == attr::ScopedLockable; }
7194};
7195
7196class SectionAttr : public InheritableAttr {
7197unsigned nameLength;
7198char *name;
7199
7200public:
7201 enum Spelling {
7202 GNU_section = 0,
7203 CXX11_gnu_section = 1,
7204 Declspec_allocate = 2
7205 };
7206
7207 static SectionAttr *CreateImplicit(ASTContext &Ctx, Spelling S, llvm::StringRef Name, SourceRange Loc = SourceRange()) {
7208 auto *A = new (Ctx) SectionAttr(Loc, Ctx, Name, S);
7209 A->setImplicit(true);
7210 return A;
7211 }
7212
7213 SectionAttr(SourceRange R, ASTContext &Ctx
7214 , llvm::StringRef Name
7215 , unsigned SI
7216 )
7217 : InheritableAttr(attr::Section, R, SI, false, false)
7218 , nameLength(Name.size()),name(new (Ctx, 1) char[nameLength])
7219 {
7220 if (!Name.empty())
7221 std::memcpy(name, Name.data(), nameLength);
7222 }
7223
7224 SectionAttr *clone(ASTContext &C) const;
7225 void printPretty(raw_ostream &OS,
7226 const PrintingPolicy &Policy) const;
7227 const char *getSpelling() const;
7228 Spelling getSemanticSpelling() const {
7229 switch (SpellingListIndex) {
7230 default: llvm_unreachable("Unknown spelling list index")::llvm::llvm_unreachable_internal("Unknown spelling list index"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 7230)
;
7231 case 0: return GNU_section;
7232 case 1: return CXX11_gnu_section;
7233 case 2: return Declspec_allocate;
7234 }
7235 }
7236 llvm::StringRef getName() const {
7237 return llvm::StringRef(name, nameLength);
7238 }
7239 unsigned getNameLength() const {
7240 return nameLength;
7241 }
7242 void setName(ASTContext &C, llvm::StringRef S) {
7243 nameLength = S.size();
7244 this->name = new (C, 1) char [nameLength];
7245 if (!S.empty())
7246 std::memcpy(this->name, S.data(), nameLength);
7247 }
7248
7249
7250
7251 static bool classof(const Attr *A) { return A->getKind() == attr::Section; }
7252};
7253
7254class SelectAnyAttr : public InheritableAttr {
7255public:
7256 static SelectAnyAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
7257 auto *A = new (Ctx) SelectAnyAttr(Loc, Ctx, 0);
7258 A->setImplicit(true);
7259 return A;
7260 }
7261
7262 SelectAnyAttr(SourceRange R, ASTContext &Ctx
7263 , unsigned SI
7264 )
7265 : InheritableAttr(attr::SelectAny, R, SI, false, false)
7266 {
7267 }
7268
7269 SelectAnyAttr *clone(ASTContext &C) const;
7270 void printPretty(raw_ostream &OS,
7271 const PrintingPolicy &Policy) const;
7272 const char *getSpelling() const;
7273
7274
7275 static bool classof(const Attr *A) { return A->getKind() == attr::SelectAny; }
7276};
7277
7278class SentinelAttr : public InheritableAttr {
7279int sentinel;
7280
7281int nullPos;
7282
7283public:
7284 static SentinelAttr *CreateImplicit(ASTContext &Ctx, int Sentinel, int NullPos, SourceRange Loc = SourceRange()) {
7285 auto *A = new (Ctx) SentinelAttr(Loc, Ctx, Sentinel, NullPos, 0);
7286 A->setImplicit(true);
7287 return A;
7288 }
7289
7290 SentinelAttr(SourceRange R, ASTContext &Ctx
7291 , int Sentinel
7292 , int NullPos
7293 , unsigned SI
7294 )
7295 : InheritableAttr(attr::Sentinel, R, SI, false, false)
7296 , sentinel(Sentinel)
7297 , nullPos(NullPos)
7298 {
7299 }
7300
7301 SentinelAttr(SourceRange R, ASTContext &Ctx
7302 , unsigned SI
7303 )
7304 : InheritableAttr(attr::Sentinel, R, SI, false, false)
7305 , sentinel()
7306 , nullPos()
7307 {
7308 }
7309
7310 SentinelAttr *clone(ASTContext &C) const;
7311 void printPretty(raw_ostream &OS,
7312 const PrintingPolicy &Policy) const;
7313 const char *getSpelling() const;
7314 int getSentinel() const {
7315 return sentinel;
7316 }
7317
7318 static const int DefaultSentinel = 0;
7319
7320 int getNullPos() const {
7321 return nullPos;
7322 }
7323
7324 static const int DefaultNullPos = 0;
7325
7326
7327
7328 static bool classof(const Attr *A) { return A->getKind() == attr::Sentinel; }
7329};
7330
7331class SetTypestateAttr : public InheritableAttr {
7332public:
7333 enum ConsumedState {
7334 Unknown,
7335 Consumed,
7336 Unconsumed
7337 };
7338private:
7339 ConsumedState newState;
7340
7341public:
7342 static SetTypestateAttr *CreateImplicit(ASTContext &Ctx, ConsumedState NewState, SourceRange Loc = SourceRange()) {
7343 auto *A = new (Ctx) SetTypestateAttr(Loc, Ctx, NewState, 0);
7344 A->setImplicit(true);
7345 return A;
7346 }
7347
7348 SetTypestateAttr(SourceRange R, ASTContext &Ctx
7349 , ConsumedState NewState
7350 , unsigned SI
7351 )
7352 : InheritableAttr(attr::SetTypestate, R, SI, false, false)
7353 , newState(NewState)
7354 {
7355 }
7356
7357 SetTypestateAttr *clone(ASTContext &C) const;
7358 void printPretty(raw_ostream &OS,
7359 const PrintingPolicy &Policy) const;
7360 const char *getSpelling() const;
7361 ConsumedState getNewState() const {
7362 return newState;
7363 }
7364
7365 static bool ConvertStrToConsumedState(StringRef Val, ConsumedState &Out) {
7366 Optional<ConsumedState> R = llvm::StringSwitch<Optional<ConsumedState>>(Val)
7367 .Case("unknown", SetTypestateAttr::Unknown)
7368 .Case("consumed", SetTypestateAttr::Consumed)
7369 .Case("unconsumed", SetTypestateAttr::Unconsumed)
7370 .Default(Optional<ConsumedState>());
7371 if (R) {
7372 Out = *R;
7373 return true;
7374 }
7375 return false;
7376 }
7377
7378 static const char *ConvertConsumedStateToStr(ConsumedState Val) {
7379 switch(Val) {
7380 case SetTypestateAttr::Unknown: return "unknown";
7381 case SetTypestateAttr::Consumed: return "consumed";
7382 case SetTypestateAttr::Unconsumed: return "unconsumed";
7383 }
7384 llvm_unreachable("No enumerator with that value")::llvm::llvm_unreachable_internal("No enumerator with that value"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 7384)
;
7385 }
7386
7387
7388 static bool classof(const Attr *A) { return A->getKind() == attr::SetTypestate; }
7389};
7390
7391class SharedTrylockFunctionAttr : public InheritableAttr {
7392Expr * successValue;
7393
7394 unsigned args_Size;
7395 Expr * *args_;
7396
7397public:
7398 static SharedTrylockFunctionAttr *CreateImplicit(ASTContext &Ctx, Expr * SuccessValue, Expr * *Args, unsigned ArgsSize, SourceRange Loc = SourceRange()) {
7399 auto *A = new (Ctx) SharedTrylockFunctionAttr(Loc, Ctx, SuccessValue, Args, ArgsSize, 0);
7400 A->setImplicit(true);
7401 return A;
7402 }
7403
7404 SharedTrylockFunctionAttr(SourceRange R, ASTContext &Ctx
7405 , Expr * SuccessValue
7406 , Expr * *Args, unsigned ArgsSize
7407 , unsigned SI
7408 )
7409 : InheritableAttr(attr::SharedTrylockFunction, R, SI, true, true)
7410 , successValue(SuccessValue)
7411 , args_Size(ArgsSize), args_(new (Ctx, 16) Expr *[args_Size])
7412 {
7413 std::copy(Args, Args + args_Size, args_);
7414 }
7415
7416 SharedTrylockFunctionAttr(SourceRange R, ASTContext &Ctx
7417 , Expr * SuccessValue
7418 , unsigned SI
7419 )
7420 : InheritableAttr(attr::SharedTrylockFunction, R, SI, true, true)
7421 , successValue(SuccessValue)
7422 , args_Size(0), args_(nullptr)
7423 {
7424 }
7425
7426 SharedTrylockFunctionAttr *clone(ASTContext &C) const;
7427 void printPretty(raw_ostream &OS,
7428 const PrintingPolicy &Policy) const;
7429 const char *getSpelling() const;
7430 Expr * getSuccessValue() const {
7431 return successValue;
7432 }
7433
7434 typedef Expr ** args_iterator;
7435 args_iterator args_begin() const { return args_; }
7436 args_iterator args_end() const { return args_ + args_Size; }
7437 unsigned args_size() const { return args_Size; }
7438 llvm::iterator_range<args_iterator> args() const { return llvm::make_range(args_begin(), args_end()); }
7439
7440
7441
7442
7443 static bool classof(const Attr *A) { return A->getKind() == attr::SharedTrylockFunction; }
7444};
7445
7446class StdCallAttr : public InheritableAttr {
7447public:
7448 static StdCallAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
7449 auto *A = new (Ctx) StdCallAttr(Loc, Ctx, 0);
7450 A->setImplicit(true);
7451 return A;
7452 }
7453
7454 StdCallAttr(SourceRange R, ASTContext &Ctx
7455 , unsigned SI
7456 )
7457 : InheritableAttr(attr::StdCall, R, SI, false, false)
7458 {
7459 }
7460
7461 StdCallAttr *clone(ASTContext &C) const;
7462 void printPretty(raw_ostream &OS,
7463 const PrintingPolicy &Policy) const;
7464 const char *getSpelling() const;
7465
7466
7467 static bool classof(const Attr *A) { return A->getKind() == attr::StdCall; }
7468};
7469
7470class SuppressAttr : public StmtAttr {
7471 unsigned diagnosticIdentifiers_Size;
7472 StringRef *diagnosticIdentifiers_;
7473
7474public:
7475 static SuppressAttr *CreateImplicit(ASTContext &Ctx, StringRef *DiagnosticIdentifiers, unsigned DiagnosticIdentifiersSize, SourceRange Loc = SourceRange()) {
7476 auto *A = new (Ctx) SuppressAttr(Loc, Ctx, DiagnosticIdentifiers, DiagnosticIdentifiersSize, 0);
7477 A->setImplicit(true);
7478 return A;
7479 }
7480
7481 SuppressAttr(SourceRange R, ASTContext &Ctx
7482 , StringRef *DiagnosticIdentifiers, unsigned DiagnosticIdentifiersSize
7483 , unsigned SI
7484 )
7485 : StmtAttr(attr::Suppress, R, SI, false)
7486 , diagnosticIdentifiers_Size(DiagnosticIdentifiersSize), diagnosticIdentifiers_(new (Ctx, 16) StringRef[diagnosticIdentifiers_Size])
7487 {
7488 for (size_t I = 0, E = diagnosticIdentifiers_Size; I != E;
7489 ++I) {
7490 StringRef Ref = DiagnosticIdentifiers[I];
7491 if (!Ref.empty()) {
7492 char *Mem = new (Ctx, 1) char[Ref.size()];
7493 std::memcpy(Mem, Ref.data(), Ref.size());
7494 diagnosticIdentifiers_[I] = StringRef(Mem, Ref.size());
7495 }
7496 }
7497 }
7498
7499 SuppressAttr(SourceRange R, ASTContext &Ctx
7500 , unsigned SI
7501 )
7502 : StmtAttr(attr::Suppress, R, SI, false)
7503 , diagnosticIdentifiers_Size(0), diagnosticIdentifiers_(nullptr)
7504 {
7505 }
7506
7507 SuppressAttr *clone(ASTContext &C) const;
7508 void printPretty(raw_ostream &OS,
7509 const PrintingPolicy &Policy) const;
7510 const char *getSpelling() const;
7511 typedef StringRef* diagnosticIdentifiers_iterator;
7512 diagnosticIdentifiers_iterator diagnosticIdentifiers_begin() const { return diagnosticIdentifiers_; }
7513 diagnosticIdentifiers_iterator diagnosticIdentifiers_end() const { return diagnosticIdentifiers_ + diagnosticIdentifiers_Size; }
7514 unsigned diagnosticIdentifiers_size() const { return diagnosticIdentifiers_Size; }
7515 llvm::iterator_range<diagnosticIdentifiers_iterator> diagnosticIdentifiers() const { return llvm::make_range(diagnosticIdentifiers_begin(), diagnosticIdentifiers_end()); }
7516
7517
7518
7519
7520 static bool classof(const Attr *A) { return A->getKind() == attr::Suppress; }
7521};
7522
7523class SwiftCallAttr : public InheritableAttr {
7524public:
7525 static SwiftCallAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
7526 auto *A = new (Ctx) SwiftCallAttr(Loc, Ctx, 0);
7527 A->setImplicit(true);
7528 return A;
7529 }
7530
7531 SwiftCallAttr(SourceRange R, ASTContext &Ctx
7532 , unsigned SI
7533 )
7534 : InheritableAttr(attr::SwiftCall, R, SI, false, false)
7535 {
7536 }
7537
7538 SwiftCallAttr *clone(ASTContext &C) const;
7539 void printPretty(raw_ostream &OS,
7540 const PrintingPolicy &Policy) const;
7541 const char *getSpelling() const;
7542
7543
7544 static bool classof(const Attr *A) { return A->getKind() == attr::SwiftCall; }
7545};
7546
7547class SwiftContextAttr : public ParameterABIAttr {
7548public:
7549 static SwiftContextAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
7550 auto *A = new (Ctx) SwiftContextAttr(Loc, Ctx, 0);
7551 A->setImplicit(true);
7552 return A;
7553 }
7554
7555 SwiftContextAttr(SourceRange R, ASTContext &Ctx
7556 , unsigned SI
7557 )
7558 : ParameterABIAttr(attr::SwiftContext, R, SI, false, false)
7559 {
7560 }
7561
7562 SwiftContextAttr *clone(ASTContext &C) const;
7563 void printPretty(raw_ostream &OS,
7564 const PrintingPolicy &Policy) const;
7565 const char *getSpelling() const;
7566
7567
7568 static bool classof(const Attr *A) { return A->getKind() == attr::SwiftContext; }
7569};
7570
7571class SwiftErrorResultAttr : public ParameterABIAttr {
7572public:
7573 static SwiftErrorResultAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
7574 auto *A = new (Ctx) SwiftErrorResultAttr(Loc, Ctx, 0);
7575 A->setImplicit(true);
7576 return A;
7577 }
7578
7579 SwiftErrorResultAttr(SourceRange R, ASTContext &Ctx
7580 , unsigned SI
7581 )
7582 : ParameterABIAttr(attr::SwiftErrorResult, R, SI, false, false)
7583 {
7584 }
7585
7586 SwiftErrorResultAttr *clone(ASTContext &C) const;
7587 void printPretty(raw_ostream &OS,
7588 const PrintingPolicy &Policy) const;
7589 const char *getSpelling() const;
7590
7591
7592 static bool classof(const Attr *A) { return A->getKind() == attr::SwiftErrorResult; }
7593};
7594
7595class SwiftIndirectResultAttr : public ParameterABIAttr {
7596public:
7597 static SwiftIndirectResultAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
7598 auto *A = new (Ctx) SwiftIndirectResultAttr(Loc, Ctx, 0);
7599 A->setImplicit(true);
7600 return A;
7601 }
7602
7603 SwiftIndirectResultAttr(SourceRange R, ASTContext &Ctx
7604 , unsigned SI
7605 )
7606 : ParameterABIAttr(attr::SwiftIndirectResult, R, SI, false, false)
7607 {
7608 }
7609
7610 SwiftIndirectResultAttr *clone(ASTContext &C) const;
7611 void printPretty(raw_ostream &OS,
7612 const PrintingPolicy &Policy) const;
7613 const char *getSpelling() const;
7614
7615
7616 static bool classof(const Attr *A) { return A->getKind() == attr::SwiftIndirectResult; }
7617};
7618
7619class SysVABIAttr : public InheritableAttr {
7620public:
7621 static SysVABIAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
7622 auto *A = new (Ctx) SysVABIAttr(Loc, Ctx, 0);
7623 A->setImplicit(true);
7624 return A;
7625 }
7626
7627 SysVABIAttr(SourceRange R, ASTContext &Ctx
7628 , unsigned SI
7629 )
7630 : InheritableAttr(attr::SysVABI, R, SI, false, false)
7631 {
7632 }
7633
7634 SysVABIAttr *clone(ASTContext &C) const;
7635 void printPretty(raw_ostream &OS,
7636 const PrintingPolicy &Policy) const;
7637 const char *getSpelling() const;
7638
7639
7640 static bool classof(const Attr *A) { return A->getKind() == attr::SysVABI; }
7641};
7642
7643class TLSModelAttr : public InheritableAttr {
7644unsigned modelLength;
7645char *model;
7646
7647public:
7648 static TLSModelAttr *CreateImplicit(ASTContext &Ctx, llvm::StringRef Model, SourceRange Loc = SourceRange()) {
7649 auto *A = new (Ctx) TLSModelAttr(Loc, Ctx, Model, 0);
7650 A->setImplicit(true);
7651 return A;
7652 }
7653
7654 TLSModelAttr(SourceRange R, ASTContext &Ctx
7655 , llvm::StringRef Model
7656 , unsigned SI
7657 )
7658 : InheritableAttr(attr::TLSModel, R, SI, false, false)
7659 , modelLength(Model.size()),model(new (Ctx, 1) char[modelLength])
7660 {
7661 if (!Model.empty())
7662 std::memcpy(model, Model.data(), modelLength);
7663 }
7664
7665 TLSModelAttr *clone(ASTContext &C) const;
7666 void printPretty(raw_ostream &OS,
7667 const PrintingPolicy &Policy) const;
7668 const char *getSpelling() const;
7669 llvm::StringRef getModel() const {
7670 return llvm::StringRef(model, modelLength);
7671 }
7672 unsigned getModelLength() const {
7673 return modelLength;
7674 }
7675 void setModel(ASTContext &C, llvm::StringRef S) {
7676 modelLength = S.size();
7677 this->model = new (C, 1) char [modelLength];
7678 if (!S.empty())
7679 std::memcpy(this->model, S.data(), modelLength);
7680 }
7681
7682
7683
7684 static bool classof(const Attr *A) { return A->getKind() == attr::TLSModel; }
7685};
7686
7687class TargetAttr : public InheritableAttr {
7688unsigned featuresStrLength;
7689char *featuresStr;
7690
7691public:
7692 static TargetAttr *CreateImplicit(ASTContext &Ctx, llvm::StringRef FeaturesStr, SourceRange Loc = SourceRange()) {
7693 auto *A = new (Ctx) TargetAttr(Loc, Ctx, FeaturesStr, 0);
7694 A->setImplicit(true);
7695 return A;
7696 }
7697
7698 TargetAttr(SourceRange R, ASTContext &Ctx
7699 , llvm::StringRef FeaturesStr
7700 , unsigned SI
7701 )
7702 : InheritableAttr(attr::Target, R, SI, false, false)
7703 , featuresStrLength(FeaturesStr.size()),featuresStr(new (Ctx, 1) char[featuresStrLength])
7704 {
7705 if (!FeaturesStr.empty())
7706 std::memcpy(featuresStr, FeaturesStr.data(), featuresStrLength);
7707 }
7708
7709 TargetAttr *clone(ASTContext &C) const;
7710 void printPretty(raw_ostream &OS,
7711 const PrintingPolicy &Policy) const;
7712 const char *getSpelling() const;
7713 llvm::StringRef getFeaturesStr() const {
7714 return llvm::StringRef(featuresStr, featuresStrLength);
7715 }
7716 unsigned getFeaturesStrLength() const {
7717 return featuresStrLength;
7718 }
7719 void setFeaturesStr(ASTContext &C, llvm::StringRef S) {
7720 featuresStrLength = S.size();
7721 this->featuresStr = new (C, 1) char [featuresStrLength];
7722 if (!S.empty())
7723 std::memcpy(this->featuresStr, S.data(), featuresStrLength);
7724 }
7725
7726
7727 struct ParsedTargetAttr {
7728 std::vector<std::string> Features;
7729 StringRef Architecture;
7730 bool DuplicateArchitecture = false;
7731 bool operator ==(const ParsedTargetAttr &Other) const {
7732 return DuplicateArchitecture == Other.DuplicateArchitecture &&
7733 Architecture == Other.Architecture && Features == Other.Features;
7734 }
7735 };
7736 ParsedTargetAttr parse() const {
7737 return parse(getFeaturesStr());
7738 }
7739
7740 template<class Compare>
7741 ParsedTargetAttr parse(Compare cmp) const {
7742 ParsedTargetAttr Attrs = parse();
7743 llvm::sort(std::begin(Attrs.Features), std::end(Attrs.Features), cmp);
7744 return Attrs;
7745 }
7746
7747 bool isDefaultVersion() const { return getFeaturesStr() == "default"; }
7748
7749 static ParsedTargetAttr parse(StringRef Features) {
7750 ParsedTargetAttr Ret;
7751 if (Features == "default") return Ret;
7752 SmallVector<StringRef, 1> AttrFeatures;
7753 Features.split(AttrFeatures, ",");
7754
7755 // Grab the various features and prepend a "+" to turn on the feature to
7756 // the backend and add them to our existing set of features.
7757 for (auto &Feature : AttrFeatures) {
7758 // Go ahead and trim whitespace rather than either erroring or
7759 // accepting it weirdly.
7760 Feature = Feature.trim();
7761
7762 // We don't support cpu tuning this way currently.
7763 // TODO: Support the fpmath option. It will require checking
7764 // overall feature validity for the function with the rest of the
7765 // attributes on the function.
7766 if (Feature.startswith("fpmath=") || Feature.startswith("tune="))
7767 continue;
7768
7769 // While we're here iterating check for a different target cpu.
7770 if (Feature.startswith("arch=")) {
7771 if (!Ret.Architecture.empty())
7772 Ret.DuplicateArchitecture = true;
7773 else
7774 Ret.Architecture = Feature.split("=").second.trim();
7775 } else if (Feature.startswith("no-"))
7776 Ret.Features.push_back("-" + Feature.split("-").second.str());
7777 else
7778 Ret.Features.push_back("+" + Feature.str());
7779 }
7780 return Ret;
7781 }
7782
7783
7784 static bool classof(const Attr *A) { return A->getKind() == attr::Target; }
7785};
7786
7787class TestTypestateAttr : public InheritableAttr {
7788public:
7789 enum ConsumedState {
7790 Consumed,
7791 Unconsumed
7792 };
7793private:
7794 ConsumedState testState;
7795
7796public:
7797 static TestTypestateAttr *CreateImplicit(ASTContext &Ctx, ConsumedState TestState, SourceRange Loc = SourceRange()) {
7798 auto *A = new (Ctx) TestTypestateAttr(Loc, Ctx, TestState, 0);
7799 A->setImplicit(true);
7800 return A;
7801 }
7802
7803 TestTypestateAttr(SourceRange R, ASTContext &Ctx
7804 , ConsumedState TestState
7805 , unsigned SI
7806 )
7807 : InheritableAttr(attr::TestTypestate, R, SI, false, false)
7808 , testState(TestState)
7809 {
7810 }
7811
7812 TestTypestateAttr *clone(ASTContext &C) const;
7813 void printPretty(raw_ostream &OS,
7814 const PrintingPolicy &Policy) const;
7815 const char *getSpelling() const;
7816 ConsumedState getTestState() const {
7817 return testState;
7818 }
7819
7820 static bool ConvertStrToConsumedState(StringRef Val, ConsumedState &Out) {
7821 Optional<ConsumedState> R = llvm::StringSwitch<Optional<ConsumedState>>(Val)
7822 .Case("consumed", TestTypestateAttr::Consumed)
7823 .Case("unconsumed", TestTypestateAttr::Unconsumed)
7824 .Default(Optional<ConsumedState>());
7825 if (R) {
7826 Out = *R;
7827 return true;
7828 }
7829 return false;
7830 }
7831
7832 static const char *ConvertConsumedStateToStr(ConsumedState Val) {
7833 switch(Val) {
7834 case TestTypestateAttr::Consumed: return "consumed";
7835 case TestTypestateAttr::Unconsumed: return "unconsumed";
7836 }
7837 llvm_unreachable("No enumerator with that value")::llvm::llvm_unreachable_internal("No enumerator with that value"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 7837)
;
7838 }
7839
7840
7841 static bool classof(const Attr *A) { return A->getKind() == attr::TestTypestate; }
7842};
7843
7844class ThisCallAttr : public InheritableAttr {
7845public:
7846 static ThisCallAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
7847 auto *A = new (Ctx) ThisCallAttr(Loc, Ctx, 0);
7848 A->setImplicit(true);
7849 return A;
7850 }
7851
7852 ThisCallAttr(SourceRange R, ASTContext &Ctx
7853 , unsigned SI
7854 )
7855 : InheritableAttr(attr::ThisCall, R, SI, false, false)
7856 {
7857 }
7858
7859 ThisCallAttr *clone(ASTContext &C) const;
7860 void printPretty(raw_ostream &OS,
7861 const PrintingPolicy &Policy) const;
7862 const char *getSpelling() const;
7863
7864
7865 static bool classof(const Attr *A) { return A->getKind() == attr::ThisCall; }
7866};
7867
7868class ThreadAttr : public Attr {
7869public:
7870 static ThreadAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
7871 auto *A = new (Ctx) ThreadAttr(Loc, Ctx, 0);
7872 A->setImplicit(true);
7873 return A;
7874 }
7875
7876 ThreadAttr(SourceRange R, ASTContext &Ctx
7877 , unsigned SI
7878 )
7879 : Attr(attr::Thread, R, SI, false)
7880 {
7881 }
7882
7883 ThreadAttr *clone(ASTContext &C) const;
7884 void printPretty(raw_ostream &OS,
7885 const PrintingPolicy &Policy) const;
7886 const char *getSpelling() const;
7887
7888
7889 static bool classof(const Attr *A) { return A->getKind() == attr::Thread; }
7890};
7891
7892class TransparentUnionAttr : public InheritableAttr {
7893public:
7894 static TransparentUnionAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
7895 auto *A = new (Ctx) TransparentUnionAttr(Loc, Ctx, 0);
7896 A->setImplicit(true);
7897 return A;
7898 }
7899
7900 TransparentUnionAttr(SourceRange R, ASTContext &Ctx
7901 , unsigned SI
7902 )
7903 : InheritableAttr(attr::TransparentUnion, R, SI, false, false)
7904 {
7905 }
7906
7907 TransparentUnionAttr *clone(ASTContext &C) const;
7908 void printPretty(raw_ostream &OS,
7909 const PrintingPolicy &Policy) const;
7910 const char *getSpelling() const;
7911
7912
7913 static bool classof(const Attr *A) { return A->getKind() == attr::TransparentUnion; }
7914};
7915
7916class TrivialABIAttr : public InheritableAttr {
7917public:
7918 static TrivialABIAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
7919 auto *A = new (Ctx) TrivialABIAttr(Loc, Ctx, 0);
7920 A->setImplicit(true);
7921 return A;
7922 }
7923
7924 TrivialABIAttr(SourceRange R, ASTContext &Ctx
7925 , unsigned SI
7926 )
7927 : InheritableAttr(attr::TrivialABI, R, SI, false, false)
7928 {
7929 }
7930
7931 TrivialABIAttr *clone(ASTContext &C) const;
7932 void printPretty(raw_ostream &OS,
7933 const PrintingPolicy &Policy) const;
7934 const char *getSpelling() const;
7935
7936
7937 static bool classof(const Attr *A) { return A->getKind() == attr::TrivialABI; }
7938};
7939
7940class TryAcquireCapabilityAttr : public InheritableAttr {
7941Expr * successValue;
7942
7943 unsigned args_Size;
7944 Expr * *args_;
7945
7946public:
7947 enum Spelling {
7948 GNU_try_acquire_capability = 0,
7949 CXX11_clang_try_acquire_capability = 1,
7950 GNU_try_acquire_shared_capability = 2,
7951 CXX11_clang_try_acquire_shared_capability = 3
7952 };
7953
7954 static TryAcquireCapabilityAttr *CreateImplicit(ASTContext &Ctx, Spelling S, Expr * SuccessValue, Expr * *Args, unsigned ArgsSize, SourceRange Loc = SourceRange()) {
7955 auto *A = new (Ctx) TryAcquireCapabilityAttr(Loc, Ctx, SuccessValue, Args, ArgsSize, S);
7956 A->setImplicit(true);
7957 return A;
7958 }
7959
7960 TryAcquireCapabilityAttr(SourceRange R, ASTContext &Ctx
7961 , Expr * SuccessValue
7962 , Expr * *Args, unsigned ArgsSize
7963 , unsigned SI
7964 )
7965 : InheritableAttr(attr::TryAcquireCapability, R, SI, true, true)
7966 , successValue(SuccessValue)
7967 , args_Size(ArgsSize), args_(new (Ctx, 16) Expr *[args_Size])
7968 {
7969 std::copy(Args, Args + args_Size, args_);
7970 }
7971
7972 TryAcquireCapabilityAttr(SourceRange R, ASTContext &Ctx
7973 , Expr * SuccessValue
7974 , unsigned SI
7975 )
7976 : InheritableAttr(attr::TryAcquireCapability, R, SI, true, true)
7977 , successValue(SuccessValue)
7978 , args_Size(0), args_(nullptr)
7979 {
7980 }
7981
7982 TryAcquireCapabilityAttr *clone(ASTContext &C) const;
7983 void printPretty(raw_ostream &OS,
7984 const PrintingPolicy &Policy) const;
7985 const char *getSpelling() const;
7986 Spelling getSemanticSpelling() const {
7987 switch (SpellingListIndex) {
7988 default: llvm_unreachable("Unknown spelling list index")::llvm::llvm_unreachable_internal("Unknown spelling list index"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 7988)
;
7989 case 0: return GNU_try_acquire_capability;
7990 case 1: return CXX11_clang_try_acquire_capability;
7991 case 2: return GNU_try_acquire_shared_capability;
7992 case 3: return CXX11_clang_try_acquire_shared_capability;
7993 }
7994 }
7995 bool isShared() const { return SpellingListIndex == 2 ||
7996 SpellingListIndex == 3; }
7997 Expr * getSuccessValue() const {
7998 return successValue;
7999 }
8000
8001 typedef Expr ** args_iterator;
8002 args_iterator args_begin() const { return args_; }
8003 args_iterator args_end() const { return args_ + args_Size; }
8004 unsigned args_size() const { return args_Size; }
8005 llvm::iterator_range<args_iterator> args() const { return llvm::make_range(args_begin(), args_end()); }
8006
8007
8008
8009
8010 static bool classof(const Attr *A) { return A->getKind() == attr::TryAcquireCapability; }
8011};
8012
8013class TypeTagForDatatypeAttr : public InheritableAttr {
8014IdentifierInfo * argumentKind;
8015
8016TypeSourceInfo * matchingCType;
8017
8018bool layoutCompatible;
8019
8020bool mustBeNull;
8021
8022public:
8023 static TypeTagForDatatypeAttr *CreateImplicit(ASTContext &Ctx, IdentifierInfo * ArgumentKind, TypeSourceInfo * MatchingCType, bool LayoutCompatible, bool MustBeNull, SourceRange Loc = SourceRange()) {
8024 auto *A = new (Ctx) TypeTagForDatatypeAttr(Loc, Ctx, ArgumentKind, MatchingCType, LayoutCompatible, MustBeNull, 0);
8025 A->setImplicit(true);
8026 return A;
8027 }
8028
8029 TypeTagForDatatypeAttr(SourceRange R, ASTContext &Ctx
8030 , IdentifierInfo * ArgumentKind
8031 , TypeSourceInfo * MatchingCType
8032 , bool LayoutCompatible
8033 , bool MustBeNull
8034 , unsigned SI
8035 )
8036 : InheritableAttr(attr::TypeTagForDatatype, R, SI, false, false)
8037 , argumentKind(ArgumentKind)
8038 , matchingCType(MatchingCType)
8039 , layoutCompatible(LayoutCompatible)
8040 , mustBeNull(MustBeNull)
8041 {
8042 }
8043
8044 TypeTagForDatatypeAttr *clone(ASTContext &C) const;
8045 void printPretty(raw_ostream &OS,
8046 const PrintingPolicy &Policy) const;
8047 const char *getSpelling() const;
8048 IdentifierInfo * getArgumentKind() const {
8049 return argumentKind;
8050 }
8051
8052 QualType getMatchingCType() const {
8053 return matchingCType->getType();
8054 } TypeSourceInfo * getMatchingCTypeLoc() const {
8055 return matchingCType;
8056 }
8057
8058 bool getLayoutCompatible() const {
8059 return layoutCompatible;
8060 }
8061
8062 bool getMustBeNull() const {
8063 return mustBeNull;
8064 }
8065
8066
8067
8068 static bool classof(const Attr *A) { return A->getKind() == attr::TypeTagForDatatype; }
8069};
8070
8071class TypeVisibilityAttr : public InheritableAttr {
8072public:
8073 enum VisibilityType {
8074 Default,
8075 Hidden,
8076 Protected
8077 };
8078private:
8079 VisibilityType visibility;
8080
8081public:
8082 static TypeVisibilityAttr *CreateImplicit(ASTContext &Ctx, VisibilityType Visibility, SourceRange Loc = SourceRange()) {
8083 auto *A = new (Ctx) TypeVisibilityAttr(Loc, Ctx, Visibility, 0);
8084 A->setImplicit(true);
8085 return A;
8086 }
8087
8088 TypeVisibilityAttr(SourceRange R, ASTContext &Ctx
8089 , VisibilityType Visibility
8090 , unsigned SI
8091 )
8092 : InheritableAttr(attr::TypeVisibility, R, SI, false, false)
8093 , visibility(Visibility)
8094 {
8095 }
8096
8097 TypeVisibilityAttr *clone(ASTContext &C) const;
8098 void printPretty(raw_ostream &OS,
8099 const PrintingPolicy &Policy) const;
8100 const char *getSpelling() const;
8101 VisibilityType getVisibility() const {
8102 return visibility;
8103 }
8104
8105 static bool ConvertStrToVisibilityType(StringRef Val, VisibilityType &Out) {
8106 Optional<VisibilityType> R = llvm::StringSwitch<Optional<VisibilityType>>(Val)
8107 .Case("default", TypeVisibilityAttr::Default)
8108 .Case("hidden", TypeVisibilityAttr::Hidden)
8109 .Case("internal", TypeVisibilityAttr::Hidden)
8110 .Case("protected", TypeVisibilityAttr::Protected)
8111 .Default(Optional<VisibilityType>());
8112 if (R) {
8113 Out = *R;
8114 return true;
8115 }
8116 return false;
8117 }
8118
8119 static const char *ConvertVisibilityTypeToStr(VisibilityType Val) {
8120 switch(Val) {
8121 case TypeVisibilityAttr::Default: return "default";
8122 case TypeVisibilityAttr::Hidden: return "hidden";
8123 case TypeVisibilityAttr::Protected: return "protected";
8124 }
8125 llvm_unreachable("No enumerator with that value")::llvm::llvm_unreachable_internal("No enumerator with that value"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 8125)
;
8126 }
8127
8128
8129 static bool classof(const Attr *A) { return A->getKind() == attr::TypeVisibility; }
8130};
8131
8132class UnavailableAttr : public InheritableAttr {
8133unsigned messageLength;
8134char *message;
8135
8136public:
8137 enum ImplicitReason {
8138 IR_None,
8139 IR_ARCForbiddenType,
8140 IR_ForbiddenWeak,
8141 IR_ARCForbiddenConversion,
8142 IR_ARCInitReturnsUnrelated,
8143 IR_ARCFieldWithOwnership
8144 };
8145private:
8146 ImplicitReason implicitReason;
8147
8148public:
8149 static UnavailableAttr *CreateImplicit(ASTContext &Ctx, llvm::StringRef Message, ImplicitReason ImplicitReason, SourceRange Loc = SourceRange()) {
8150 auto *A = new (Ctx) UnavailableAttr(Loc, Ctx, Message, ImplicitReason, 0);
8151 A->setImplicit(true);
8152 return A;
8153 }
8154
8155 static UnavailableAttr *CreateImplicit(ASTContext &Ctx, llvm::StringRef Message, SourceRange Loc = SourceRange()) {
8156 auto *A = new (Ctx) UnavailableAttr(Loc, Ctx, Message, 0);
8157 A->setImplicit(true);
8158 return A;
8159 }
8160
8161 UnavailableAttr(SourceRange R, ASTContext &Ctx
8162 , llvm::StringRef Message
8163 , ImplicitReason ImplicitReason
8164 , unsigned SI
8165 )
8166 : InheritableAttr(attr::Unavailable, R, SI, false, false)
8167 , messageLength(Message.size()),message(new (Ctx, 1) char[messageLength])
8168 , implicitReason(ImplicitReason)
8169 {
8170 if (!Message.empty())
8171 std::memcpy(message, Message.data(), messageLength);
8172 }
8173
8174 UnavailableAttr(SourceRange R, ASTContext &Ctx
8175 , llvm::StringRef Message
8176 , unsigned SI
8177 )
8178 : InheritableAttr(attr::Unavailable, R, SI, false, false)
8179 , messageLength(Message.size()),message(new (Ctx, 1) char[messageLength])
8180 , implicitReason(ImplicitReason(0))
8181 {
8182 if (!Message.empty())
8183 std::memcpy(message, Message.data(), messageLength);
8184 }
8185
8186 UnavailableAttr(SourceRange R, ASTContext &Ctx
8187 , unsigned SI
8188 )
8189 : InheritableAttr(attr::Unavailable, R, SI, false, false)
8190 , messageLength(0),message(nullptr)
8191 , implicitReason(ImplicitReason(0))
8192 {
8193 }
8194
8195 UnavailableAttr *clone(ASTContext &C) const;
8196 void printPretty(raw_ostream &OS,
8197 const PrintingPolicy &Policy) const;
8198 const char *getSpelling() const;
8199 llvm::StringRef getMessage() const {
8200 return llvm::StringRef(message, messageLength);
8201 }
8202 unsigned getMessageLength() const {
8203 return messageLength;
8204 }
8205 void setMessage(ASTContext &C, llvm::StringRef S) {
8206 messageLength = S.size();
8207 this->message = new (C, 1) char [messageLength];
8208 if (!S.empty())
8209 std::memcpy(this->message, S.data(), messageLength);
8210 }
8211
8212 ImplicitReason getImplicitReason() const {
8213 return implicitReason;
8214 }
8215
8216
8217
8218 static bool classof(const Attr *A) { return A->getKind() == attr::Unavailable; }
8219};
8220
8221class UnusedAttr : public InheritableAttr {
8222public:
8223 enum Spelling {
8224 CXX11_maybe_unused = 0,
8225 GNU_unused = 1,
8226 CXX11_gnu_unused = 2,
8227 C2x_maybe_unused = 3
8228 };
8229
8230 static UnusedAttr *CreateImplicit(ASTContext &Ctx, Spelling S, SourceRange Loc = SourceRange()) {
8231 auto *A = new (Ctx) UnusedAttr(Loc, Ctx, S);
8232 A->setImplicit(true);
8233 return A;
8234 }
8235
8236 UnusedAttr(SourceRange R, ASTContext &Ctx
8237 , unsigned SI
8238 )
8239 : InheritableAttr(attr::Unused, R, SI, false, false)
8240 {
8241 }
8242
8243 UnusedAttr *clone(ASTContext &C) const;
8244 void printPretty(raw_ostream &OS,
8245 const PrintingPolicy &Policy) const;
8246 const char *getSpelling() const;
8247 Spelling getSemanticSpelling() const {
8248 switch (SpellingListIndex) {
8249 default: llvm_unreachable("Unknown spelling list index")::llvm::llvm_unreachable_internal("Unknown spelling list index"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 8249)
;
8250 case 0: return CXX11_maybe_unused;
8251 case 1: return GNU_unused;
8252 case 2: return CXX11_gnu_unused;
8253 case 3: return C2x_maybe_unused;
8254 }
8255 }
8256
8257
8258 static bool classof(const Attr *A) { return A->getKind() == attr::Unused; }
8259};
8260
8261class UsedAttr : public InheritableAttr {
8262public:
8263 static UsedAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
8264 auto *A = new (Ctx) UsedAttr(Loc, Ctx, 0);
8265 A->setImplicit(true);
8266 return A;
8267 }
8268
8269 UsedAttr(SourceRange R, ASTContext &Ctx
8270 , unsigned SI
8271 )
8272 : InheritableAttr(attr::Used, R, SI, false, false)
8273 {
8274 }
8275
8276 UsedAttr *clone(ASTContext &C) const;
8277 void printPretty(raw_ostream &OS,
8278 const PrintingPolicy &Policy) const;
8279 const char *getSpelling() const;
8280
8281
8282 static bool classof(const Attr *A) { return A->getKind() == attr::Used; }
8283};
8284
8285class UuidAttr : public InheritableAttr {
8286unsigned guidLength;
8287char *guid;
8288
8289public:
8290 static UuidAttr *CreateImplicit(ASTContext &Ctx, llvm::StringRef Guid, SourceRange Loc = SourceRange()) {
8291 auto *A = new (Ctx) UuidAttr(Loc, Ctx, Guid, 0);
8292 A->setImplicit(true);
8293 return A;
8294 }
8295
8296 UuidAttr(SourceRange R, ASTContext &Ctx
8297 , llvm::StringRef Guid
8298 , unsigned SI
8299 )
8300 : InheritableAttr(attr::Uuid, R, SI, false, false)
8301 , guidLength(Guid.size()),guid(new (Ctx, 1) char[guidLength])
8302 {
8303 if (!Guid.empty())
8304 std::memcpy(guid, Guid.data(), guidLength);
8305 }
8306
8307 UuidAttr *clone(ASTContext &C) const;
8308 void printPretty(raw_ostream &OS,
8309 const PrintingPolicy &Policy) const;
8310 const char *getSpelling() const;
8311 llvm::StringRef getGuid() const {
8312 return llvm::StringRef(guid, guidLength);
8313 }
8314 unsigned getGuidLength() const {
8315 return guidLength;
8316 }
8317 void setGuid(ASTContext &C, llvm::StringRef S) {
8318 guidLength = S.size();
8319 this->guid = new (C, 1) char [guidLength];
8320 if (!S.empty())
8321 std::memcpy(this->guid, S.data(), guidLength);
8322 }
8323
8324
8325
8326 static bool classof(const Attr *A) { return A->getKind() == attr::Uuid; }
8327};
8328
8329class VecReturnAttr : public InheritableAttr {
8330public:
8331 static VecReturnAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
8332 auto *A = new (Ctx) VecReturnAttr(Loc, Ctx, 0);
8333 A->setImplicit(true);
8334 return A;
8335 }
8336
8337 VecReturnAttr(SourceRange R, ASTContext &Ctx
8338 , unsigned SI
8339 )
8340 : InheritableAttr(attr::VecReturn, R, SI, false, false)
8341 {
8342 }
8343
8344 VecReturnAttr *clone(ASTContext &C) const;
8345 void printPretty(raw_ostream &OS,
8346 const PrintingPolicy &Policy) const;
8347 const char *getSpelling() const;
8348
8349
8350 static bool classof(const Attr *A) { return A->getKind() == attr::VecReturn; }
8351};
8352
8353class VecTypeHintAttr : public InheritableAttr {
8354TypeSourceInfo * typeHint;
8355
8356public:
8357 static VecTypeHintAttr *CreateImplicit(ASTContext &Ctx, TypeSourceInfo * TypeHint, SourceRange Loc = SourceRange()) {
8358 auto *A = new (Ctx) VecTypeHintAttr(Loc, Ctx, TypeHint, 0);
8359 A->setImplicit(true);
8360 return A;
8361 }
8362
8363 VecTypeHintAttr(SourceRange R, ASTContext &Ctx
8364 , TypeSourceInfo * TypeHint
8365 , unsigned SI
8366 )
8367 : InheritableAttr(attr::VecTypeHint, R, SI, false, false)
8368 , typeHint(TypeHint)
8369 {
8370 }
8371
8372 VecTypeHintAttr *clone(ASTContext &C) const;
8373 void printPretty(raw_ostream &OS,
8374 const PrintingPolicy &Policy) const;
8375 const char *getSpelling() const;
8376 QualType getTypeHint() const {
8377 return typeHint->getType();
8378 } TypeSourceInfo * getTypeHintLoc() const {
8379 return typeHint;
8380 }
8381
8382
8383
8384 static bool classof(const Attr *A) { return A->getKind() == attr::VecTypeHint; }
8385};
8386
8387class VectorCallAttr : public InheritableAttr {
8388public:
8389 static VectorCallAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
8390 auto *A = new (Ctx) VectorCallAttr(Loc, Ctx, 0);
8391 A->setImplicit(true);
8392 return A;
8393 }
8394
8395 VectorCallAttr(SourceRange R, ASTContext &Ctx
8396 , unsigned SI
8397 )
8398 : InheritableAttr(attr::VectorCall, R, SI, false, false)
8399 {
8400 }
8401
8402 VectorCallAttr *clone(ASTContext &C) const;
8403 void printPretty(raw_ostream &OS,
8404 const PrintingPolicy &Policy) const;
8405 const char *getSpelling() const;
8406
8407
8408 static bool classof(const Attr *A) { return A->getKind() == attr::VectorCall; }
8409};
8410
8411class VisibilityAttr : public InheritableAttr {
8412public:
8413 enum VisibilityType {
8414 Default,
8415 Hidden,
8416 Protected
8417 };
8418private:
8419 VisibilityType visibility;
8420
8421public:
8422 static VisibilityAttr *CreateImplicit(ASTContext &Ctx, VisibilityType Visibility, SourceRange Loc = SourceRange()) {
8423 auto *A = new (Ctx) VisibilityAttr(Loc, Ctx, Visibility, 0);
8424 A->setImplicit(true);
8425 return A;
8426 }
8427
8428 VisibilityAttr(SourceRange R, ASTContext &Ctx
8429 , VisibilityType Visibility
8430 , unsigned SI
8431 )
8432 : InheritableAttr(attr::Visibility, R, SI, false, false)
8433 , visibility(Visibility)
8434 {
8435 }
8436
8437 VisibilityAttr *clone(ASTContext &C) const;
8438 void printPretty(raw_ostream &OS,
8439 const PrintingPolicy &Policy) const;
8440 const char *getSpelling() const;
8441 VisibilityType getVisibility() const {
8442 return visibility;
8443 }
8444
8445 static bool ConvertStrToVisibilityType(StringRef Val, VisibilityType &Out) {
8446 Optional<VisibilityType> R = llvm::StringSwitch<Optional<VisibilityType>>(Val)
8447 .Case("default", VisibilityAttr::Default)
8448 .Case("hidden", VisibilityAttr::Hidden)
8449 .Case("internal", VisibilityAttr::Hidden)
8450 .Case("protected", VisibilityAttr::Protected)
8451 .Default(Optional<VisibilityType>());
8452 if (R) {
8453 Out = *R;
8454 return true;
8455 }
8456 return false;
8457 }
8458
8459 static const char *ConvertVisibilityTypeToStr(VisibilityType Val) {
8460 switch(Val) {
8461 case VisibilityAttr::Default: return "default";
8462 case VisibilityAttr::Hidden: return "hidden";
8463 case VisibilityAttr::Protected: return "protected";
8464 }
8465 llvm_unreachable("No enumerator with that value")::llvm::llvm_unreachable_internal("No enumerator with that value"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 8465)
;
8466 }
8467
8468
8469 static bool classof(const Attr *A) { return A->getKind() == attr::Visibility; }
8470};
8471
8472class WarnUnusedAttr : public InheritableAttr {
8473public:
8474 static WarnUnusedAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
8475 auto *A = new (Ctx) WarnUnusedAttr(Loc, Ctx, 0);
8476 A->setImplicit(true);
8477 return A;
8478 }
8479
8480 WarnUnusedAttr(SourceRange R, ASTContext &Ctx
8481 , unsigned SI
8482 )
8483 : InheritableAttr(attr::WarnUnused, R, SI, false, false)
8484 {
8485 }
8486
8487 WarnUnusedAttr *clone(ASTContext &C) const;
8488 void printPretty(raw_ostream &OS,
8489 const PrintingPolicy &Policy) const;
8490 const char *getSpelling() const;
8491
8492
8493 static bool classof(const Attr *A) { return A->getKind() == attr::WarnUnused; }
8494};
8495
8496class WarnUnusedResultAttr : public InheritableAttr {
8497public:
8498 enum Spelling {
8499 CXX11_nodiscard = 0,
8500 C2x_nodiscard = 1,
8501 CXX11_clang_warn_unused_result = 2,
8502 GNU_warn_unused_result = 3,
8503 CXX11_gnu_warn_unused_result = 4
8504 };
8505
8506 static WarnUnusedResultAttr *CreateImplicit(ASTContext &Ctx, Spelling S, SourceRange Loc = SourceRange()) {
8507 auto *A = new (Ctx) WarnUnusedResultAttr(Loc, Ctx, S);
8508 A->setImplicit(true);
8509 return A;
8510 }
8511
8512 WarnUnusedResultAttr(SourceRange R, ASTContext &Ctx
8513 , unsigned SI
8514 )
8515 : InheritableAttr(attr::WarnUnusedResult, R, SI, false, false)
8516 {
8517 }
8518
8519 WarnUnusedResultAttr *clone(ASTContext &C) const;
8520 void printPretty(raw_ostream &OS,
8521 const PrintingPolicy &Policy) const;
8522 const char *getSpelling() const;
8523 Spelling getSemanticSpelling() const {
8524 switch (SpellingListIndex) {
8525 default: llvm_unreachable("Unknown spelling list index")::llvm::llvm_unreachable_internal("Unknown spelling list index"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 8525)
;
8526 case 0: return CXX11_nodiscard;
8527 case 1: return C2x_nodiscard;
8528 case 2: return CXX11_clang_warn_unused_result;
8529 case 3: return GNU_warn_unused_result;
8530 case 4: return CXX11_gnu_warn_unused_result;
8531 }
8532 }
8533
8534
8535 static bool classof(const Attr *A) { return A->getKind() == attr::WarnUnusedResult; }
8536};
8537
8538class WeakAttr : public InheritableAttr {
8539public:
8540 static WeakAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
8541 auto *A = new (Ctx) WeakAttr(Loc, Ctx, 0);
8542 A->setImplicit(true);
8543 return A;
8544 }
8545
8546 WeakAttr(SourceRange R, ASTContext &Ctx
8547 , unsigned SI
8548 )
8549 : InheritableAttr(attr::Weak, R, SI, false, false)
8550 {
8551 }
8552
8553 WeakAttr *clone(ASTContext &C) const;
8554 void printPretty(raw_ostream &OS,
8555 const PrintingPolicy &Policy) const;
8556 const char *getSpelling() const;
8557
8558
8559 static bool classof(const Attr *A) { return A->getKind() == attr::Weak; }
8560};
8561
8562class WeakImportAttr : public InheritableAttr {
8563public:
8564 static WeakImportAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
8565 auto *A = new (Ctx) WeakImportAttr(Loc, Ctx, 0);
8566 A->setImplicit(true);
8567 return A;
8568 }
8569
8570 WeakImportAttr(SourceRange R, ASTContext &Ctx
8571 , unsigned SI
8572 )
8573 : InheritableAttr(attr::WeakImport, R, SI, false, false)
8574 {
8575 }
8576
8577 WeakImportAttr *clone(ASTContext &C) const;
8578 void printPretty(raw_ostream &OS,
8579 const PrintingPolicy &Policy) const;
8580 const char *getSpelling() const;
8581
8582
8583 static bool classof(const Attr *A) { return A->getKind() == attr::WeakImport; }
8584};
8585
8586class WeakRefAttr : public InheritableAttr {
8587unsigned aliaseeLength;
8588char *aliasee;
8589
8590public:
8591 static WeakRefAttr *CreateImplicit(ASTContext &Ctx, llvm::StringRef Aliasee, SourceRange Loc = SourceRange()) {
8592 auto *A = new (Ctx) WeakRefAttr(Loc, Ctx, Aliasee, 0);
8593 A->setImplicit(true);
8594 return A;
8595 }
8596
8597 WeakRefAttr(SourceRange R, ASTContext &Ctx
8598 , llvm::StringRef Aliasee
8599 , unsigned SI
8600 )
8601 : InheritableAttr(attr::WeakRef, R, SI, false, false)
8602 , aliaseeLength(Aliasee.size()),aliasee(new (Ctx, 1) char[aliaseeLength])
8603 {
8604 if (!Aliasee.empty())
8605 std::memcpy(aliasee, Aliasee.data(), aliaseeLength);
8606 }
8607
8608 WeakRefAttr(SourceRange R, ASTContext &Ctx
8609 , unsigned SI
8610 )
8611 : InheritableAttr(attr::WeakRef, R, SI, false, false)
8612 , aliaseeLength(0),aliasee(nullptr)
8613 {
8614 }
8615
8616 WeakRefAttr *clone(ASTContext &C) const;
8617 void printPretty(raw_ostream &OS,
8618 const PrintingPolicy &Policy) const;
8619 const char *getSpelling() const;
8620 llvm::StringRef getAliasee() const {
8621 return llvm::StringRef(aliasee, aliaseeLength);
8622 }
8623 unsigned getAliaseeLength() const {
8624 return aliaseeLength;
8625 }
8626 void setAliasee(ASTContext &C, llvm::StringRef S) {
8627 aliaseeLength = S.size();
8628 this->aliasee = new (C, 1) char [aliaseeLength];
8629 if (!S.empty())
8630 std::memcpy(this->aliasee, S.data(), aliaseeLength);
8631 }
8632
8633
8634
8635 static bool classof(const Attr *A) { return A->getKind() == attr::WeakRef; }
8636};
8637
8638class WorkGroupSizeHintAttr : public InheritableAttr {
8639unsigned xDim;
8640
8641unsigned yDim;
8642
8643unsigned zDim;
8644
8645public:
8646 static WorkGroupSizeHintAttr *CreateImplicit(ASTContext &Ctx, unsigned XDim, unsigned YDim, unsigned ZDim, SourceRange Loc = SourceRange()) {
8647 auto *A = new (Ctx) WorkGroupSizeHintAttr(Loc, Ctx, XDim, YDim, ZDim, 0);
8648 A->setImplicit(true);
8649 return A;
8650 }
8651
8652 WorkGroupSizeHintAttr(SourceRange R, ASTContext &Ctx
8653 , unsigned XDim
8654 , unsigned YDim
8655 , unsigned ZDim
8656 , unsigned SI
8657 )
8658 : InheritableAttr(attr::WorkGroupSizeHint, R, SI, false, false)
8659 , xDim(XDim)
8660 , yDim(YDim)
8661 , zDim(ZDim)
8662 {
8663 }
8664
8665 WorkGroupSizeHintAttr *clone(ASTContext &C) const;
8666 void printPretty(raw_ostream &OS,
8667 const PrintingPolicy &Policy) const;
8668 const char *getSpelling() const;
8669 unsigned getXDim() const {
8670 return xDim;
8671 }
8672
8673 unsigned getYDim() const {
8674 return yDim;
8675 }
8676
8677 unsigned getZDim() const {
8678 return zDim;
8679 }
8680
8681
8682
8683 static bool classof(const Attr *A) { return A->getKind() == attr::WorkGroupSizeHint; }
8684};
8685
8686class X86ForceAlignArgPointerAttr : public InheritableAttr {
8687public:
8688 static X86ForceAlignArgPointerAttr *CreateImplicit(ASTContext &Ctx, SourceRange Loc = SourceRange()) {
8689 auto *A = new (Ctx) X86ForceAlignArgPointerAttr(Loc, Ctx, 0);
8690 A->setImplicit(true);
8691 return A;
8692 }
8693
8694 X86ForceAlignArgPointerAttr(SourceRange R, ASTContext &Ctx
8695 , unsigned SI
8696 )
8697 : InheritableAttr(attr::X86ForceAlignArgPointer, R, SI, false, false)
8698 {
8699 }
8700
8701 X86ForceAlignArgPointerAttr *clone(ASTContext &C) const;
8702 void printPretty(raw_ostream &OS,
8703 const PrintingPolicy &Policy) const;
8704 const char *getSpelling() const;
8705
8706
8707 static bool classof(const Attr *A) { return A->getKind() == attr::X86ForceAlignArgPointer; }
8708};
8709
8710class XRayInstrumentAttr : public InheritableAttr {
8711public:
8712 enum Spelling {
8713 GNU_xray_always_instrument = 0,
8714 CXX11_clang_xray_always_instrument = 1,
8715 C2x_clang_xray_always_instrument = 2,
8716 GNU_xray_never_instrument = 3,
8717 CXX11_clang_xray_never_instrument = 4,
8718 C2x_clang_xray_never_instrument = 5
8719 };
8720
8721 static XRayInstrumentAttr *CreateImplicit(ASTContext &Ctx, Spelling S, SourceRange Loc = SourceRange()) {
8722 auto *A = new (Ctx) XRayInstrumentAttr(Loc, Ctx, S);
8723 A->setImplicit(true);
8724 return A;
8725 }
8726
8727 XRayInstrumentAttr(SourceRange R, ASTContext &Ctx
8728 , unsigned SI
8729 )
8730 : InheritableAttr(attr::XRayInstrument, R, SI, false, false)
8731 {
8732 }
8733
8734 XRayInstrumentAttr *clone(ASTContext &C) const;
8735 void printPretty(raw_ostream &OS,
8736 const PrintingPolicy &Policy) const;
8737 const char *getSpelling() const;
8738 Spelling getSemanticSpelling() const {
8739 switch (SpellingListIndex) {
8740 default: llvm_unreachable("Unknown spelling list index")::llvm::llvm_unreachable_internal("Unknown spelling list index"
, "/build/llvm-toolchain-snapshot-7~svn329677/build-llvm/tools/clang/include/clang/AST/Attrs.inc"
, 8740)
;
8741 case 0: return GNU_xray_always_instrument;
8742 case 1: return CXX11_clang_xray_always_instrument;
8743 case 2: return C2x_clang_xray_always_instrument;
8744 case 3: return GNU_xray_never_instrument;
8745 case 4: return CXX11_clang_xray_never_instrument;
8746 case 5: return C2x_clang_xray_never_instrument;
8747 }
8748 }
8749 bool alwaysXRayInstrument() const { return SpellingListIndex == 0 ||
8750 SpellingListIndex == 1 ||
8751 SpellingListIndex == 2; }
8752 bool neverXRayInstrument() const { return SpellingListIndex == 3 ||
8753 SpellingListIndex == 4 ||
8754 SpellingListIndex == 5; }
8755
8756
8757 static bool classof(const Attr *A) { return A->getKind() == attr::XRayInstrument; }
8758};
8759
8760class XRayLogArgsAttr : public InheritableAttr {
8761unsigned argumentCount;
8762
8763public:
8764 static XRayLogArgsAttr *CreateImplicit(ASTContext &Ctx, unsigned ArgumentCount, SourceRange Loc = SourceRange()) {
8765 auto *A = new (Ctx) XRayLogArgsAttr(Loc, Ctx, ArgumentCount, 0);
8766 A->setImplicit(true);
8767 return A;
8768 }
8769
8770 XRayLogArgsAttr(SourceRange R, ASTContext &Ctx
8771 , unsigned ArgumentCount
8772 , unsigned SI
8773 )
8774 : InheritableAttr(attr::XRayLogArgs, R, SI, false, false)
8775 , argumentCount(ArgumentCount)
8776 {
8777 }
8778
8779 XRayLogArgsAttr *clone(ASTContext &C) const;
8780 void printPretty(raw_ostream &OS,
8781 const PrintingPolicy &Policy) const;
8782 const char *getSpelling() const;
8783 unsigned getArgumentCount() const {
8784 return argumentCount;
8785 }
8786
8787
8788
8789 static bool classof(const Attr *A) { return A->getKind() == attr::XRayLogArgs; }
8790};
8791
8792#endif // LLVM_CLANG_ATTR_CLASSES_INC