Clang Project

clang_source_code/lib/Sema/SemaDecl.cpp
1//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9//  This file implements semantic analysis for declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/CommentDiagnostic.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclTemplate.h"
23#include "clang/AST/EvaluatedExprVisitor.h"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/StmtCXX.h"
26#include "clang/Basic/Builtins.h"
27#include "clang/Basic/PartialDiagnostic.h"
28#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/TargetInfo.h"
30#include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
31#include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
32#include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
33#include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
34#include "clang/Sema/CXXFieldCollector.h"
35#include "clang/Sema/DeclSpec.h"
36#include "clang/Sema/DelayedDiagnostic.h"
37#include "clang/Sema/Initialization.h"
38#include "clang/Sema/Lookup.h"
39#include "clang/Sema/ParsedTemplate.h"
40#include "clang/Sema/Scope.h"
41#include "clang/Sema/ScopeInfo.h"
42#include "clang/Sema/SemaInternal.h"
43#include "clang/Sema/Template.h"
44#include "llvm/ADT/SmallString.h"
45#include "llvm/ADT/Triple.h"
46#include <algorithm>
47#include <cstring>
48#include <functional>
49
50using namespace clang;
51using namespace sema;
52
53Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *PtrDecl *OwnedType) {
54  if (OwnedType) {
55    Decl *Group[2] = { OwnedTypePtr };
56    return DeclGroupPtrTy::make(DeclGroupRef::Create(ContextGroup2));
57  }
58
59  return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
60}
61
62namespace {
63
64class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
65 public:
66   TypeNameValidatorCCC(bool AllowInvalidbool WantClass = false,
67                        bool AllowTemplates = false,
68                        bool AllowNonTemplates = true)
69       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70         AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
71     WantExpressionKeywords = false;
72     WantCXXNamedCasts = false;
73     WantRemainingKeywords = false;
74  }
75
76  bool ValidateCandidate(const TypoCorrection &candidate) override {
77    if (NamedDecl *ND = candidate.getCorrectionDecl()) {
78      if (!AllowInvalidDecl && ND->isInvalidDecl())
79        return false;
80
81      if (getAsTypeTemplateDecl(ND))
82        return AllowTemplates;
83
84      bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
85      if (!IsType)
86        return false;
87
88      if (AllowNonTemplates)
89        return true;
90
91      // An injected-class-name of a class template (specialization) is valid
92      // as a template or as a non-template.
93      if (AllowTemplates) {
94        auto *RD = dyn_cast<CXXRecordDecl>(ND);
95        if (!RD || !RD->isInjectedClassName())
96          return false;
97        RD = cast<CXXRecordDecl>(RD->getDeclContext());
98        return RD->getDescribedClassTemplate() ||
99               isa<ClassTemplateSpecializationDecl>(RD);
100      }
101
102      return false;
103    }
104
105    return !WantClassName && candidate.isKeyword();
106  }
107
108  std::unique_ptr<CorrectionCandidateCallbackclone() override {
109    return llvm::make_unique<TypeNameValidatorCCC>(*this);
110  }
111
112 private:
113  bool AllowInvalidDecl;
114  bool WantClassName;
115  bool AllowTemplates;
116  bool AllowNonTemplates;
117};
118
119// end anonymous namespace
120
121/// Determine whether the token kind starts a simple-type-specifier.
122bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kindconst {
123  switch (Kind) {
124  // FIXME: Take into account the current language when deciding whether a
125  // token kind is a valid type specifier
126  case tok::kw_short:
127  case tok::kw_long:
128  case tok::kw___int64:
129  case tok::kw___int128:
130  case tok::kw_signed:
131  case tok::kw_unsigned:
132  case tok::kw_void:
133  case tok::kw_char:
134  case tok::kw_int:
135  case tok::kw_half:
136  case tok::kw_float:
137  case tok::kw_double:
138  case tok::kw__Float16:
139  case tok::kw___float128:
140  case tok::kw_wchar_t:
141  case tok::kw_bool:
142  case tok::kw___underlying_type:
143  case tok::kw___auto_type:
144    return true;
145
146  case tok::annot_typename:
147  case tok::kw_char16_t:
148  case tok::kw_char32_t:
149  case tok::kw_typeof:
150  case tok::annot_decltype:
151  case tok::kw_decltype:
152    return getLangOpts().CPlusPlus;
153
154  case tok::kw_char8_t:
155    return getLangOpts().Char8;
156
157  default:
158    break;
159  }
160
161  return false;
162}
163
164namespace {
165enum class UnqualifiedTypeNameLookupResult {
166  NotFound,
167  FoundNonType,
168  FoundType
169};
170// end anonymous namespace
171
172/// Tries to perform unqualified lookup of the type decls in bases for
173/// dependent class.
174/// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
175/// type decl, \a FoundType if only type decls are found.
176static UnqualifiedTypeNameLookupResult
177lookupUnqualifiedTypeNameInBase(Sema &Sconst IdentifierInfo &II,
178                                SourceLocation NameLoc,
179                                const CXXRecordDecl *RD) {
180  if (!RD->hasDefinition())
181    return UnqualifiedTypeNameLookupResult::NotFound;
182  // Look for type decls in base classes.
183  UnqualifiedTypeNameLookupResult FoundTypeDecl =
184      UnqualifiedTypeNameLookupResult::NotFound;
185  for (const auto &Base : RD->bases()) {
186    const CXXRecordDecl *BaseRD = nullptr;
187    if (auto *BaseTT = Base.getType()->getAs<TagType>())
188      BaseRD = BaseTT->getAsCXXRecordDecl();
189    else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
190      // Look for type decls in dependent base classes that have known primary
191      // templates.
192      if (!TST || !TST->isDependentType())
193        continue;
194      auto *TD = TST->getTemplateName().getAsTemplateDecl();
195      if (!TD)
196        continue;
197      if (auto *BasePrimaryTemplate =
198          dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
199        if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
200          BaseRD = BasePrimaryTemplate;
201        else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
202          if (const ClassTemplatePartialSpecializationDecl *PS =
203                  CTD->findPartialSpecialization(Base.getType()))
204            if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
205              BaseRD = PS;
206        }
207      }
208    }
209    if (BaseRD) {
210      for (NamedDecl *ND : BaseRD->lookup(&II)) {
211        if (!isa<TypeDecl>(ND))
212          return UnqualifiedTypeNameLookupResult::FoundNonType;
213        FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
214      }
215      if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
216        switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
217        case UnqualifiedTypeNameLookupResult::FoundNonType:
218          return UnqualifiedTypeNameLookupResult::FoundNonType;
219        case UnqualifiedTypeNameLookupResult::FoundType:
220          FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
221          break;
222        case UnqualifiedTypeNameLookupResult::NotFound:
223          break;
224        }
225      }
226    }
227  }
228
229  return FoundTypeDecl;
230}
231
232static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
233                                                      const IdentifierInfo &II,
234                                                      SourceLocation NameLoc) {
235  // Lookup in the parent class template context, if any.
236  const CXXRecordDecl *RD = nullptr;
237  UnqualifiedTypeNameLookupResult FoundTypeDecl =
238      UnqualifiedTypeNameLookupResult::NotFound;
239  for (DeclContext *DC = S.CurContext;
240       DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
241       DC = DC->getParent()) {
242    // Look for type decls in dependent base classes that have known primary
243    // templates.
244    RD = dyn_cast<CXXRecordDecl>(DC);
245    if (RD && RD->getDescribedClassTemplate())
246      FoundTypeDecl = lookupUnqualifiedTypeNameInBase(SIINameLocRD);
247  }
248  if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
249    return nullptr;
250
251  // We found some types in dependent base classes.  Recover as if the user
252  // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
253  // lookup during template instantiation.
254  S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
255
256  ASTContext &Context = S.Context;
257  auto *NNS = NestedNameSpecifier::Create(Contextnullptrfalse,
258                                          cast<Type>(Context.getRecordType(RD)));
259  QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
260
261  CXXScopeSpec SS;
262  SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
263
264  TypeLocBuilder Builder;
265  DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
266  DepTL.setNameLoc(NameLoc);
267  DepTL.setElaboratedKeywordLoc(SourceLocation());
268  DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
269  return S.CreateParsedType(TBuilder.getTypeSourceInfo(ContextT));
270}
271
272/// If the identifier refers to a type name within this scope,
273/// return the declaration of that type.
274///
275/// This routine performs ordinary name lookup of the identifier II
276/// within the given scope, with optional C++ scope specifier SS, to
277/// determine whether the name refers to a type. If so, returns an
278/// opaque pointer (actually a QualType) corresponding to that
279/// type. Otherwise, returns NULL.
280ParsedType Sema::getTypeName(const IdentifierInfo &IISourceLocation NameLoc,
281                             Scope *SCXXScopeSpec *SS,
282                             bool isClassNamebool HasTrailingDot,
283                             ParsedType ObjectTypePtr,
284                             bool IsCtorOrDtorName,
285                             bool WantNontrivialTypeSourceInfo,
286                             bool IsClassTemplateDeductionContext,
287                             IdentifierInfo **CorrectedII) {
288  // FIXME: Consider allowing this outside C++1z mode as an extension.
289  bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
290                              getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
291                              !isClassName && !HasTrailingDot;
292
293  // Determine where we will perform name lookup.
294  DeclContext *LookupCtx = nullptr;
295  if (ObjectTypePtr) {
296    QualType ObjectType = ObjectTypePtr.get();
297    if (ObjectType->isRecordType())
298      LookupCtx = computeDeclContext(ObjectType);
299  } else if (SS && SS->isNotEmpty()) {
300    LookupCtx = computeDeclContext(*SSfalse);
301
302    if (!LookupCtx) {
303      if (isDependentScopeSpecifier(*SS)) {
304        // C++ [temp.res]p3:
305        //   A qualified-id that refers to a type and in which the
306        //   nested-name-specifier depends on a template-parameter (14.6.2)
307        //   shall be prefixed by the keyword typename to indicate that the
308        //   qualified-id denotes a type, forming an
309        //   elaborated-type-specifier (7.1.5.3).
310        //
311        // We therefore do not perform any name lookup if the result would
312        // refer to a member of an unknown specialization.
313        if (!isClassName && !IsCtorOrDtorName)
314          return nullptr;
315
316        // We know from the grammar that this name refers to a type,
317        // so build a dependent node to describe the type.
318        if (WantNontrivialTypeSourceInfo)
319          return ActOnTypenameType(SSourceLocation(), *SSIINameLoc).get();
320
321        NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
322        QualType T = CheckTypenameType(ETK_NoneSourceLocation(), QualifierLoc,
323                                       IINameLoc);
324        return ParsedType::make(T);
325      }
326
327      return nullptr;
328    }
329
330    if (!LookupCtx->isDependentContext() &&
331        RequireCompleteDeclContext(*SSLookupCtx))
332      return nullptr;
333  }
334
335  // FIXME: LookupNestedNameSpecifierName isn't the right kind of
336  // lookup for class-names.
337  LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
338                                      LookupOrdinaryName;
339  LookupResult Result(*this, &IINameLocKind);
340  if (LookupCtx) {
341    // Perform "qualified" name lookup into the declaration context we
342    // computed, which is either the type of the base of a member access
343    // expression or the declaration context associated with a prior
344    // nested-name-specifier.
345    LookupQualifiedName(ResultLookupCtx);
346
347    if (ObjectTypePtr && Result.empty()) {
348      // C++ [basic.lookup.classref]p3:
349      //   If the unqualified-id is ~type-name, the type-name is looked up
350      //   in the context of the entire postfix-expression. If the type T of
351      //   the object expression is of a class type C, the type-name is also
352      //   looked up in the scope of class C. At least one of the lookups shall
353      //   find a name that refers to (possibly cv-qualified) T.
354      LookupName(ResultS);
355    }
356  } else {
357    // Perform unqualified name lookup.
358    LookupName(ResultS);
359
360    // For unqualified lookup in a class template in MSVC mode, look into
361    // dependent base classes where the primary class template is known.
362    if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
363      if (ParsedType TypeInBase =
364              recoverFromTypeInKnownDependentBase(*thisIINameLoc))
365        return TypeInBase;
366    }
367  }
368
369  NamedDecl *IIDecl = nullptr;
370  switch (Result.getResultKind()) {
371  case LookupResult::NotFound:
372  case LookupResult::NotFoundInCurrentInstantiation:
373    if (CorrectedII) {
374      TypeNameValidatorCCC CCC(/*AllowInvalid=*/trueisClassName,
375                               AllowDeducedTemplate);
376      TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
377                                              SSSCCCCTK_ErrorRecovery);
378      IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
379      TemplateTy Template;
380      bool MemberOfUnknownSpecialization;
381      UnqualifiedId TemplateName;
382      TemplateName.setIdentifier(NewIINameLoc);
383      NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
384      CXXScopeSpec NewSS, *NewSSPtr = SS;
385      if (SS && NNS) {
386        NewSS.MakeTrivial(ContextNNSSourceRange(NameLoc));
387        NewSSPtr = &NewSS;
388      }
389      if (Correction && (NNS || NewII != &II) &&
390          // Ignore a correction to a template type as the to-be-corrected
391          // identifier is not a template (typo correction for template names
392          // is handled elsewhere).
393          !(getLangOpts().CPlusPlus && NewSSPtr &&
394            isTemplateName(S*NewSSPtrfalseTemplateNamenullptrfalse,
395                           TemplateMemberOfUnknownSpecialization))) {
396        ParsedType Ty = getTypeName(*NewIINameLocSNewSSPtr,
397                                    isClassNameHasTrailingDotObjectTypePtr,
398                                    IsCtorOrDtorName,
399                                    WantNontrivialTypeSourceInfo,
400                                    IsClassTemplateDeductionContext);
401        if (Ty) {
402          diagnoseTypo(Correction,
403                       PDiag(diag::err_unknown_type_or_class_name_suggest)
404                         << Result.getLookupName() << isClassName);
405          if (SS && NNS)
406            SS->MakeTrivial(ContextNNSSourceRange(NameLoc));
407          *CorrectedII = NewII;
408          return Ty;
409        }
410      }
411    }
412    // If typo correction failed or was not performed, fall through
413    LLVM_FALLTHROUGH;
414  case LookupResult::FoundOverloaded:
415  case LookupResult::FoundUnresolvedValue:
416    Result.suppressDiagnostics();
417    return nullptr;
418
419  case LookupResult::Ambiguous:
420    // Recover from type-hiding ambiguities by hiding the type.  We'll
421    // do the lookup again when looking for an object, and we can
422    // diagnose the error then.  If we don't do this, then the error
423    // about hiding the type will be immediately followed by an error
424    // that only makes sense if the identifier was treated like a type.
425    if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
426      Result.suppressDiagnostics();
427      return nullptr;
428    }
429
430    // Look to see if we have a type anywhere in the list of results.
431    for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
432         Res != ResEnd; ++Res) {
433      if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res) ||
434          (AllowDeducedTemplate && getAsTypeTemplateDecl(*Res))) {
435        if (!IIDecl ||
436            (*Res)->getLocation().getRawEncoding() <
437              IIDecl->getLocation().getRawEncoding())
438          IIDecl = *Res;
439      }
440    }
441
442    if (!IIDecl) {
443      // None of the entities we found is a type, so there is no way
444      // to even assume that the result is a type. In this case, don't
445      // complain about the ambiguity. The parser will either try to
446      // perform this lookup again (e.g., as an object name), which
447      // will produce the ambiguity, or will complain that it expected
448      // a type name.
449      Result.suppressDiagnostics();
450      return nullptr;
451    }
452
453    // We found a type within the ambiguous lookup; diagnose the
454    // ambiguity and then return that type. This might be the right
455    // answer, or it might not be, but it suppresses any attempt to
456    // perform the name lookup again.
457    break;
458
459  case LookupResult::Found:
460    IIDecl = Result.getFoundDecl();
461    break;
462  }
463
464   (0) . __assert_fail ("IIDecl && \"Didn't find decl\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 464, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(IIDecl && "Didn't find decl");
465
466  QualType T;
467  if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
468    // C++ [class.qual]p2: A lookup that would find the injected-class-name
469    // instead names the constructors of the class, except when naming a class.
470    // This is ill-formed when we're not actually forming a ctor or dtor name.
471    auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
472    auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
473    if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
474        FoundRD->isInjectedClassName() &&
475        declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
476      Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
477          << &II << /*Type*/1;
478
479    DiagnoseUseOfDecl(IIDeclNameLoc);
480
481    T = Context.getTypeDeclType(TD);
482    MarkAnyDeclReferenced(TD->getLocation(), TD/*OdrUse=*/false);
483  } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
484    (void)DiagnoseUseOfDecl(IDeclNameLoc);
485    if (!HasTrailingDot)
486      T = Context.getObjCInterfaceType(IDecl);
487  } else if (AllowDeducedTemplate) {
488    if (auto *TD = getAsTypeTemplateDecl(IIDecl))
489      T = Context.getDeducedTemplateSpecializationType(TemplateName(TD),
490                                                       QualType(), false);
491  }
492
493  if (T.isNull()) {
494    // If it's not plausibly a type, suppress diagnostics.
495    Result.suppressDiagnostics();
496    return nullptr;
497  }
498
499  // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
500  // constructor or destructor name (in such a case, the scope specifier
501  // will be attached to the enclosing Expr or Decl node).
502  if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
503      !isa<ObjCInterfaceDecl>(IIDecl)) {
504    if (WantNontrivialTypeSourceInfo) {
505      // Construct a type with type-source information.
506      TypeLocBuilder Builder;
507      Builder.pushTypeSpec(T).setNameLoc(NameLoc);
508
509      T = getElaboratedType(ETK_None, *SST);
510      ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
511      ElabTL.setElaboratedKeywordLoc(SourceLocation());
512      ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
513      return CreateParsedType(TBuilder.getTypeSourceInfo(ContextT));
514    } else {
515      T = getElaboratedType(ETK_None, *SST);
516    }
517  }
518
519  return ParsedType::make(T);
520}
521
522// Builds a fake NNS for the given decl context.
523static NestedNameSpecifier *
524synthesizeCurrentNestedNameSpecifier(ASTContext &ContextDeclContext *DC) {
525  for (;; DC = DC->getLookupParent()) {
526    DC = DC->getPrimaryContext();
527    auto *ND = dyn_cast<NamespaceDecl>(DC);
528    if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
529      return NestedNameSpecifier::Create(Context, nullptr, ND);
530    else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
531      return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
532                                         RD->getTypeForDecl());
533    else if (isa<TranslationUnitDecl>(DC))
534      return NestedNameSpecifier::GlobalSpecifier(Context);
535  }
536  llvm_unreachable("something isn't in TU scope?");
537}
538
539/// Find the parent class with dependent bases of the innermost enclosing method
540/// context. Do not look for enclosing CXXRecordDecls directly, or we will end
541/// up allowing unqualified dependent type names at class-level, which MSVC
542/// correctly rejects.
543static const CXXRecordDecl *
544findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
545  for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
546    DC = DC->getPrimaryContext();
547    if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
548      if (MD->getParent()->hasAnyDependentBases())
549        return MD->getParent();
550  }
551  return nullptr;
552}
553
554ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
555                                          SourceLocation NameLoc,
556                                          bool IsTemplateTypeArg) {
557   (0) . __assert_fail ("getLangOpts().MSVCCompat && \"shouldn't be called in non-MSVC mode\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 557, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
558
559  NestedNameSpecifier *NNS = nullptr;
560  if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
561    // If we weren't able to parse a default template argument, delay lookup
562    // until instantiation time by making a non-dependent DependentTypeName. We
563    // pretend we saw a NestedNameSpecifier referring to the current scope, and
564    // lookup is retried.
565    // FIXME: This hurts our diagnostic quality, since we get errors like "no
566    // type named 'Foo' in 'current_namespace'" when the user didn't write any
567    // name specifiers.
568    NNS = synthesizeCurrentNestedNameSpecifier(ContextCurContext);
569    Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
570  } else if (const CXXRecordDecl *RD =
571                 findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
572    // Build a DependentNameType that will perform lookup into RD at
573    // instantiation time.
574    NNS = NestedNameSpecifier::Create(ContextnullptrRD->isTemplateDecl(),
575                                      RD->getTypeForDecl());
576
577    // Diagnose that this identifier was undeclared, and retry the lookup during
578    // template instantiation.
579    Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
580                                                                      << RD;
581  } else {
582    // This is not a situation that we should recover from.
583    return ParsedType();
584  }
585
586  QualType T = Context.getDependentNameType(ETK_NoneNNS, &II);
587
588  // Build type location information.  We synthesized the qualifier, so we have
589  // to build a fake NestedNameSpecifierLoc.
590  NestedNameSpecifierLocBuilder NNSLocBuilder;
591  NNSLocBuilder.MakeTrivial(ContextNNSSourceRange(NameLoc));
592  NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
593
594  TypeLocBuilder Builder;
595  DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
596  DepTL.setNameLoc(NameLoc);
597  DepTL.setElaboratedKeywordLoc(SourceLocation());
598  DepTL.setQualifierLoc(QualifierLoc);
599  return CreateParsedType(TBuilder.getTypeSourceInfo(ContextT));
600}
601
602/// isTagName() - This method is called *for error recovery purposes only*
603/// to determine if the specified name is a valid tag name ("struct foo").  If
604/// so, this returns the TST for the tag corresponding to it (TST_enum,
605/// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
606/// cases in C where the user forgot to specify the tag.
607DeclSpec::TST Sema::isTagName(IdentifierInfo &IIScope *S) {
608  // Do a tag name lookup in this scope.
609  LookupResult R(*this, &IISourceLocation(), LookupTagName);
610  LookupName(RSfalse);
611  R.suppressDiagnostics();
612  if (R.getResultKind() == LookupResult::Found)
613    if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
614      switch (TD->getTagKind()) {
615      case TTK_Structreturn DeclSpec::TST_struct;
616      case TTK_Interfacereturn DeclSpec::TST_interface;
617      case TTK_Union:  return DeclSpec::TST_union;
618      case TTK_Class:  return DeclSpec::TST_class;
619      case TTK_Enum:   return DeclSpec::TST_enum;
620      }
621    }
622
623  return DeclSpec::TST_unspecified;
624}
625
626/// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
627/// if a CXXScopeSpec's type is equal to the type of one of the base classes
628/// then downgrade the missing typename error to a warning.
629/// This is needed for MSVC compatibility; Example:
630/// @code
631/// template<class T> class A {
632/// public:
633///   typedef int TYPE;
634/// };
635/// template<class T> class B : public A<T> {
636/// public:
637///   A<T>::TYPE a; // no typename required because A<T> is a base class.
638/// };
639/// @endcode
640bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SSScope *S) {
641  if (CurContext->isRecord()) {
642    if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
643      return true;
644
645    const Type *Ty = SS->getScopeRep()->getAsType();
646
647    CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
648    for (const auto &Base : RD->bases())
649      if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
650        return true;
651    return S->isFunctionPrototypeScope();
652  }
653  return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
654}
655
656void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
657                                   SourceLocation IILoc,
658                                   Scope *S,
659                                   CXXScopeSpec *SS,
660                                   ParsedType &SuggestedType,
661                                   bool IsTemplateName) {
662  // Don't report typename errors for editor placeholders.
663  if (II->isEditorPlaceholder())
664    return;
665  // We don't have anything to suggest (yet).
666  SuggestedType = nullptr;
667
668  // There may have been a typo in the name of the type. Look up typo
669  // results, in case we have something that we can suggest.
670  TypeNameValidatorCCC CCC(/*AllowInvalid=*/false/*WantClass=*/false,
671                           /*AllowTemplates=*/IsTemplateName,
672                           /*AllowNonTemplates=*/!IsTemplateName);
673  if (TypoCorrection Corrected =
674          CorrectTypo(DeclarationNameInfo(IIIILoc), LookupOrdinaryNameSSS,
675                      CCCCTK_ErrorRecovery)) {
676    // FIXME: Support error recovery for the template-name case.
677    bool CanRecover = !IsTemplateName;
678    if (Corrected.isKeyword()) {
679      // We corrected to a keyword.
680      diagnoseTypo(Corrected,
681                   PDiag(IsTemplateName ? diag::err_no_template_suggest
682                                        : diag::err_unknown_typename_suggest)
683                       << II);
684      II = Corrected.getCorrectionAsIdentifierInfo();
685    } else {
686      // We found a similarly-named type or interface; suggest that.
687      if (!SS || !SS->isSet()) {
688        diagnoseTypo(Corrected,
689                     PDiag(IsTemplateName ? diag::err_no_template_suggest
690                                          : diag::err_unknown_typename_suggest)
691                         << II, CanRecover);
692      } else if (DeclContext *DC = computeDeclContext(*SSfalse)) {
693        std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
694        bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
695                                II->getName().equals(CorrectedStr);
696        diagnoseTypo(Corrected,
697                     PDiag(IsTemplateName
698                               ? diag::err_no_member_template_suggest
699                               : diag::err_unknown_nested_typename_suggest)
700                         << II << DC << DroppedSpecifier << SS->getRange(),
701                     CanRecover);
702      } else {
703        llvm_unreachable("could not have corrected a typo here");
704      }
705
706      if (!CanRecover)
707        return;
708
709      CXXScopeSpec tmpSS;
710      if (Corrected.getCorrectionSpecifier())
711        tmpSS.MakeTrivial(ContextCorrected.getCorrectionSpecifier(),
712                          SourceRange(IILoc));
713      // FIXME: Support class template argument deduction here.
714      SuggestedType =
715          getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILocS,
716                      tmpSS.isSet() ? &tmpSS : SSfalsefalsenullptr,
717                      /*IsCtorOrDtorName=*/false,
718                      /*NonTrivialTypeSourceInfo=*/true);
719    }
720    return;
721  }
722
723  if (getLangOpts().CPlusPlus && !IsTemplateName) {
724    // See if II is a class template that the user forgot to pass arguments to.
725    UnqualifiedId Name;
726    Name.setIdentifier(IIIILoc);
727    CXXScopeSpec EmptySS;
728    TemplateTy TemplateResult;
729    bool MemberOfUnknownSpecialization;
730    if (isTemplateName(SSS ? *SS : EmptySS/*hasTemplateKeyword=*/false,
731                       NamenullptrtrueTemplateResult,
732                       MemberOfUnknownSpecialization) == TNK_Type_template) {
733      diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
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(*SSfalse))
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(SSourceLocation(),
759                                      *SS, *IIIILoc).get();
760  } else {
761     (0) . __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 762, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(SS && SS->isInvalid() &&
762 (0) . __assert_fail ("SS && SS->isInvalid() && \"Invalid scope specifier has already been diagnosed\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 762, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           "Invalid scope specifier has already been diagnosed");
763  }
764}
765
766/// Determine whether the given result set contains either a type name
767/// or
768static bool isResultTypeOrTemplate(LookupResult &Rconst 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 &SemaRefLookupResult &Result,
784                                    Scope *SCXXScopeSpec &SS,
785                                    IdentifierInfo *&Name,
786                                    SourceLocation NameLoc) {
787  LookupResult R(SemaRefNameNameLocSema::LookupTagName);
788  SemaRef.LookupParsedName(RS, &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(ResultS, &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 &SCXXScopeSpec &SS,
834                                  QualType TSourceLocation NameLoc) {
835  ASTContext &Context = S.Context;
836
837  TypeLocBuilder Builder;
838  Builder.pushTypeSpec(T).setNameLoc(NameLoc);
839
840  T = S.getElaboratedType(ETK_NoneSST);
841  ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
842  ElabTL.setElaboratedKeywordLoc(SourceLocation());
843  ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
844  return S.CreateParsedType(TBuilder.getTypeSourceInfo(ContextT));
845}
846
847Sema::NameClassification
848Sema::ClassifyName(Scope *SCXXScopeSpec &SSIdentifierInfo *&Name,
849                   SourceLocation NameLocconst Token &NextToken,
850                   bool IsAddressOfOperandCorrectionCandidateCallback *CCC) {
851  DeclarationNameInfo NameInfo(NameNameLoc);
852  ObjCMethodDecl *CurMethod = getCurMethodDecl();
853
854  if (NextToken.is(tok::coloncolon)) {
855    NestedNameSpecInfo IdInfo(NameNameLocNextToken.getLocation());
856    BuildCXXNestedNameSpecifier(SIdInfofalseSSnullptrfalse);
857  } else if (getLangOpts().CPlusPlus && SS.isSet() &&
858             isCurrentClassName(*NameS, &SS)) {
859    // Per [class.qual]p2, this names the constructors of SS, not the
860    // injected-class-name. We don't have a classification for that.
861    // There's not much point caching this result, since the parser
862    // will reject it later.
863    return NameClassification::Unknown();
864  }
865
866  LookupResult Result(*thisNameNameLocLookupOrdinaryName);
867  LookupParsedName(ResultS, &SS, !CurMethod);
868
869  // For unqualified lookup in a class template in MSVC mode, look into
870  // dependent base classes where the primary class template is known.
871  if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
872    if (ParsedType TypeInBase =
873            recoverFromTypeInKnownDependentBase(*this, *NameNameLoc))
874      return TypeInBase;
875  }
876
877  // Perform lookup for Objective-C instance variables (including automatically
878  // synthesized instance variables), if we're in an Objective-C method.
879  // FIXME: This lookup really, really needs to be folded in to the normal
880  // unqualified lookup mechanism.
881  if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(ResultNextToken)) {
882    ExprResult E = LookupInObjCMethod(ResultSNametrue);
883    if (E.get() || E.isInvalid())
884      return E;
885  }
886
887  bool SecondTry = false;
888  bool IsFilteredTemplateName = false;
889
890Corrected:
891  switch (Result.getResultKind()) {
892  case LookupResult::NotFound:
893    // If an unqualified-id is followed by a '(', then we have a function
894    // call.
895    if (!SS.isSet() && NextToken.is(tok::l_paren)) {
896      // In C++, this is an ADL-only call.
897      // FIXME: Reference?
898      if (getLangOpts().CPlusPlus)
899        return BuildDeclarationNameExpr(SSResult/*ADL=*/true);
900
901      // C90 6.3.2.2:
902      //   If the expression that precedes the parenthesized argument list in a
903      //   function call consists solely of an identifier, and if no
904      //   declaration is visible for this identifier, the identifier is
905      //   implicitly declared exactly as if, in the innermost block containing
906      //   the function call, the declaration
907      //
908      //     extern int identifier ();
909      //
910      //   appeared.
911      //
912      // We also allow this in C99 as an extension.
913      if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc*NameS)) {
914        Result.addDecl(D);
915        Result.resolveKind();
916        return BuildDeclarationNameExpr(SSResult/*ADL=*/false);
917      }
918    }
919
920    // In C, we first see whether there is a tag type by the same name, in
921    // which case it's likely that the user just forgot to write "enum",
922    // "struct", or "union".
923    if (!getLangOpts().CPlusPlus && !SecondTry &&
924        isTagTypeWithMissingTag(*thisResultSSSNameNameLoc)) {
925      break;
926    }
927
928    // Perform typo correction to determine if there is another name that is
929    // close to this name.
930    if (!SecondTry && CCC) {
931      SecondTry = true;
932      if (TypoCorrection Corrected =
933              CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
934                          &SS*CCCCTK_ErrorRecovery)) {
935        unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
936        unsigned QualifiedDiag = diag::err_no_member_suggest;
937
938        NamedDecl *FirstDecl = Corrected.getFoundDecl();
939        NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
940        if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
941            UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
942          UnqualifiedDiag = diag::err_no_template_suggest;
943          QualifiedDiag = diag::err_no_member_template_suggest;
944        } else if (UnderlyingFirstDecl &&
945                   (isa<TypeDecl>(UnderlyingFirstDecl) ||
946                    isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
947                    isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
948          UnqualifiedDiag = diag::err_unknown_typename_suggest;
949          QualifiedDiag = diag::err_unknown_nested_typename_suggest;
950        }
951
952        if (SS.isEmpty()) {
953          diagnoseTypo(CorrectedPDiag(UnqualifiedDiag) << Name);
954        } else {// FIXME: is this even reachable? Test it.
955          std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
956          bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
957                                  Name->getName().equals(CorrectedStr);
958          diagnoseTypo(CorrectedPDiag(QualifiedDiag)
959                                    << Name << computeDeclContext(SSfalse)
960                                    << DroppedSpecifier << SS.getRange());
961        }
962
963        // Update the name, so that the caller has the new name.
964        Name = Corrected.getCorrectionAsIdentifierInfo();
965
966        // Typo correction corrected to a keyword.
967        if (Corrected.isKeyword())
968          return Name;
969
970        // Also update the LookupResult...
971        // FIXME: This should probably go away at some point
972        Result.clear();
973        Result.setLookupName(Corrected.getCorrection());
974        if (FirstDecl)
975          Result.addDecl(FirstDecl);
976
977        // If we found an Objective-C instance variable, let
978        // LookupInObjCMethod build the appropriate expression to
979        // reference the ivar.
980        // FIXME: This is a gross hack.
981        if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
982          Result.clear();
983          ExprResult E(LookupInObjCMethod(ResultSIvar->getIdentifier()));
984          return E;
985        }
986
987        goto Corrected;
988      }
989    }
990
991    // We failed to correct; just fall through and let the parser deal with it.
992    Result.suppressDiagnostics();
993    return NameClassification::Unknown();
994
995  case LookupResult::NotFoundInCurrentInstantiation: {
996    // We performed name lookup into the current instantiation, and there were
997    // dependent bases, so we treat this result the same way as any other
998    // dependent nested-name-specifier.
999
1000    // C++ [temp.res]p2:
1001    //   A name used in a template declaration or definition and that is
1002    //   dependent on a template-parameter is assumed not to name a type
1003    //   unless the applicable name lookup finds a type name or the name is
1004    //   qualified by the keyword typename.
1005    //
1006    // FIXME: If the next token is '<', we might want to ask the parser to
1007    // perform some heroics to see if we actually have a
1008    // template-argument-list, which would indicate a missing 'template'
1009    // keyword here.
1010    return ActOnDependentIdExpression(SS/*TemplateKWLoc=*/SourceLocation(),
1011                                      NameInfoIsAddressOfOperand,
1012                                      /*TemplateArgs=*/nullptr);
1013  }
1014
1015  case LookupResult::Found:
1016  case LookupResult::FoundOverloaded:
1017  case LookupResult::FoundUnresolvedValue:
1018    break;
1019
1020  case LookupResult::Ambiguous:
1021    if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1022        hasAnyAcceptableTemplateNames(Result/*AllowFunctionTemplates=*/true,
1023                                      /*AllowDependent=*/false)) {
1024      // C++ [temp.local]p3:
1025      //   A lookup that finds an injected-class-name (10.2) can result in an
1026      //   ambiguity in certain cases (for example, if it is found in more than
1027      //   one base class). If all of the injected-class-names that are found
1028      //   refer to specializations of the same class template, and if the name
1029      //   is followed by a template-argument-list, the reference refers to the
1030      //   class template itself and not a specialization thereof, and is not
1031      //   ambiguous.
1032      //
1033      // This filtering can make an ambiguous result into an unambiguous one,
1034      // so try again after filtering out template names.
1035      FilterAcceptableTemplateNames(Result);
1036      if (!Result.isAmbiguous()) {
1037        IsFilteredTemplateName = true;
1038        break;
1039      }
1040    }
1041
1042    // Diagnose the ambiguity and return an error.
1043    return NameClassification::Error();
1044  }
1045
1046  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1047      (IsFilteredTemplateName ||
1048       hasAnyAcceptableTemplateNames(Result/*AllowFunctionTemplates=*/true,
1049                                     /*AllowDependent=*/false))) {
1050    // C++ [temp.names]p3:
1051    //   After name lookup (3.4) finds that a name is a template-name or that
1052    //   an operator-function-id or a literal- operator-id refers to a set of
1053    //   overloaded functions any member of which is a function template if
1054    //   this is followed by a <, the < is always taken as the delimiter of a
1055    //   template-argument-list and never as the less-than operator.
1056    if (!IsFilteredTemplateName)
1057      FilterAcceptableTemplateNames(Result);
1058
1059    if (!Result.empty()) {
1060      bool IsFunctionTemplate;
1061      bool IsVarTemplate;
1062      TemplateName Template;
1063      if (Result.end() - Result.begin() > 1) {
1064        IsFunctionTemplate = true;
1065        Template = Context.getOverloadedTemplateName(Result.begin(),
1066                                                     Result.end());
1067      } else {
1068        auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1069            *Result.begin(), /*AllowFunctionTemplates=*/true,
1070            /*AllowDependent=*/false));
1071        IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1072        IsVarTemplate = isa<VarTemplateDecl>(TD);
1073
1074        if (SS.isSet() && !SS.isInvalid())
1075          Template =
1076              Context.getQualifiedTemplateName(SS.getScopeRep(),
1077                                               /*TemplateKeyword=*/false, TD);
1078        else
1079          Template = TemplateName(TD);
1080      }
1081
1082      if (IsFunctionTemplate) {
1083        // Function templates always go through overload resolution, at which
1084        // point we'll perform the various checks (e.g., accessibility) we need
1085        // to based on which function we selected.
1086        Result.suppressDiagnostics();
1087
1088        return NameClassification::FunctionTemplate(Template);
1089      }
1090
1091      return IsVarTemplate ? NameClassification::VarTemplate(Template)
1092                           : NameClassification::TypeTemplate(Template);
1093    }
1094  }
1095
1096  NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1097  if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1098    DiagnoseUseOfDecl(TypeNameLoc);
1099    MarkAnyDeclReferenced(Type->getLocation(), Type/*OdrUse=*/false);
1100    QualType T = Context.getTypeDeclType(Type);
1101    if (SS.isNotEmpty())
1102      return buildNestedType(*thisSSTNameLoc);
1103    return ParsedType::make(T);
1104  }
1105
1106  ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1107  if (!Class) {
1108    // FIXME: It's unfortunate that we don't have a Type node for handling this.
1109    if (ObjCCompatibleAliasDecl *Alias =
1110            dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1111      Class = Alias->getClassInterface();
1112  }
1113
1114  if (Class) {
1115    DiagnoseUseOfDecl(ClassNameLoc);
1116
1117    if (NextToken.is(tok::period)) {
1118      // Interface. <something> is parsed as a property reference expression.
1119      // Just return "unknown" as a fall-through for now.
1120      Result.suppressDiagnostics();
1121      return NameClassification::Unknown();
1122    }
1123
1124    QualType T = Context.getObjCInterfaceType(Class);
1125    return ParsedType::make(T);
1126  }
1127
1128  // We can have a type template here if we're classifying a template argument.
1129  if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1130      !isa<VarTemplateDecl>(FirstDecl))
1131    return NameClassification::TypeTemplate(
1132        TemplateName(cast<TemplateDecl>(FirstDecl)));
1133
1134  // Check for a tag type hidden by a non-type decl in a few cases where it
1135  // seems likely a type is wanted instead of the non-type that was found.
1136  bool NextIsOp = NextToken.isOneOf(tok::amptok::star);
1137  if ((NextToken.is(tok::identifier) ||
1138       (NextIsOp &&
1139        FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1140      isTagTypeWithMissingTag(*thisResultSSSNameNameLoc)) {
1141    TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1142    DiagnoseUseOfDecl(TypeNameLoc);
1143    QualType T = Context.getTypeDeclType(Type);
1144    if (SS.isNotEmpty())
1145      return buildNestedType(*thisSSTNameLoc);
1146    return ParsedType::make(T);
1147  }
1148
1149  if (FirstDecl->isCXXClassMember())
1150    return BuildPossibleImplicitMemberExpr(SSSourceLocation(), Result,
1151                                           nullptrS);
1152
1153  bool ADL = UseArgumentDependentLookup(SSResultNextToken.is(tok::l_paren));
1154  return BuildDeclarationNameExpr(SSResultADL);
1155}
1156
1157Sema::TemplateNameKindForDiagnostics
1158Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1159  auto *TD = Name.getAsTemplateDecl();
1160  if (!TD)
1161    return TemplateNameKindForDiagnostics::DependentTemplate;
1162  if (isa<ClassTemplateDecl>(TD))
1163    return TemplateNameKindForDiagnostics::ClassTemplate;
1164  if (isa<FunctionTemplateDecl>(TD))
1165    return TemplateNameKindForDiagnostics::FunctionTemplate;
1166  if (isa<VarTemplateDecl>(TD))
1167    return TemplateNameKindForDiagnostics::VarTemplate;
1168  if (isa<TypeAliasTemplateDecl>(TD))
1169    return TemplateNameKindForDiagnostics::AliasTemplate;
1170  if (isa<TemplateTemplateParmDecl>(TD))
1171    return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1172  return TemplateNameKindForDiagnostics::DependentTemplate;
1173}
1174
1175// Determines the context to return to after temporarily entering a
1176// context.  This depends in an unnecessarily complicated way on the
1177// exact ordering of callbacks from the parser.
1178DeclContext *Sema::getContainingDC(DeclContext *DC) {
1179
1180  // Functions defined inline within classes aren't parsed until we've
1181  // finished parsing the top-level class, so the top-level class is
1182  // the context we'll need to return to.
1183  // A Lambda call operator whose parent is a class must not be treated
1184  // as an inline member function.  A Lambda can be used legally
1185  // either as an in-class member initializer or a default argument.  These
1186  // are parsed once the class has been marked complete and so the containing
1187  // context would be the nested class (when the lambda is defined in one);
1188  // If the class is not complete, then the lambda is being used in an
1189  // ill-formed fashion (such as to specify the width of a bit-field, or
1190  // in an array-bound) - in which case we still want to return the
1191  // lexically containing DC (which could be a nested class).
1192  if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1193    DC = DC->getLexicalParent();
1194
1195    // A function not defined within a class will always return to its
1196    // lexical context.
1197    if (!isa<CXXRecordDecl>(DC))
1198      return DC;
1199
1200    // A C++ inline method/friend is parsed *after* the topmost class
1201    // it was declared in is fully parsed ("complete");  the topmost
1202    // class is the context we need to return to.
1203    while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1204      DC = RD;
1205
1206    // Return the declaration context of the topmost class the inline method is
1207    // declared in.
1208    return DC;
1209  }
1210
1211  return DC->getLexicalParent();
1212}
1213
1214void Sema::PushDeclContext(Scope *SDeclContext *DC) {
1215   (0) . __assert_fail ("getContainingDC(DC) == CurContext && \"The next DeclContext should be lexically contained in the current one.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 1216, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(getContainingDC(DC) == CurContext &&
1216 (0) . __assert_fail ("getContainingDC(DC) == CurContext && \"The next DeclContext should be lexically contained in the current one.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 1216, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">      "The next DeclContext should be lexically contained in the current one.");
1217  CurContext = DC;
1218  S->setEntity(DC);
1219}
1220
1221void Sema::PopDeclContext() {
1222   (0) . __assert_fail ("CurContext && \"DeclContext imbalance!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 1222, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(CurContext && "DeclContext imbalance!");
1223
1224  CurContext = getContainingDC(CurContext);
1225   (0) . __assert_fail ("CurContext && \"Popped translation unit!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 1225, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(CurContext && "Popped translation unit!");
1226}
1227
1228Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1229                                                                    Decl *D) {
1230  // Unlike PushDeclContext, the context to which we return is not necessarily
1231  // the containing DC of TD, because the new context will be some pre-existing
1232  // TagDecl definition instead of a fresh one.
1233  auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1234  CurContext = cast<TagDecl>(D)->getDefinition();
1235   (0) . __assert_fail ("CurContext && \"skipping definition of undefined tag\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 1235, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(CurContext && "skipping definition of undefined tag");
1236  // Start lookups from the parent of the current context; we don't want to look
1237  // into the pre-existing complete definition.
1238  S->setEntity(CurContext->getLookupParent());
1239  return Result;
1240}
1241
1242void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1243  CurContext = static_cast<decltype(CurContext)>(Context);
1244}
1245
1246/// EnterDeclaratorContext - Used when we must lookup names in the context
1247/// of a declarator's nested name specifier.
1248///
1249void Sema::EnterDeclaratorContext(Scope *SDeclContext *DC) {
1250  // C++0x [basic.lookup.unqual]p13:
1251  //   A name used in the definition of a static data member of class
1252  //   X (after the qualified-id of the static member) is looked up as
1253  //   if the name was used in a member function of X.
1254  // C++0x [basic.lookup.unqual]p14:
1255  //   If a variable member of a namespace is defined outside of the
1256  //   scope of its namespace then any name used in the definition of
1257  //   the variable member (after the declarator-id) is looked up as
1258  //   if the definition of the variable member occurred in its
1259  //   namespace.
1260  // Both of these imply that we should push a scope whose context
1261  // is the semantic context of the declaration.  We can't use
1262  // PushDeclContext here because that context is not necessarily
1263  // lexically contained in the current context.  Fortunately,
1264  // the containing scope should have the appropriate information.
1265
1266   (0) . __assert_fail ("!S->getEntity() && \"scope already has entity\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 1266, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!S->getEntity() && "scope already has entity");
1267
1268#ifndef NDEBUG
1269  Scope *Ancestor = S->getParent();
1270  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1271   (0) . __assert_fail ("Ancestor->getEntity() == CurContext && \"ancestor context mismatch\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 1271, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1272#endif
1273
1274  CurContext = DC;
1275  S->setEntity(DC);
1276}
1277
1278void Sema::ExitDeclaratorContext(Scope *S) {
1279   (0) . __assert_fail ("S->getEntity() == CurContext && \"Context imbalance!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 1279, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(S->getEntity() == CurContext && "Context imbalance!");
1280
1281  // Switch back to the lexical context.  The safety of this is
1282  // enforced by an assert in EnterDeclaratorContext.
1283  Scope *Ancestor = S->getParent();
1284  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1285  CurContext = Ancestor->getEntity();
1286
1287  // We don't need to do anything with the scope, which is going to
1288  // disappear.
1289}
1290
1291void Sema::ActOnReenterFunctionContext(ScopeSDecl *D) {
1292  // We assume that the caller has already called
1293  // ActOnReenterTemplateScope so getTemplatedDecl() works.
1294  FunctionDecl *FD = D->getAsFunction();
1295  if (!FD)
1296    return;
1297
1298  // Same implementation as PushDeclContext, but enters the context
1299  // from the lexical parent, rather than the top-level class.
1300   (0) . __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 1301, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(CurContext == FD->getLexicalParent() &&
1301 (0) . __assert_fail ("CurContext == FD->getLexicalParent() && \"The next DeclContext should be lexically contained in the current one.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 1301, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">    "The next DeclContext should be lexically contained in the current one.");
1302  CurContext = FD;
1303  S->setEntity(CurContext);
1304
1305  for (unsigned P = 0NumParams = FD->getNumParams(); P < NumParams; ++P) {
1306    ParmVarDecl *Param = FD->getParamDecl(P);
1307    // If the parameter has an identifier, then add it to the scope
1308    if (Param->getIdentifier()) {
1309      S->AddDecl(Param);
1310      IdResolver.AddDecl(Param);
1311    }
1312  }
1313}
1314
1315void Sema::ActOnExitFunctionContext() {
1316  // Same implementation as PopDeclContext, but returns to the lexical parent,
1317  // rather than the top-level class.
1318   (0) . __assert_fail ("CurContext && \"DeclContext imbalance!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 1318, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(CurContext && "DeclContext imbalance!");
1319  CurContext = CurContext->getLexicalParent();
1320   (0) . __assert_fail ("CurContext && \"Popped translation unit!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 1320, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(CurContext && "Popped translation unit!");
1321}
1322
1323/// Determine whether we allow overloading of the function
1324/// PrevDecl with another declaration.
1325///
1326/// This routine determines whether overloading is possible, not
1327/// whether some new function is actually an overload. It will return
1328/// true in C++ (where we can always provide overloads) or, as an
1329/// extension, in C when the previous function is already an
1330/// overloaded function declaration or has the "overloadable"
1331/// attribute.
1332static bool AllowOverloadingOfFunction(LookupResult &Previous,
1333                                       ASTContext &Context,
1334                                       const FunctionDecl *New) {
1335  if (Context.getLangOpts().CPlusPlus)
1336    return true;
1337
1338  if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1339    return true;
1340
1341  return Previous.getResultKind() == LookupResult::Found &&
1342         (Previous.getFoundDecl()->hasAttr<OverloadableAttr>() ||
1343          New->hasAttr<OverloadableAttr>());
1344}
1345
1346/// Add this decl to the scope shadowed decl chains.
1347void Sema::PushOnScopeChains(NamedDecl *DScope *Sbool AddToContext) {
1348  // Move up the scope chain until we find the nearest enclosing
1349  // non-transparent context. The declaration will be introduced into this
1350  // scope.
1351  while (S->getEntity() && S->getEntity()->isTransparentContext())
1352    S = S->getParent();
1353
1354  // Add scoped declarations into their context, so that they can be
1355  // found later. Declarations without a context won't be inserted
1356  // into any context.
1357  if (AddToContext)
1358    CurContext->addDecl(D);
1359
1360  // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1361  // are function-local declarations.
1362  if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1363      !D->getDeclContext()->getRedeclContext()->Equals(
1364        D->getLexicalDeclContext()->getRedeclContext()) &&
1365      !D->getLexicalDeclContext()->isFunctionOrMethod())
1366    return;
1367
1368  // Template instantiations should also not be pushed into scope.
1369  if (isa<FunctionDecl>(D) &&
1370      cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1371    return;
1372
1373  // If this replaces anything in the current scope,
1374  IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1375                               IEnd = IdResolver.end();
1376  for (; I != IEnd; ++I) {
1377    if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1378      S->RemoveDecl(*I);
1379      IdResolver.RemoveDecl(*I);
1380
1381      // Should only need to replace one decl.
1382      break;
1383    }
1384  }
1385
1386  S->AddDecl(D);
1387
1388  if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1389    // Implicitly-generated labels may end up getting generated in an order that
1390    // isn't strictly lexical, which breaks name lookup. Be careful to insert
1391    // the label at the appropriate place in the identifier chain.
1392    for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1393      DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1394      if (IDC == CurContext) {
1395        if (!S->isDeclScope(*I))
1396          continue;
1397      } else if (IDC->Encloses(CurContext))
1398        break;
1399    }
1400
1401    IdResolver.InsertDeclAfter(ID);
1402  } else {
1403    IdResolver.AddDecl(D);
1404  }
1405}
1406
1407void Sema::pushExternalDeclIntoScope(NamedDecl *DDeclarationName Name) {
1408  if (IdResolver.tryAddTopLevelDecl(DName) && TUScope)
1409    TUScope->AddDecl(D);
1410}
1411
1412bool Sema::isDeclInScope(NamedDecl *DDeclContext *CtxScope *S,
1413                         bool AllowInlineNamespace) {
1414  return IdResolver.isDeclInScope(DCtxSAllowInlineNamespace);
1415}
1416
1417Scope *Sema::getScopeForDeclContext(Scope *SDeclContext *DC) {
1418  DeclContext *TargetDC = DC->getPrimaryContext();
1419  do {
1420    if (DeclContext *ScopeDC = S->getEntity())
1421      if (ScopeDC->getPrimaryContext() == TargetDC)
1422        return S;
1423  } while ((S = S->getParent()));
1424
1425  return nullptr;
1426}
1427
1428static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1429                                            DeclContext*,
1430                                            ASTContext&);
1431
1432/// Filters out lookup results that don't fall within the given scope
1433/// as determined by isDeclInScope.
1434void Sema::FilterLookupForScope(LookupResult &RDeclContext *CtxScope *S,
1435                                bool ConsiderLinkage,
1436                                bool AllowInlineNamespace) {
1437  LookupResult::Filter F = R.makeFilter();
1438  while (F.hasNext()) {
1439    NamedDecl *D = F.next();
1440
1441    if (isDeclInScope(DCtxSAllowInlineNamespace))
1442      continue;
1443
1444    if (ConsiderLinkage && isOutOfScopePreviousDeclaration(DCtxContext))
1445      continue;
1446
1447    F.erase();
1448  }
1449
1450  F.done();
1451}
1452
1453/// We've determined that \p New is a redeclaration of \p Old. Check that they
1454/// have compatible owning modules.
1455bool Sema::CheckRedeclarationModuleOwnership(NamedDecl *NewNamedDecl *Old) {
1456  // FIXME: The Modules TS is not clear about how friend declarations are
1457  // to be treated. It's not meaningful to have different owning modules for
1458  // linkage in redeclarations of the same entity, so for now allow the
1459  // redeclaration and change the owning modules to match.
1460  if (New->getFriendObjectKind() &&
1461      Old->getOwningModuleForLinkage() != New->getOwningModuleForLinkage()) {
1462    New->setLocalOwningModule(Old->getOwningModule());
1463    makeMergedDefinitionVisible(New);
1464    return false;
1465  }
1466
1467  Module *NewM = New->getOwningModule();
1468  Module *OldM = Old->getOwningModule();
1469  if (NewM == OldM)
1470    return false;
1471
1472  // FIXME: Check proclaimed-ownership-declarations here too.
1473  bool NewIsModuleInterface = NewM && NewM->Kind == Module::ModuleInterfaceUnit;
1474  bool OldIsModuleInterface = OldM && OldM->Kind == Module::ModuleInterfaceUnit;
1475  if (NewIsModuleInterface || OldIsModuleInterface) {
1476    // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1477    //   if a declaration of D [...] appears in the purview of a module, all
1478    //   other such declarations shall appear in the purview of the same module
1479    Diag(New->getLocation(), diag::err_mismatched_owning_module)
1480      << New
1481      << NewIsModuleInterface
1482      << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1483      << OldIsModuleInterface
1484      << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1485    Diag(Old->getLocation(), diag::note_previous_declaration);
1486    New->setInvalidDecl();
1487    return true;
1488  }
1489
1490  return false;
1491}
1492
1493static bool isUsingDecl(NamedDecl *D) {
1494  return isa<UsingShadowDecl>(D) ||
1495         isa<UnresolvedUsingTypenameDecl>(D) ||
1496         isa<UnresolvedUsingValueDecl>(D);
1497}
1498
1499/// Removes using shadow declarations from the lookup results.
1500static void RemoveUsingDecls(LookupResult &R) {
1501  LookupResult::Filter F = R.makeFilter();
1502  while (F.hasNext())
1503    if (isUsingDecl(F.next()))
1504      F.erase();
1505
1506  F.done();
1507}
1508
1509/// Check for this common pattern:
1510/// @code
1511/// class S {
1512///   S(const S&); // DO NOT IMPLEMENT
1513///   void operator=(const S&); // DO NOT IMPLEMENT
1514/// };
1515/// @endcode
1516static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1517  // FIXME: Should check for private access too but access is set after we get
1518  // the decl here.
1519  if (D->doesThisDeclarationHaveABody())
1520    return false;
1521
1522  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1523    return CD->isCopyConstructor();
1524  return D->isCopyAssignmentOperator();
1525}
1526
1527// We need this to handle
1528//
1529// typedef struct {
1530//   void *foo() { return 0; }
1531// } A;
1532//
1533// When we see foo we don't know if after the typedef we will get 'A' or '*A'
1534// for example. If 'A', foo will have external linkage. If we have '*A',
1535// foo will have no linkage. Since we can't know until we get to the end
1536// of the typedef, this function finds out if D might have non-external linkage.
1537// Callers should verify at the end of the TU if it D has external linkage or
1538// not.
1539bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1540  const DeclContext *DC = D->getDeclContext();
1541  while (!DC->isTranslationUnit()) {
1542    if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1543      if (!RD->hasNameForLinkage())
1544        return true;
1545    }
1546    DC = DC->getParent();
1547  }
1548
1549  return !D->isExternallyVisible();
1550}
1551
1552// FIXME: This needs to be refactored; some other isInMainFile users want
1553// these semantics.
1554static bool isMainFileLoc(const Sema &SSourceLocation Loc) {
1555  if (S.TUKind != TU_Complete)
1556    return false;
1557  return S.SourceMgr.isInMainFile(Loc);
1558}
1559
1560bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *Dconst {
1561  assert(D);
1562
1563  if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1564    return false;
1565
1566  // Ignore all entities declared within templates, and out-of-line definitions
1567  // of members of class templates.
1568  if (D->getDeclContext()->isDependentContext() ||
1569      D->getLexicalDeclContext()->isDependentContext())
1570    return false;
1571
1572  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1573    if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1574      return false;
1575    // A non-out-of-line declaration of a member specialization was implicitly
1576    // instantiated; it's the out-of-line declaration that we're interested in.
1577    if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1578        FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1579      return false;
1580
1581    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1582      if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1583        return false;
1584    } else {
1585      // 'static inline' functions are defined in headers; don't warn.
1586      if (FD->isInlined() && !isMainFileLoc(*thisFD->getLocation()))
1587        return false;
1588    }
1589
1590    if (FD->doesThisDeclarationHaveABody() &&
1591        Context.DeclMustBeEmitted(FD))
1592      return false;
1593  } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1594    // Constants and utility variables are defined in headers with internal
1595    // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1596    // like "inline".)
1597    if (!isMainFileLoc(*thisVD->getLocation()))
1598      return false;
1599
1600    if (Context.DeclMustBeEmitted(VD))
1601      return false;
1602
1603    if (VD->isStaticDataMember() &&
1604        VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1605      return false;
1606    if (VD->isStaticDataMember() &&
1607        VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1608        VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1609      return false;
1610
1611    if (VD->isInline() && !isMainFileLoc(*thisVD->getLocation()))
1612      return false;
1613  } else {
1614    return false;
1615  }
1616
1617  // Only warn for unused decls internal to the translation unit.
1618  // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1619  // for inline functions defined in the main source file, for instance.
1620  return mightHaveNonExternalLinkage(D);
1621}
1622
1623void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1624  if (!D)
1625    return;
1626
1627  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1628    const FunctionDecl *First = FD->getFirstDecl();
1629    if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1630      return// First should already be in the vector.
1631  }
1632
1633  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1634    const VarDecl *First = VD->getFirstDecl();
1635    if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1636      return// First should already be in the vector.
1637  }
1638
1639  if (ShouldWarnIfUnusedFileScopedDecl(D))
1640    UnusedFileScopedDecls.push_back(D);
1641}
1642
1643static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1644  if (D->isInvalidDecl())
1645    return false;
1646
1647  bool Referenced = false;
1648  if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1649    // For a decomposition declaration, warn if none of the bindings are
1650    // referenced, instead of if the variable itself is referenced (which
1651    // it is, by the bindings' expressions).
1652    for (auto *BD : DD->bindings()) {
1653      if (BD->isReferenced()) {
1654        Referenced = true;
1655        break;
1656      }
1657    }
1658  } else if (!D->getDeclName()) {
1659    return false;
1660  } else if (D->isReferenced() || D->isUsed()) {
1661    Referenced = true;
1662  }
1663
1664  if (Referenced || D->hasAttr<UnusedAttr>() ||
1665      D->hasAttr<ObjCPreciseLifetimeAttr>())
1666    return false;
1667
1668  if (isa<LabelDecl>(D))
1669    return true;
1670
1671  // Except for labels, we only care about unused decls that are local to
1672  // functions.
1673  bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1674  if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1675    // For dependent types, the diagnostic is deferred.
1676    WithinFunction =
1677        WithinFunction || (R->isLocalClass() && !R->isDependentType());
1678  if (!WithinFunction)
1679    return false;
1680
1681  if (isa<TypedefNameDecl>(D))
1682    return true;
1683
1684  // White-list anything that isn't a local variable.
1685  if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1686    return false;
1687
1688  // Types of valid local variables should be complete, so this should succeed.
1689  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1690
1691    // White-list anything with an __attribute__((unused)) type.
1692    const auto *Ty = VD->getType().getTypePtr();
1693
1694    // Only look at the outermost level of typedef.
1695    if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1696      if (TT->getDecl()->hasAttr<UnusedAttr>())
1697        return false;
1698    }
1699
1700    // If we failed to complete the type for some reason, or if the type is
1701    // dependent, don't diagnose the variable.
1702    if (Ty->isIncompleteType() || Ty->isDependentType())
1703      return false;
1704
1705    // Look at the element type to ensure that the warning behaviour is
1706    // consistent for both scalars and arrays.
1707    Ty = Ty->getBaseElementTypeUnsafe();
1708
1709    if (const TagType *TT = Ty->getAs<TagType>()) {
1710      const TagDecl *Tag = TT->getDecl();
1711      if (Tag->hasAttr<UnusedAttr>())
1712        return false;
1713
1714      if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1715        if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1716          return false;
1717
1718        if (const Expr *Init = VD->getInit()) {
1719          if (const ExprWithCleanups *Cleanups =
1720                  dyn_cast<ExprWithCleanups>(Init))
1721            Init = Cleanups->getSubExpr();
1722          const CXXConstructExpr *Construct =
1723            dyn_cast<CXXConstructExpr>(Init);
1724          if (Construct && !Construct->isElidable()) {
1725            CXXConstructorDecl *CD = Construct->getConstructor();
1726            if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1727                (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1728              return false;
1729          }
1730        }
1731      }
1732    }
1733
1734    // TODO: __attribute__((unused)) templates?
1735  }
1736
1737  return true;
1738}
1739
1740static void GenerateFixForUnusedDecl(const NamedDecl *DASTContext &Ctx,
1741                                     FixItHint &Hint) {
1742  if (isa<LabelDecl>(D)) {
1743    SourceLocation AfterColon = Lexer::findLocationAfterToken(
1744        D->getEndLoc(), tok::colonCtx.getSourceManager(), Ctx.getLangOpts(),
1745        true);
1746    if (AfterColon.isInvalid())
1747      return;
1748    Hint = FixItHint::CreateRemoval(
1749        CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1750  }
1751}
1752
1753void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1754  if (D->getTypeForDecl()->isDependentType())
1755    return;
1756
1757  for (auto *TmpD : D->decls()) {
1758    if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1759      DiagnoseUnusedDecl(T);
1760    else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1761      DiagnoseUnusedNestedTypedefs(R);
1762  }
1763}
1764
1765/// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1766/// unless they are marked attr(unused).
1767void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1768  if (!ShouldDiagnoseUnusedDecl(D))
1769    return;
1770
1771  if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1772    // typedefs can be referenced later on, so the diagnostics are emitted
1773    // at end-of-translation-unit.
1774    UnusedLocalTypedefNameCandidates.insert(TD);
1775    return;
1776  }
1777
1778  FixItHint Hint;
1779  GenerateFixForUnusedDecl(DContextHint);
1780
1781  unsigned DiagID;
1782  if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1783    DiagID = diag::warn_unused_exception_param;
1784  else if (isa<LabelDecl>(D))
1785    DiagID = diag::warn_unused_label;
1786  else
1787    DiagID = diag::warn_unused_variable;
1788
1789  Diag(D->getLocation(), DiagID) << D << Hint;
1790}
1791
1792static void CheckPoppedLabel(LabelDecl *LSema &S) {
1793  // Verify that we have no forward references left.  If so, there was a goto
1794  // or address of a label taken, but no definition of it.  Label fwd
1795  // definitions are indicated with a null substmt which is also not a resolved
1796  // MS inline assembly label name.
1797  bool Diagnose = false;
1798  if (L->isMSAsmLabel())
1799    Diagnose = !L->isResolvedMSAsmLabel();
1800  else
1801    Diagnose = L->getStmt() == nullptr;
1802  if (Diagnose)
1803    S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1804}
1805
1806void Sema::ActOnPopScope(SourceLocation LocScope *S) {
1807  S->mergeNRVOIntoParent();
1808
1809  if (S->decl_empty()) return;
1810   (0) . __assert_fail ("(S->getFlags() & (Scope..DeclScope | Scope..TemplateParamScope)) && \"Scope shouldn't contain decls!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 1811, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1811 (0) . __assert_fail ("(S->getFlags() & (Scope..DeclScope | Scope..TemplateParamScope)) && \"Scope shouldn't contain decls!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 1811, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "Scope shouldn't contain decls!");
1812
1813  for (auto *TmpD : S->decls()) {
1814     (0) . __assert_fail ("TmpD && \"This decl didn't get pushed??\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 1814, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(TmpD && "This decl didn't get pushed??");
1815
1816     (0) . __assert_fail ("isa(TmpD) && \"Decl isn't NamedDecl?\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 1816, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1817    NamedDecl *D = cast<NamedDecl>(TmpD);
1818
1819    // Diagnose unused variables in this scope.
1820    if (!S->hasUnrecoverableErrorOccurred()) {
1821      DiagnoseUnusedDecl(D);
1822      if (const auto *RD = dyn_cast<RecordDecl>(D))
1823        DiagnoseUnusedNestedTypedefs(RD);
1824    }
1825
1826    if (!D->getDeclName()) continue;
1827
1828    // If this was a forward reference to a label, verify it was defined.
1829    if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1830      CheckPoppedLabel(LD, *this);
1831
1832    // Remove this name from our lexical scope, and warn on it if we haven't
1833    // already.
1834    IdResolver.RemoveDecl(D);
1835    auto ShadowI = ShadowingDecls.find(D);
1836    if (ShadowI != ShadowingDecls.end()) {
1837      if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1838        Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1839            << D << FD << FD->getParent();
1840        Diag(FD->getLocation(), diag::note_previous_declaration);
1841      }
1842      ShadowingDecls.erase(ShadowI);
1843    }
1844  }
1845}
1846
1847/// Look for an Objective-C class in the translation unit.
1848///
1849/// \param Id The name of the Objective-C class we're looking for. If
1850/// typo-correction fixes this name, the Id will be updated
1851/// to the fixed name.
1852///
1853/// \param IdLoc The location of the name in the translation unit.
1854///
1855/// \param DoTypoCorrection If true, this routine will attempt typo correction
1856/// if there is no class with the given name.
1857///
1858/// \returns The declaration of the named Objective-C class, or NULL if the
1859/// class could not be found.
1860ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1861                                              SourceLocation IdLoc,
1862                                              bool DoTypoCorrection) {
1863  // The third "scope" argument is 0 since we aren't enabling lazy built-in
1864  // creation from this context.
1865  NamedDecl *IDecl = LookupSingleName(TUScopeIdIdLocLookupOrdinaryName);
1866
1867  if (!IDecl && DoTypoCorrection) {
1868    // Perform typo correction at the given location, but only if we
1869    // find an Objective-C class name.
1870    DeclFilterCCC<ObjCInterfaceDeclCCC{};
1871    if (TypoCorrection C =
1872            CorrectTypo(DeclarationNameInfo(IdIdLoc), LookupOrdinaryName,
1873                        TUScopenullptrCCCCTK_ErrorRecovery)) {
1874      diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1875      IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1876      Id = IDecl->getIdentifier();
1877    }
1878  }
1879  ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1880  // This routine must always return a class definition, if any.
1881  if (Def && Def->getDefinition())
1882      Def = Def->getDefinition();
1883  return Def;
1884}
1885
1886/// getNonFieldDeclScope - Retrieves the innermost scope, starting
1887/// from S, where a non-field would be declared. This routine copes
1888/// with the difference between C and C++ scoping rules in structs and
1889/// unions. For example, the following code is well-formed in C but
1890/// ill-formed in C++:
1891/// @code
1892/// struct S6 {
1893///   enum { BAR } e;
1894/// };
1895///
1896/// void test_S6() {
1897///   struct S6 a;
1898///   a.e = BAR;
1899/// }
1900/// @endcode
1901/// For the declaration of BAR, this routine will return a different
1902/// scope. The scope S will be the scope of the unnamed enumeration
1903/// within S6. In C++, this routine will return the scope associated
1904/// with S6, because the enumeration's scope is a transparent
1905/// context but structures can contain non-field names. In C, this
1906/// routine will return the translation unit scope, since the
1907/// enumeration's scope is a transparent context and structures cannot
1908/// contain non-field names.
1909Scope *Sema::getNonFieldDeclScope(Scope *S) {
1910  while (((S->getFlags() & Scope::DeclScope) == 0) ||
1911         (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1912         (S->isClassScope() && !getLangOpts().CPlusPlus))
1913    S = S->getParent();
1914  return S;
1915}
1916
1917/// Looks up the declaration of "struct objc_super" and
1918/// saves it for later use in building builtin declaration of
1919/// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1920/// pre-existing declaration exists no action takes place.
1921static void LookupPredefedObjCSuperType(Sema &ThisSemaScope *S,
1922                                        IdentifierInfo *II) {
1923  if (!II->isStr("objc_msgSendSuper"))
1924    return;
1925  ASTContext &Context = ThisSema.Context;
1926
1927  LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1928                      SourceLocation(), Sema::LookupTagName);
1929  ThisSema.LookupName(ResultS);
1930  if (Result.getResultKind() == LookupResult::Found)
1931    if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1932      Context.setObjCSuperType(Context.getTagDeclType(TD));
1933}
1934
1935static StringRef getHeaderName(Builtin::Context &BuiltinInfounsigned ID,
1936                               ASTContext::GetBuiltinTypeError Error) {
1937  switch (Error) {
1938  case ASTContext::GE_None:
1939    return "";
1940  case ASTContext::GE_Missing_type:
1941    return BuiltinInfo.getHeaderName(ID);
1942  case ASTContext::GE_Missing_stdio:
1943    return "stdio.h";
1944  case ASTContext::GE_Missing_setjmp:
1945    return "setjmp.h";
1946  case ASTContext::GE_Missing_ucontext:
1947    return "ucontext.h";
1948  }
1949  llvm_unreachable("unhandled error kind");
1950}
1951
1952/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1953/// file scope.  lazily create a decl for it. ForRedeclaration is true
1954/// if we're creating this built-in in anticipation of redeclaring the
1955/// built-in.
1956NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *IIunsigned ID,
1957                                     Scope *Sbool ForRedeclaration,
1958                                     SourceLocation Loc) {
1959  LookupPredefedObjCSuperType(*thisSII);
1960
1961  ASTContext::GetBuiltinTypeError Error;
1962  QualType R = Context.GetBuiltinType(IDError);
1963  if (Error) {
1964    if (ForRedeclaration)
1965      Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1966          << getHeaderName(Context.BuiltinInfo, ID, Error)
1967          << Context.BuiltinInfo.getName(ID);
1968    return nullptr;
1969  }
1970
1971  if (!ForRedeclaration &&
1972      (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1973       Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1974    Diag(Loc, diag::ext_implicit_lib_function_decl)
1975        << Context.BuiltinInfo.getName(ID) << R;
1976    if (Context.BuiltinInfo.getHeaderName(ID) &&
1977        !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1978      Diag(Loc, diag::note_include_header_or_declare)
1979          << Context.BuiltinInfo.getHeaderName(ID)
1980          << Context.BuiltinInfo.getName(ID);
1981  }
1982
1983  if (R.isNull())
1984    return nullptr;
1985
1986  DeclContext *Parent = Context.getTranslationUnitDecl();
1987  if (getLangOpts().CPlusPlus) {
1988    LinkageSpecDecl *CLinkageDecl =
1989        LinkageSpecDecl::Create(ContextParentLocLoc,
1990                                LinkageSpecDecl::lang_cfalse);
1991    CLinkageDecl->setImplicit();
1992    Parent->addDecl(CLinkageDecl);
1993    Parent = CLinkageDecl;
1994  }
1995
1996  FunctionDecl *New = FunctionDecl::Create(Context,
1997                                           Parent,
1998                                           LocLocIIR/*TInfo=*/nullptr,
1999                                           SC_Extern,
2000                                           false,
2001                                           R->isFunctionProtoType());
2002  New->setImplicit();
2003
2004  // Create Decl objects for each parameter, adding them to the
2005  // FunctionDecl.
2006  if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
2007    SmallVector<ParmVarDecl*, 16Params;
2008    for (unsigned i = 0e = FT->getNumParams(); i != e; ++i) {
2009      ParmVarDecl *parm =
2010          ParmVarDecl::Create(ContextNewSourceLocation(), SourceLocation(),
2011                              nullptrFT->getParamType(i), /*TInfo=*/nullptr,
2012                              SC_Nonenullptr);
2013      parm->setScopeInfo(0i);
2014      Params.push_back(parm);
2015    }
2016    New->setParams(Params);
2017  }
2018
2019  AddKnownFunctionAttributes(New);
2020  RegisterLocallyScopedExternCDecl(NewS);
2021
2022  // TUScope is the translation-unit scope to insert this function into.
2023  // FIXME: This is hideous. We need to teach PushOnScopeChains to
2024  // relate Scopes to DeclContexts, and probably eliminate CurContext
2025  // entirely, but we're not there yet.
2026  DeclContext *SavedContext = CurContext;
2027  CurContext = Parent;
2028  PushOnScopeChains(NewTUScope);
2029  CurContext = SavedContext;
2030  return New;
2031}
2032
2033/// Typedef declarations don't have linkage, but they still denote the same
2034/// entity if their types are the same.
2035/// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2036/// isSameEntity.
2037static void filterNonConflictingPreviousTypedefDecls(Sema &S,
2038                                                     TypedefNameDecl *Decl,
2039                                                     LookupResult &Previous) {
2040  // This is only interesting when modules are enabled.
2041  if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2042    return;
2043
2044  // Empty sets are uninteresting.
2045  if (Previous.empty())
2046    return;
2047
2048  LookupResult::Filter Filter = Previous.makeFilter();
2049  while (Filter.hasNext()) {
2050    NamedDecl *Old = Filter.next();
2051
2052    // Non-hidden declarations are never ignored.
2053    if (S.isVisible(Old))
2054      continue;
2055
2056    // Declarations of the same entity are not ignored, even if they have
2057    // different linkages.
2058    if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2059      if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2060                                Decl->getUnderlyingType()))
2061        continue;
2062
2063      // If both declarations give a tag declaration a typedef name for linkage
2064      // purposes, then they declare the same entity.
2065      if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2066          Decl->getAnonDeclWithTypedefName())
2067        continue;
2068    }
2069
2070    Filter.erase();
2071  }
2072
2073  Filter.done();
2074}
2075
2076bool Sema::isIncompatibleTypedef(TypeDecl *OldTypedefNameDecl *New) {
2077  QualType OldType;
2078  if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2079    OldType = OldTypedef->getUnderlyingType();
2080  else
2081    OldType = Context.getTypeDeclType(Old);
2082  QualType NewType = New->getUnderlyingType();
2083
2084  if (NewType->isVariablyModifiedType()) {
2085    // Must not redefine a typedef with a variably-modified type.
2086    int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2087    Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2088      << Kind << NewType;
2089    if (Old->getLocation().isValid())
2090      notePreviousDefinition(OldNew->getLocation());
2091    New->setInvalidDecl();
2092    return true;
2093  }
2094
2095  if (OldType != NewType &&
2096      !OldType->isDependentType() &&
2097      !NewType->isDependentType() &&
2098      !Context.hasSameType(OldTypeNewType)) {
2099    int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2100    Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2101      << Kind << NewType << OldType;
2102    if (Old->getLocation().isValid())
2103      notePreviousDefinition(OldNew->getLocation());
2104    New->setInvalidDecl();
2105    return true;
2106  }
2107  return false;
2108}
2109
2110/// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2111/// same name and scope as a previous declaration 'Old'.  Figure out
2112/// how to resolve this situation, merging decls or emitting
2113/// diagnostics as appropriate. If there was an error, set New to be invalid.
2114///
2115void Sema::MergeTypedefNameDecl(Scope *STypedefNameDecl *New,
2116                                LookupResult &OldDecls) {
2117  // If the new decl is known invalid already, don't bother doing any
2118  // merging checks.
2119  if (New->isInvalidDecl()) return;
2120
2121  // Allow multiple definitions for ObjC built-in typedefs.
2122  // FIXME: Verify the underlying types are equivalent!
2123  if (getLangOpts().ObjC) {
2124    const IdentifierInfo *TypeID = New->getIdentifier();
2125    switch (TypeID->getLength()) {
2126    defaultbreak;
2127    case 2:
2128      {
2129        if (!TypeID->isStr("id"))
2130          break;
2131        QualType T = New->getUnderlyingType();
2132        if (!T->isPointerType())
2133          break;
2134        if (!T->isVoidPointerType()) {
2135          QualType PT = T->getAs<PointerType>()->getPointeeType();
2136          if (!PT->isStructureType())
2137            break;
2138        }
2139        Context.setObjCIdRedefinitionType(T);
2140        // Install the built-in type for 'id', ignoring the current definition.
2141        New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2142        return;
2143      }
2144    case 5:
2145      if (!TypeID->isStr("Class"))
2146        break;
2147      Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2148      // Install the built-in type for 'Class', ignoring the current definition.
2149      New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2150      return;
2151    case 3:
2152      if (!TypeID->isStr("SEL"))
2153        break;
2154      Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2155      // Install the built-in type for 'SEL', ignoring the current definition.
2156      New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2157      return;
2158    }
2159    // Fall through - the typedef name was not a builtin type.
2160  }
2161
2162  // Verify the old decl was also a type.
2163  TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2164  if (!Old) {
2165    Diag(New->getLocation(), diag::err_redefinition_different_kind)
2166      << New->getDeclName();
2167
2168    NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2169    if (OldD->getLocation().isValid())
2170      notePreviousDefinition(OldDNew->getLocation());
2171
2172    return New->setInvalidDecl();
2173  }
2174
2175  // If the old declaration is invalid, just give up here.
2176  if (Old->isInvalidDecl())
2177    return New->setInvalidDecl();
2178
2179  if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2180    auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2181    auto *NewTag = New->getAnonDeclWithTypedefName();
2182    NamedDecl *Hidden = nullptr;
2183    if (OldTag && NewTag &&
2184        OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2185        !hasVisibleDefinition(OldTag, &Hidden)) {
2186      // There is a definition of this tag, but it is not visible. Use it
2187      // instead of our tag.
2188      New->setTypeForDecl(OldTD->getTypeForDecl());
2189      if (OldTD->isModed())
2190        New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2191                                    OldTD->getUnderlyingType());
2192      else
2193        New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2194
2195      // Make the old tag definition visible.
2196      makeMergedDefinitionVisible(Hidden);
2197
2198      // If this was an unscoped enumeration, yank all of its enumerators
2199      // out of the scope.
2200      if (isa<EnumDecl>(NewTag)) {
2201        Scope *EnumScope = getNonFieldDeclScope(S);
2202        for (auto *D : NewTag->decls()) {
2203          auto *ED = cast<EnumConstantDecl>(D);
2204          isDeclScope(ED)", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 2204, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(EnumScope->isDeclScope(ED));
2205          EnumScope->RemoveDecl(ED);
2206          IdResolver.RemoveDecl(ED);
2207          ED->getLexicalDeclContext()->removeDecl(ED);
2208        }
2209      }
2210    }
2211  }
2212
2213  // If the typedef types are not identical, reject them in all languages and
2214  // with any extensions enabled.
2215  if (isIncompatibleTypedef(OldNew))
2216    return;
2217
2218  // The types match.  Link up the redeclaration chain and merge attributes if
2219  // the old declaration was a typedef.
2220  if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2221    New->setPreviousDecl(Typedef);
2222    mergeDeclAttributes(NewOld);
2223  }
2224
2225  if (getLangOpts().MicrosoftExt)
2226    return;
2227
2228  if (getLangOpts().CPlusPlus) {
2229    // C++ [dcl.typedef]p2:
2230    //   In a given non-class scope, a typedef specifier can be used to
2231    //   redefine the name of any type declared in that scope to refer
2232    //   to the type to which it already refers.
2233    if (!isa<CXXRecordDecl>(CurContext))
2234      return;
2235
2236    // C++0x [dcl.typedef]p4:
2237    //   In a given class scope, a typedef specifier can be used to redefine
2238    //   any class-name declared in that scope that is not also a typedef-name
2239    //   to refer to the type to which it already refers.
2240    //
2241    // This wording came in via DR424, which was a correction to the
2242    // wording in DR56, which accidentally banned code like:
2243    //
2244    //   struct S {
2245    //     typedef struct A { } A;
2246    //   };
2247    //
2248    // in the C++03 standard. We implement the C++0x semantics, which
2249    // allow the above but disallow
2250    //
2251    //   struct S {
2252    //     typedef int I;
2253    //     typedef int I;
2254    //   };
2255    //
2256    // since that was the intent of DR56.
2257    if (!isa<TypedefNameDecl>(Old))
2258      return;
2259
2260    Diag(New->getLocation(), diag::err_redefinition)
2261      << New->getDeclName();
2262    notePreviousDefinition(OldNew->getLocation());
2263    return New->setInvalidDecl();
2264  }
2265
2266  // Modules always permit redefinition of typedefs, as does C11.
2267  if (getLangOpts().Modules || getLangOpts().C11)
2268    return;
2269
2270  // If we have a redefinition of a typedef in C, emit a warning.  This warning
2271  // is normally mapped to an error, but can be controlled with
2272  // -Wtypedef-redefinition.  If either the original or the redefinition is
2273  // in a system header, don't emit this for compatibility with GCC.
2274  if (getDiagnostics().getSuppressSystemWarnings() &&
2275      // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2276      (Old->isImplicit() ||
2277       Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2278       Context.getSourceManager().isInSystemHeader(New->getLocation())))
2279    return;
2280
2281  Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2282    << New->getDeclName();
2283  notePreviousDefinition(OldNew->getLocation());
2284}
2285
2286/// DeclhasAttr - returns true if decl Declaration already has the target
2287/// attribute.
2288static bool DeclHasAttr(const Decl *Dconst Attr *A) {
2289  const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2290  const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2291  for (const auto *i : D->attrs())
2292    if (i->getKind() == A->getKind()) {
2293      if (Ann) {
2294        if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2295          return true;
2296        continue;
2297      }
2298      // FIXME: Don't hardcode this check
2299      if (OA && isa<OwnershipAttr>(i))
2300        return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2301      return true;
2302    }
2303
2304  return false;
2305}
2306
2307static bool isAttributeTargetADefinition(Decl *D) {
2308  if (VarDecl *VD = dyn_cast<VarDecl>(D))
2309    return VD->isThisDeclarationADefinition();
2310  if (TagDecl *TD = dyn_cast<TagDecl>(D))
2311    return TD->isCompleteDefinition() || TD->isBeingDefined();
2312  return true;
2313}
2314
2315/// Merge alignment attributes from \p Old to \p New, taking into account the
2316/// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2317///
2318/// \return \c true if any attributes were added to \p New.
2319static bool mergeAlignedAttrs(Sema &SNamedDecl *NewDecl *Old) {
2320  // Look for alignas attributes on Old, and pick out whichever attribute
2321  // specifies the strictest alignment requirement.
2322  AlignedAttr *OldAlignasAttr = nullptr;
2323  AlignedAttr *OldStrictestAlignAttr = nullptr;
2324  unsigned OldAlign = 0;
2325  for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2326    // FIXME: We have no way of representing inherited dependent alignments
2327    // in a case like:
2328    //   template<int A, int B> struct alignas(A) X;
2329    //   template<int A, int B> struct alignas(B) X {};
2330    // For now, we just ignore any alignas attributes which are not on the
2331    // definition in such a case.
2332    if (I->isAlignmentDependent())
2333      return false;
2334
2335    if (I->isAlignas())
2336      OldAlignasAttr = I;
2337
2338    unsigned Align = I->getAlignment(S.Context);
2339    if (Align > OldAlign) {
2340      OldAlign = Align;
2341      OldStrictestAlignAttr = I;
2342    }
2343  }
2344
2345  // Look for alignas attributes on New.
2346  AlignedAttr *NewAlignasAttr = nullptr;
2347  unsigned NewAlign = 0;
2348  for (auto *I : New->specific_attrs<AlignedAttr>()) {
2349    if (I->isAlignmentDependent())
2350      return false;
2351
2352    if (I->isAlignas())
2353      NewAlignasAttr = I;
2354
2355    unsigned Align = I->getAlignment(S.Context);
2356    if (Align > NewAlign)
2357      NewAlign = Align;
2358  }
2359
2360  if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2361    // Both declarations have 'alignas' attributes. We require them to match.
2362    // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2363    // fall short. (If two declarations both have alignas, they must both match
2364    // every definition, and so must match each other if there is a definition.)
2365
2366    // If either declaration only contains 'alignas(0)' specifiers, then it
2367    // specifies the natural alignment for the type.
2368    if (OldAlign == 0 || NewAlign == 0) {
2369      QualType Ty;
2370      if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2371        Ty = VD->getType();
2372      else
2373        Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2374
2375      if (OldAlign == 0)
2376        OldAlign = S.Context.getTypeAlign(Ty);
2377      if (NewAlign == 0)
2378        NewAlign = S.Context.getTypeAlign(Ty);
2379    }
2380
2381    if (OldAlign != NewAlign) {
2382      S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2383        << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2384        << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2385      S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2386    }
2387  }
2388
2389  if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2390    // C++11 [dcl.align]p6:
2391    //   if any declaration of an entity has an alignment-specifier,
2392    //   every defining declaration of that entity shall specify an
2393    //   equivalent alignment.
2394    // C11 6.7.5/7:
2395    //   If the definition of an object does not have an alignment
2396    //   specifier, any other declaration of that object shall also
2397    //   have no alignment specifier.
2398    S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2399      << OldAlignasAttr;
2400    S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2401      << OldAlignasAttr;
2402  }
2403
2404  bool AnyAdded = false;
2405
2406  // Ensure we have an attribute representing the strictest alignment.
2407  if (OldAlign > NewAlign) {
2408    AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2409    Clone->setInherited(true);
2410    New->addAttr(Clone);
2411    AnyAdded = true;
2412  }
2413
2414  // Ensure we have an alignas attribute if the old declaration had one.
2415  if (OldAlignasAttr && !NewAlignasAttr &&
2416      !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2417    AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2418    Clone->setInherited(true);
2419    New->addAttr(Clone);
2420    AnyAdded = true;
2421  }
2422
2423  return AnyAdded;
2424}
2425
2426static bool mergeDeclAttribute(Sema &SNamedDecl *D,
2427                               const InheritableAttr *Attr,
2428                               Sema::AvailabilityMergeKind AMK) {
2429  // This function copies an attribute Attr from a previous declaration to the
2430  // new declaration D if the new declaration doesn't itself have that attribute
2431  // yet or if that attribute allows duplicates.
2432  // If you're adding a new attribute that requires logic different from
2433  // "use explicit attribute on decl if present, else use attribute from
2434  // previous decl", for example if the attribute needs to be consistent
2435  // between redeclarations, you need to call a custom merge function here.
2436  InheritableAttr *NewAttr = nullptr;
2437  unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2438  if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2439    NewAttr = S.mergeAvailabilityAttr(
2440        D, AA->getRange(), AA->getPlatform(), AA->isImplicit(),
2441        AA->getIntroduced(), AA->getDeprecated(), AA->getObsoleted(),
2442        AA->getUnavailable(), AA->getMessage(), AA->getStrict(),
2443        AA->getReplacement(), AMK, AA->getPriority(), AttrSpellingListIndex);
2444  else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2445    NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2446                                    AttrSpellingListIndex);
2447  else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2448    NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2449                                        AttrSpellingListIndex);
2450  else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2451    NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2452                                   AttrSpellingListIndex);
2453  else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2454    NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2455                                   AttrSpellingListIndex);
2456  else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2457    NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2458                                FA->getFormatIdx(), FA->getFirstArg(),
2459                                AttrSpellingListIndex);
2460  else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2461    NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2462                                 AttrSpellingListIndex);
2463  else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2464    NewAttr = S.mergeCodeSegAttr(D, CSA->getRange(), CSA->getName(),
2465                                 AttrSpellingListIndex);
2466  else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2467    NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2468                                       AttrSpellingListIndex,
2469                                       IA->getSemanticSpelling());
2470  else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2471    NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2472                                      &S.Context.Idents.get(AA->getSpelling()),
2473                                      AttrSpellingListIndex);
2474  else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2475           (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2476            isa<CUDAGlobalAttr>(Attr))) {
2477    // CUDA target attributes are part of function signature for
2478    // overloading purposes and must not be merged.
2479    return false;
2480  } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2481    NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2482  else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2483    NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2484  else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2485    NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2486  else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2487    NewAttr = S.mergeCommonAttr(D, *CommonA);
2488  else if (isa<AlignedAttr>(Attr))
2489    // AlignedAttrs are handled separately, because we need to handle all
2490    // such attributes on a declaration at the same time.
2491    NewAttr = nullptr;
2492  else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2493           (AMK == Sema::AMK_Override ||
2494            AMK == Sema::AMK_ProtocolImplementation))
2495    NewAttr = nullptr;
2496  else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2497    NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2498                              UA->getGuid());
2499  else if (const auto *SLHA = dyn_cast<SpeculativeLoadHardeningAttr>(Attr))
2500    NewAttr = S.mergeSpeculativeLoadHardeningAttr(D, *SLHA);
2501  else if (const auto *SLHA = dyn_cast<NoSpeculativeLoadHardeningAttr>(Attr))
2502    NewAttr = S.mergeNoSpeculativeLoadHardeningAttr(D, *SLHA);
2503  else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(DAttr))
2504    NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2505
2506  if (NewAttr) {
2507    NewAttr->setInherited(true);
2508    D->addAttr(NewAttr);
2509    if (isa<MSInheritanceAttr>(NewAttr))
2510      S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2511    return true;
2512  }
2513
2514  return false;
2515}
2516
2517static const NamedDecl *getDefinition(const Decl *D) {
2518  if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2519    return TD->getDefinition();
2520  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2521    const VarDecl *Def = VD->getDefinition();
2522    if (Def)
2523      return Def;
2524    return VD->getActingDefinition();
2525  }
2526  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2527    return FD->getDefinition();
2528  return nullptr;
2529}
2530
2531static bool hasAttribute(const Decl *Dattr::Kind Kind) {
2532  for (const auto *Attribute : D->attrs())
2533    if (Attribute->getKind() == Kind)
2534      return true;
2535  return false;
2536}
2537
2538/// checkNewAttributesAfterDef - If we already have a definition, check that
2539/// there are no new attributes in this declaration.
2540static void checkNewAttributesAfterDef(Sema &SDecl *Newconst Decl *Old) {
2541  if (!New->hasAttrs())
2542    return;
2543
2544  const NamedDecl *Def = getDefinition(Old);
2545  if (!Def || Def == New)
2546    return;
2547
2548  AttrVec &NewAttributes = New->getAttrs();
2549  for (unsigned I = 0E = NewAttributes.size(); I != E;) {
2550    const Attr *NewAttribute = NewAttributes[I];
2551
2552    if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2553      if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2554        Sema::SkipBodyInfo SkipBody;
2555        S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2556
2557        // If we're skipping this definition, drop the "alias" attribute.
2558        if (SkipBody.ShouldSkip) {
2559          NewAttributes.erase(NewAttributes.begin() + I);
2560          --E;
2561          continue;
2562        }
2563      } else {
2564        VarDecl *VD = cast<VarDecl>(New);
2565        unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2566                                VarDecl::TentativeDefinition
2567                            ? diag::err_alias_after_tentative
2568                            : diag::err_redefinition;
2569        S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2570        if (Diag == diag::err_redefinition)
2571          S.notePreviousDefinition(DefVD->getLocation());
2572        else
2573          S.Diag(Def->getLocation(), diag::note_previous_definition);
2574        VD->setInvalidDecl();
2575      }
2576      ++I;
2577      continue;
2578    }
2579
2580    if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2581      // Tentative definitions are only interesting for the alias check above.
2582      if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2583        ++I;
2584        continue;
2585      }
2586    }
2587
2588    if (hasAttribute(DefNewAttribute->getKind())) {
2589      ++I;
2590      continue// regular attr merging will take care of validating this.
2591    }
2592
2593    if (isa<C11NoReturnAttr>(NewAttribute)) {
2594      // C's _Noreturn is allowed to be added to a function after it is defined.
2595      ++I;
2596      continue;
2597    } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2598      if (AA->isAlignas()) {
2599        // C++11 [dcl.align]p6:
2600        //   if any declaration of an entity has an alignment-specifier,
2601        //   every defining declaration of that entity shall specify an
2602        //   equivalent alignment.
2603        // C11 6.7.5/7:
2604        //   If the definition of an object does not have an alignment
2605        //   specifier, any other declaration of that object shall also
2606        //   have no alignment specifier.
2607        S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2608          << AA;
2609        S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2610          << AA;
2611        NewAttributes.erase(NewAttributes.begin() + I);
2612        --E;
2613        continue;
2614      }
2615    }
2616
2617    S.Diag(NewAttribute->getLocation(),
2618           diag::warn_attribute_precede_definition);
2619    S.Diag(Def->getLocation(), diag::note_previous_definition);
2620    NewAttributes.erase(NewAttributes.begin() + I);
2621    --E;
2622  }
2623}
2624
2625/// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2626void Sema::mergeDeclAttributes(NamedDecl *NewDecl *Old,
2627                               AvailabilityMergeKind AMK) {
2628  if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2629    UsedAttr *NewAttr = OldAttr->clone(Context);
2630    NewAttr->setInherited(true);
2631    New->addAttr(NewAttr);
2632  }
2633
2634  if (!Old->hasAttrs() && !New->hasAttrs())
2635    return;
2636
2637  // Attributes declared post-definition are currently ignored.
2638  checkNewAttributesAfterDef(*thisNewOld);
2639
2640  if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2641    if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2642      if (OldA->getLabel() != NewA->getLabel()) {
2643        // This redeclaration changes __asm__ label.
2644        Diag(New->getLocation(), diag::err_different_asm_label);
2645        Diag(OldA->getLocation(), diag::note_previous_declaration);
2646      }
2647    } else if (Old->isUsed()) {
2648      // This redeclaration adds an __asm__ label to a declaration that has
2649      // already been ODR-used.
2650      Diag(New->getLocation(), diag::err_late_asm_label_name)
2651        << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2652    }
2653  }
2654
2655  // Re-declaration cannot add abi_tag's.
2656  if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2657    if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2658      for (const auto &NewTag : NewAbiTagAttr->tags()) {
2659        if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2660                      NewTag) == OldAbiTagAttr->tags_end()) {
2661          Diag(NewAbiTagAttr->getLocation(),
2662               diag::err_new_abi_tag_on_redeclaration)
2663              << NewTag;
2664          Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2665        }
2666      }
2667    } else {
2668      Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2669      Diag(Old->getLocation(), diag::note_previous_declaration);
2670    }
2671  }
2672
2673  // This redeclaration adds a section attribute.
2674  if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
2675    if (auto *VD = dyn_cast<VarDecl>(New)) {
2676      if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
2677        Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
2678        Diag(Old->getLocation(), diag::note_previous_declaration);
2679      }
2680    }
2681  }
2682
2683  // Redeclaration adds code-seg attribute.
2684  const auto *NewCSA = New->getAttr<CodeSegAttr>();
2685  if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
2686      !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
2687    Diag(New->getLocation(), diag::warn_mismatched_section)
2688         << 0 /*codeseg*/;
2689    Diag(Old->getLocation(), diag::note_previous_declaration);
2690  }
2691
2692  if (!Old->hasAttrs())
2693    return;
2694
2695  bool foundAny = New->hasAttrs();
2696
2697  // Ensure that any moving of objects within the allocated map is done before
2698  // we process them.
2699  if (!foundAnyNew->setAttrs(AttrVec());
2700
2701  for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2702    // Ignore deprecated/unavailable/availability attributes if requested.
2703    AvailabilityMergeKind LocalAMK = AMK_None;
2704    if (isa<DeprecatedAttr>(I) ||
2705        isa<UnavailableAttr>(I) ||
2706        isa<AvailabilityAttr>(I)) {
2707      switch (AMK) {
2708      case AMK_None:
2709        continue;
2710
2711      case AMK_Redeclaration:
2712      case AMK_Override:
2713      case AMK_ProtocolImplementation:
2714        LocalAMK = AMK;
2715        break;
2716      }
2717    }
2718
2719    // Already handled.
2720    if (isa<UsedAttr>(I))
2721      continue;
2722
2723    if (mergeDeclAttribute(*this, New, I, LocalAMK))
2724      foundAny = true;
2725  }
2726
2727  if (mergeAlignedAttrs(*thisNewOld))
2728    foundAny = true;
2729
2730  if (!foundAnyNew->dropAttrs();
2731}
2732
2733/// mergeParamDeclAttributes - Copy attributes from the old parameter
2734/// to the new one.
2735static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2736                                     const ParmVarDecl *oldDecl,
2737                                     Sema &S) {
2738  // C++11 [dcl.attr.depend]p2:
2739  //   The first declaration of a function shall specify the
2740  //   carries_dependency attribute for its declarator-id if any declaration
2741  //   of the function specifies the carries_dependency attribute.
2742  const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2743  if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2744    S.Diag(CDA->getLocation(),
2745           diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2746    // Find the first declaration of the parameter.
2747    // FIXME: Should we build redeclaration chains for function parameters?
2748    const FunctionDecl *FirstFD =
2749      cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2750    const ParmVarDecl *FirstVD =
2751      FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2752    S.Diag(FirstVD->getLocation(),
2753           diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2754  }
2755
2756  if (!oldDecl->hasAttrs())
2757    return;
2758
2759  bool foundAny = newDecl->hasAttrs();
2760
2761  // Ensure that any moving of objects within the allocated map is
2762  // done before we process them.
2763  if (!foundAnynewDecl->setAttrs(AttrVec());
2764
2765  for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2766    if (!DeclHasAttr(newDecl, I)) {
2767      InheritableAttr *newAttr =
2768        cast<InheritableParamAttr>(I->clone(S.Context));
2769      newAttr->setInherited(true);
2770      newDecl->addAttr(newAttr);
2771      foundAny = true;
2772    }
2773  }
2774
2775  if (!foundAnynewDecl->dropAttrs();
2776}
2777
2778static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2779                                const ParmVarDecl *OldParam,
2780                                Sema &S) {
2781  if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2782    if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2783      if (*Oldnullability != *Newnullability) {
2784        S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2785          << DiagNullabilityKind(
2786               *Newnullability,
2787               ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2788                != 0))
2789          << DiagNullabilityKind(
2790               *Oldnullability,
2791               ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2792                != 0));
2793        S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2794      }
2795    } else {
2796      QualType NewT = NewParam->getType();
2797      NewT = S.Context.getAttributedType(
2798                         AttributedType::getNullabilityAttrKind(*Oldnullability),
2799                         NewT, NewT);
2800      NewParam->setType(NewT);
2801    }
2802  }
2803}
2804
2805namespace {
2806
2807/// Used in MergeFunctionDecl to keep track of function parameters in
2808/// C.
2809struct GNUCompatibleParamWarning {
2810  ParmVarDecl *OldParm;
2811  ParmVarDecl *NewParm;
2812  QualType PromotedType;
2813};
2814
2815// end anonymous namespace
2816
2817/// getSpecialMember - get the special member enum for a method.
2818Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2819  if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2820    if (Ctor->isDefaultConstructor())
2821      return Sema::CXXDefaultConstructor;
2822
2823    if (Ctor->isCopyConstructor())
2824      return Sema::CXXCopyConstructor;
2825
2826    if (Ctor->isMoveConstructor())
2827      return Sema::CXXMoveConstructor;
2828  } else if (isa<CXXDestructorDecl>(MD)) {
2829    return Sema::CXXDestructor;
2830  } else if (MD->isCopyAssignmentOperator()) {
2831    return Sema::CXXCopyAssignment;
2832  } else if (MD->isMoveAssignmentOperator()) {
2833    return Sema::CXXMoveAssignment;
2834  }
2835
2836  return Sema::CXXInvalid;
2837}
2838
2839// Determine whether the previous declaration was a definition, implicit
2840// declaration, or a declaration.
2841template <typename T>
2842static std::pair<diag::kindSourceLocation>
2843getNoteDiagForInvalidRedeclaration(const T *Oldconst T *New) {
2844  diag::kind PrevDiag;
2845  SourceLocation OldLocation = Old->getLocation();
2846  if (Old->isThisDeclarationADefinition())
2847    PrevDiag = diag::note_previous_definition;
2848  else if (Old->isImplicit()) {
2849    PrevDiag = diag::note_previous_implicit_declaration;
2850    if (OldLocation.isInvalid())
2851      OldLocation = New->getLocation();
2852  } else
2853    PrevDiag = diag::note_previous_declaration;
2854  return std::make_pair(PrevDiagOldLocation);
2855}
2856
2857/// canRedefineFunction - checks if a function can be redefined. Currently,
2858/// only extern inline functions can be redefined, and even then only in
2859/// GNU89 mode.
2860static bool canRedefineFunction(const FunctionDecl *FD,
2861                                const LangOptionsLangOpts) {
2862  return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2863          !LangOpts.CPlusPlus &&
2864          FD->isInlineSpecified() &&
2865          FD->getStorageClass() == SC_Extern);
2866}
2867
2868const AttributedType *Sema::getCallingConvAttributedType(QualType Tconst {
2869  const AttributedType *AT = T->getAs<AttributedType>();
2870  while (AT && !AT->isCallingConv())
2871    AT = AT->getModifiedType()->getAs<AttributedType>();
2872  return AT;
2873}
2874
2875template <typename T>
2876static bool haveIncompatibleLanguageLinkages(const T *Oldconst T *New) {
2877  const DeclContext *DC = Old->getDeclContext();
2878  if (DC->isRecord())
2879    return false;
2880
2881  LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2882  if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2883    return true;
2884  if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2885    return true;
2886  return false;
2887}
2888
2889template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2890static bool isExternC(VarTemplateDecl *) { return false; }
2891
2892/// Check whether a redeclaration of an entity introduced by a
2893/// using-declaration is valid, given that we know it's not an overload
2894/// (nor a hidden tag declaration).
2895template<typename ExpectedDecl>
2896static bool checkUsingShadowRedecl(Sema &SUsingShadowDecl *OldS,
2897                                   ExpectedDecl *New) {
2898  // C++11 [basic.scope.declarative]p4:
2899  //   Given a set of declarations in a single declarative region, each of
2900  //   which specifies the same unqualified name,
2901  //   -- they shall all refer to the same entity, or all refer to functions
2902  //      and function templates; or
2903  //   -- exactly one declaration shall declare a class name or enumeration
2904  //      name that is not a typedef name and the other declarations shall all
2905  //      refer to the same variable or enumerator, or all refer to functions
2906  //      and function templates; in this case the class name or enumeration
2907  //      name is hidden (3.3.10).
2908
2909  // C++11 [namespace.udecl]p14:
2910  //   If a function declaration in namespace scope or block scope has the
2911  //   same name and the same parameter-type-list as a function introduced
2912  //   by a using-declaration, and the declarations do not declare the same
2913  //   function, the program is ill-formed.
2914
2915  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2916  if (Old &&
2917      !Old->getDeclContext()->getRedeclContext()->Equals(
2918          New->getDeclContext()->getRedeclContext()) &&
2919      !(isExternC(Old) && isExternC(New)))
2920    Old = nullptr;
2921
2922  if (!Old) {
2923    S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2924    S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2925    S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2926    return true;
2927  }
2928  return false;
2929}
2930
2931static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2932                                            const FunctionDecl *B) {
2933  getNumParams() == B->getNumParams()", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 2933, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(A->getNumParams() == B->getNumParams());
2934
2935  auto AttrEq = [](const ParmVarDecl *Aconst ParmVarDecl *B) {
2936    const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2937    const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2938    if (AttrA == AttrB)
2939      return true;
2940    return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
2941           AttrA->isDynamic() == AttrB->isDynamic();
2942  };
2943
2944  return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2945}
2946
2947/// If necessary, adjust the semantic declaration context for a qualified
2948/// declaration to name the correct inline namespace within the qualifier.
2949static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD,
2950                                               DeclaratorDecl *OldD) {
2951  // The only case where we need to update the DeclContext is when
2952  // redeclaration lookup for a qualified name finds a declaration
2953  // in an inline namespace within the context named by the qualifier:
2954  //
2955  //   inline namespace N { int f(); }
2956  //   int ::f(); // Sema DC needs adjusting from :: to N::.
2957  //
2958  // For unqualified declarations, the semantic context *can* change
2959  // along the redeclaration chain (for local extern declarations,
2960  // extern "C" declarations, and friend declarations in particular).
2961  if (!NewD->getQualifier())
2962    return;
2963
2964  // NewD is probably already in the right context.
2965  auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
2966  auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
2967  if (NamedDC->Equals(SemaDC))
2968    return;
2969
2970   (0) . __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 2972, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
2971 (0) . __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 2972, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">          NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
2972 (0) . __assert_fail ("(NamedDC->InEnclosingNamespaceSetOf(SemaDC) || NewD->isInvalidDecl() || OldD->isInvalidDecl()) && \"unexpected context for redeclaration\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 2972, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "unexpected context for redeclaration");
2973
2974  auto *LexDC = NewD->getLexicalDeclContext();
2975  auto FixSemaDC = [=](NamedDecl *D) {
2976    if (!D)
2977      return;
2978    D->setDeclContext(SemaDC);
2979    D->setLexicalDeclContext(LexDC);
2980  };
2981
2982  FixSemaDC(NewD);
2983  if (auto *FD = dyn_cast<FunctionDecl>(NewD))
2984    FixSemaDC(FD->getDescribedFunctionTemplate());
2985  else if (auto *VD = dyn_cast<VarDecl>(NewD))
2986    FixSemaDC(VD->getDescribedVarTemplate());
2987}
2988
2989/// MergeFunctionDecl - We just parsed a function 'New' from
2990/// declarator D which has the same name and scope as a previous
2991/// declaration 'Old'.  Figure out how to resolve this situation,
2992/// merging decls or emitting diagnostics as appropriate.
2993///
2994/// In C++, New and Old must be declarations that are not
2995/// overloaded. Use IsOverload to determine whether New and Old are
2996/// overloaded, and to select the Old declaration that New should be
2997/// merged with.
2998///
2999/// Returns true if there was an error, false otherwise.
3000bool Sema::MergeFunctionDecl(FunctionDecl *NewNamedDecl *&OldD,
3001                             Scope *Sbool MergeTypeWithOld) {
3002  // Verify the old decl was also a function.
3003  FunctionDecl *Old = OldD->getAsFunction();
3004  if (!Old) {
3005    if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3006      if (New->getFriendObjectKind()) {
3007        Diag(New->getLocation(), diag::err_using_decl_friend);
3008        Diag(Shadow->getTargetDecl()->getLocation(),
3009             diag::note_using_decl_target);
3010        Diag(Shadow->getUsingDecl()->getLocation(),
3011             diag::note_using_decl) << 0;
3012        return true;
3013      }
3014
3015      // Check whether the two declarations might declare the same function.
3016      if (checkUsingShadowRedecl<FunctionDecl>(*thisShadowNew))
3017        return true;
3018      OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3019    } else {
3020      Diag(New->getLocation(), diag::err_redefinition_different_kind)
3021        << New->getDeclName();
3022      notePreviousDefinition(OldDNew->getLocation());
3023      return true;
3024    }
3025  }
3026
3027  // If the old declaration is invalid, just give up here.
3028  if (Old->isInvalidDecl())
3029    return true;
3030
3031  // Disallow redeclaration of some builtins.
3032  if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3033    Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3034    Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3035        << Old << Old->getType();
3036    return true;
3037  }
3038
3039  diag::kind PrevDiag;
3040  SourceLocation OldLocation;
3041  std::tie(PrevDiagOldLocation) =
3042      getNoteDiagForInvalidRedeclaration(OldNew);
3043
3044  // Don't complain about this if we're in GNU89 mode and the old function
3045  // is an extern inline function.
3046  // Don't complain about specializations. They are not supposed to have
3047  // storage classes.
3048  if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3049      New->getStorageClass() == SC_Static &&
3050      Old->hasExternalFormalLinkage() &&
3051      !New->getTemplateSpecializationInfo() &&
3052      !canRedefineFunction(Old, getLangOpts())) {
3053    if (getLangOpts().MicrosoftExt) {
3054      Diag(New->getLocation(), diag::ext_static_non_static) << New;
3055      Diag(OldLocationPrevDiag);
3056    } else {
3057      Diag(New->getLocation(), diag::err_static_non_static) << New;
3058      Diag(OldLocationPrevDiag);
3059      return true;
3060    }
3061  }
3062
3063  if (New->hasAttr<InternalLinkageAttr>() &&
3064      !Old->hasAttr<InternalLinkageAttr>()) {
3065    Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3066        << New->getDeclName();
3067    notePreviousDefinition(OldNew->getLocation());
3068    New->dropAttr<InternalLinkageAttr>();
3069  }
3070
3071  if (CheckRedeclarationModuleOwnership(NewOld))
3072    return true;
3073
3074  if (!getLangOpts().CPlusPlus) {
3075    bool OldOvl = Old->hasAttr<OverloadableAttr>();
3076    if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3077      Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3078        << New << OldOvl;
3079
3080      // Try our best to find a decl that actually has the overloadable
3081      // attribute for the note. In most cases (e.g. programs with only one
3082      // broken declaration/definition), this won't matter.
3083      //
3084      // FIXME: We could do this if we juggled some extra state in
3085      // OverloadableAttr, rather than just removing it.
3086      const Decl *DiagOld = Old;
3087      if (OldOvl) {
3088        auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3089          const auto *A = D->getAttr<OverloadableAttr>();
3090          return A && !A->isImplicit();
3091        });
3092        // If we've implicitly added *all* of the overloadable attrs to this
3093        // chain, emitting a "previous redecl" note is pointless.
3094        DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3095      }
3096
3097      if (DiagOld)
3098        Diag(DiagOld->getLocation(),
3099             diag::note_attribute_overloadable_prev_overload)
3100          << OldOvl;
3101
3102      if (OldOvl)
3103        New->addAttr(OverloadableAttr::CreateImplicit(Context));
3104      else
3105        New->dropAttr<OverloadableAttr>();
3106    }
3107  }
3108
3109  // If a function is first declared with a calling convention, but is later
3110  // declared or defined without one, all following decls assume the calling
3111  // convention of the first.
3112  //
3113  // It's OK if a function is first declared without a calling convention,
3114  // but is later declared or defined with the default calling convention.
3115  //
3116  // To test if either decl has an explicit calling convention, we look for
3117  // AttributedType sugar nodes on the type as written.  If they are missing or
3118  // were canonicalized away, we assume the calling convention was implicit.
3119  //
3120  // Note also that we DO NOT return at this point, because we still have
3121  // other tests to run.
3122  QualType OldQType = Context.getCanonicalType(Old->getType());
3123  QualType NewQType = Context.getCanonicalType(New->getType());
3124  const FunctionType *OldType = cast<FunctionType>(OldQType);
3125  const FunctionType *NewType = cast<FunctionType>(NewQType);
3126  FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3127  FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3128  bool RequiresAdjustment = false;
3129
3130  if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3131    FunctionDecl *First = Old->getFirstDecl();
3132    const FunctionType *FT =
3133        First->getType().getCanonicalType()->castAs<FunctionType>();
3134    FunctionType::ExtInfo FI = FT->getExtInfo();
3135    bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3136    if (!NewCCExplicit) {
3137      // Inherit the CC from the previous declaration if it was specified
3138      // there but not here.
3139      NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3140      RequiresAdjustment = true;
3141    } else if (New->getBuiltinID()) {
3142      // Calling Conventions on a Builtin aren't really useful and setting a
3143      // default calling convention and cdecl'ing some builtin redeclarations is
3144      // common, so warn and ignore the calling convention on the redeclaration.
3145      Diag(New->getLocation(), diag::warn_cconv_ignored)
3146          << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3147          << (int)CallingConventionIgnoredReason::BuiltinFunction;
3148      NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3149      RequiresAdjustment = true;
3150    } else {
3151      // Calling conventions aren't compatible, so complain.
3152      bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3153      Diag(New->getLocation(), diag::err_cconv_change)
3154        << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3155        << !FirstCCExplicit
3156        << (!FirstCCExplicit ? "" :
3157            FunctionType::getNameForCallConv(FI.getCC()));
3158
3159      // Put the note on the first decl, since it is the one that matters.
3160      Diag(First->getLocation(), diag::note_previous_declaration);
3161      return true;
3162    }
3163  }
3164
3165  // FIXME: diagnose the other way around?
3166  if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3167    NewTypeInfo = NewTypeInfo.withNoReturn(true);
3168    RequiresAdjustment = true;
3169  }
3170
3171  // Merge regparm attribute.
3172  if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3173      OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3174    if (NewTypeInfo.getHasRegParm()) {
3175      Diag(New->getLocation(), diag::err_regparm_mismatch)
3176        << NewType->getRegParmType()
3177        << OldType->getRegParmType();
3178      Diag(OldLocation, diag::note_previous_declaration);
3179      return true;
3180    }
3181
3182    NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3183    RequiresAdjustment = true;
3184  }
3185
3186  // Merge ns_returns_retained attribute.
3187  if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3188    if (NewTypeInfo.getProducesResult()) {
3189      Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3190          << "'ns_returns_retained'";
3191      Diag(OldLocation, diag::note_previous_declaration);
3192      return true;
3193    }
3194
3195    NewTypeInfo = NewTypeInfo.withProducesResult(true);
3196    RequiresAdjustment = true;
3197  }
3198
3199  if (OldTypeInfo.getNoCallerSavedRegs() !=
3200      NewTypeInfo.getNoCallerSavedRegs()) {
3201    if (NewTypeInfo.getNoCallerSavedRegs()) {
3202      AnyX86NoCallerSavedRegistersAttr *Attr =
3203        New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3204      Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3205      Diag(OldLocation, diag::note_previous_declaration);
3206      return true;
3207    }
3208
3209    NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3210    RequiresAdjustment = true;
3211  }
3212
3213  if (RequiresAdjustment) {
3214    const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3215    AdjustedType = Context.adjustFunctionType(AdjustedTypeNewTypeInfo);
3216    New->setType(QualType(AdjustedType0));
3217    NewQType = Context.getCanonicalType(New->getType());
3218    NewType = cast<FunctionType>(NewQType);
3219  }
3220
3221  // If this redeclaration makes the function inline, we may need to add it to
3222  // UndefinedButUsed.
3223  if (!Old->isInlined() && New->isInlined() &&
3224      !New->hasAttr<GNUInlineAttr>() &&
3225      !getLangOpts().GNUInline &&
3226      Old->isUsed(false) &&
3227      !Old->isDefined() && !New->isThisDeclarationADefinition())
3228    UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3229                                           SourceLocation()));
3230
3231  // If this redeclaration makes it newly gnu_inline, we don't want to warn
3232  // about it.
3233  if (New->hasAttr<GNUInlineAttr>() &&
3234      Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3235    UndefinedButUsed.erase(Old->getCanonicalDecl());
3236  }
3237
3238  // If pass_object_size params don't match up perfectly, this isn't a valid
3239  // redeclaration.
3240  if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3241      !hasIdenticalPassObjectSizeAttrs(OldNew)) {
3242    Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3243        << New->getDeclName();
3244    Diag(OldLocationPrevDiag) << Old << Old->getType();
3245    return true;
3246  }
3247
3248  if (getLangOpts().CPlusPlus) {
3249    // C++1z [over.load]p2
3250    //   Certain function declarations cannot be overloaded:
3251    //     -- Function declarations that differ only in the return type,
3252    //        the exception specification, or both cannot be overloaded.
3253
3254    // Check the exception specifications match. This may recompute the type of
3255    // both Old and New if it resolved exception specifications, so grab the
3256    // types again after this. Because this updates the type, we do this before
3257    // any of the other checks below, which may update the "de facto" NewQType
3258    // but do not necessarily update the type of New.
3259    if (CheckEquivalentExceptionSpec(OldNew))
3260      return true;
3261    OldQType = Context.getCanonicalType(Old->getType());
3262    NewQType = Context.getCanonicalType(New->getType());
3263
3264    // Go back to the type source info to compare the declared return types,
3265    // per C++1y [dcl.type.auto]p13:
3266    //   Redeclarations or specializations of a function or function template
3267    //   with a declared return type that uses a placeholder type shall also
3268    //   use that placeholder, not a deduced type.
3269    QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3270    QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3271    if (!Context.hasSameType(OldDeclaredReturnTypeNewDeclaredReturnType) &&
3272        canFullyTypeCheckRedeclaration(NewOldNewDeclaredReturnType,
3273                                       OldDeclaredReturnType)) {
3274      QualType ResQT;
3275      if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3276          OldDeclaredReturnType->isObjCObjectPointerType())
3277        // FIXME: This does the wrong thing for a deduced return type.
3278        ResQT = Context.mergeObjCGCQualifiers(NewQTypeOldQType);
3279      if (ResQT.isNull()) {
3280        if (New->isCXXClassMember() && New->isOutOfLine())
3281          Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3282              << New << New->getReturnTypeSourceRange();
3283        else
3284          Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3285              << New->getReturnTypeSourceRange();
3286        Diag(OldLocationPrevDiag) << Old << Old->getType()
3287                                    << Old->getReturnTypeSourceRange();
3288        return true;
3289      }
3290      else
3291        NewQType = ResQT;
3292    }
3293
3294    QualType OldReturnType = OldType->getReturnType();
3295    QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3296    if (OldReturnType != NewReturnType) {
3297      // If this function has a deduced return type and has already been
3298      // defined, copy the deduced value from the old declaration.
3299      AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3300      if (OldAT && OldAT->isDeduced()) {
3301        New->setType(
3302            SubstAutoType(New->getType(),
3303                          OldAT->isDependentType() ? Context.DependentTy
3304                                                   : OldAT->getDeducedType()));
3305        NewQType = Context.getCanonicalType(
3306            SubstAutoType(NewQType,
3307                          OldAT->isDependentType() ? Context.DependentTy
3308                                                   : OldAT->getDeducedType()));
3309      }
3310    }
3311
3312    const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3313    CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3314    if (OldMethod && NewMethod) {
3315      // Preserve triviality.
3316      NewMethod->setTrivial(OldMethod->isTrivial());
3317
3318      // MSVC allows explicit template specialization at class scope:
3319      // 2 CXXMethodDecls referring to the same function will be injected.
3320      // We don't want a redeclaration error.
3321      bool IsClassScopeExplicitSpecialization =
3322                              OldMethod->isFunctionTemplateSpecialization() &&
3323                              NewMethod->isFunctionTemplateSpecialization();
3324      bool isFriend = NewMethod->getFriendObjectKind();
3325
3326      if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3327          !IsClassScopeExplicitSpecialization) {
3328        //    -- Member function declarations with the same name and the
3329        //       same parameter types cannot be overloaded if any of them
3330        //       is a static member function declaration.
3331        if (OldMethod->isStatic() != NewMethod->isStatic()) {
3332          Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3333          Diag(OldLocationPrevDiag) << Old << Old->getType();
3334          return true;
3335        }
3336
3337        // C++ [class.mem]p1:
3338        //   [...] A member shall not be declared twice in the
3339        //   member-specification, except that a nested class or member
3340        //   class template can be declared and then later defined.
3341        if (!inTemplateInstantiation()) {
3342          unsigned NewDiag;
3343          if (isa<CXXConstructorDecl>(OldMethod))
3344            NewDiag = diag::err_constructor_redeclared;
3345          else if (isa<CXXDestructorDecl>(NewMethod))
3346            NewDiag = diag::err_destructor_redeclared;
3347          else if (isa<CXXConversionDecl>(NewMethod))
3348            NewDiag = diag::err_conv_function_redeclared;
3349          else
3350            NewDiag = diag::err_member_redeclared;
3351
3352          Diag(New->getLocation(), NewDiag);
3353        } else {
3354          Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3355            << New << New->getType();
3356        }
3357        Diag(OldLocationPrevDiag) << Old << Old->getType();
3358        return true;
3359
3360      // Complain if this is an explicit declaration of a special
3361      // member that was initially declared implicitly.
3362      //
3363      // As an exception, it's okay to befriend such methods in order
3364      // to permit the implicit constructor/destructor/operator calls.
3365      } else if (OldMethod->isImplicit()) {
3366        if (isFriend) {
3367          NewMethod->setImplicit();
3368        } else {
3369          Diag(NewMethod->getLocation(),
3370               diag::err_definition_of_implicitly_declared_member)
3371            << New << getSpecialMember(OldMethod);
3372          return true;
3373        }
3374      } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3375        Diag(NewMethod->getLocation(),
3376             diag::err_definition_of_explicitly_defaulted_member)
3377          << getSpecialMember(OldMethod);
3378        return true;
3379      }
3380    }
3381
3382    // C++11 [dcl.attr.noreturn]p1:
3383    //   The first declaration of a function shall specify the noreturn
3384    //   attribute if any declaration of that function specifies the noreturn
3385    //   attribute.
3386    const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3387    if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3388      Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3389      Diag(Old->getFirstDecl()->getLocation(),
3390           diag::note_noreturn_missing_first_decl);
3391    }
3392
3393    // C++11 [dcl.attr.depend]p2:
3394    //   The first declaration of a function shall specify the
3395    //   carries_dependency attribute for its declarator-id if any declaration
3396    //   of the function specifies the carries_dependency attribute.
3397    const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3398    if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3399      Diag(CDA->getLocation(),
3400           diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3401      Diag(Old->getFirstDecl()->getLocation(),
3402           diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3403    }
3404
3405    // (C++98 8.3.5p3):
3406    //   All declarations for a function shall agree exactly in both the
3407    //   return type and the parameter-type-list.
3408    // We also want to respect all the extended bits except noreturn.
3409
3410    // noreturn should now match unless the old type info didn't have it.
3411    QualType OldQTypeForComparison = OldQType;
3412    if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3413      auto *OldType = OldQType->castAs<FunctionProtoType>();
3414      const FunctionType *OldTypeForComparison
3415        = Context.adjustFunctionType(OldTypeOldTypeInfo.withNoReturn(true));
3416      OldQTypeForComparison = QualType(OldTypeForComparison0);
3417      assert(OldQTypeForComparison.isCanonical());
3418    }
3419
3420    if (haveIncompatibleLanguageLinkages(OldNew)) {
3421      // As a special case, retain the language linkage from previous
3422      // declarations of a friend function as an extension.
3423      //
3424      // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3425      // and is useful because there's otherwise no way to specify language
3426      // linkage within class scope.
3427      //
3428      // Check cautiously as the friend object kind isn't yet complete.
3429      if (New->getFriendObjectKind() != Decl::FOK_None) {
3430        Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3431        Diag(OldLocationPrevDiag);
3432      } else {
3433        Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3434        Diag(OldLocationPrevDiag);
3435        return true;
3436      }
3437    }
3438
3439    if (OldQTypeForComparison == NewQType)
3440      return MergeCompatibleFunctionDecls(NewOldSMergeTypeWithOld);
3441
3442    // If the types are imprecise (due to dependent constructs in friends or
3443    // local extern declarations), it's OK if they differ. We'll check again
3444    // during instantiation.
3445    if (!canFullyTypeCheckRedeclaration(NewOldNewQTypeOldQType))
3446      return false;
3447
3448    // Fall through for conflicting redeclarations and redefinitions.
3449  }
3450
3451  // C: Function types need to be compatible, not identical. This handles
3452  // duplicate function decls like "void f(int); void f(enum X);" properly.
3453  if (!getLangOpts().CPlusPlus &&
3454      Context.typesAreCompatible(OldQTypeNewQType)) {
3455    const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3456    const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3457    const FunctionProtoType *OldProto = nullptr;
3458    if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3459        (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3460      // The old declaration provided a function prototype, but the
3461      // new declaration does not. Merge in the prototype.
3462       (0) . __assert_fail ("!OldProto->hasExceptionSpec() && \"Exception spec in C\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 3462, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3463      SmallVector<QualType16ParamTypes(OldProto->param_types());
3464      NewQType =
3465          Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3466                                  OldProto->getExtProtoInfo());
3467      New->setType(NewQType);
3468      New->setHasInheritedPrototype();
3469
3470      // Synthesize parameters with the same types.
3471      SmallVector<ParmVarDecl*, 16Params;
3472      for (const auto &ParamType : OldProto->param_types()) {
3473        ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3474                                                 SourceLocation(), nullptr,
3475                                                 ParamType, /*TInfo=*/nullptr,
3476                                                 SC_None, nullptr);
3477        Param->setScopeInfo(0, Params.size());
3478        Param->setImplicit();
3479        Params.push_back(Param);
3480      }
3481
3482      New->setParams(Params);
3483    }
3484
3485    return MergeCompatibleFunctionDecls(NewOldSMergeTypeWithOld);
3486  }
3487
3488  // GNU C permits a K&R definition to follow a prototype declaration
3489  // if the declared types of the parameters in the K&R definition
3490  // match the types in the prototype declaration, even when the
3491  // promoted types of the parameters from the K&R definition differ
3492  // from the types in the prototype. GCC then keeps the types from
3493  // the prototype.
3494  //
3495  // If a variadic prototype is followed by a non-variadic K&R definition,
3496  // the K&R definition becomes variadic.  This is sort of an edge case, but
3497  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3498  // C99 6.9.1p8.
3499  if (!getLangOpts().CPlusPlus &&
3500      Old->hasPrototype() && !New->hasPrototype() &&
3501      New->getType()->getAs<FunctionProtoType>() &&
3502      Old->getNumParams() == New->getNumParams()) {
3503    SmallVector<QualType16ArgTypes;
3504    SmallVector<GNUCompatibleParamWarning16Warnings;
3505    const FunctionProtoType *OldProto
3506      = Old->getType()->getAs<FunctionProtoType>();
3507    const FunctionProtoType *NewProto
3508      = New->getType()->getAs<FunctionProtoType>();
3509
3510    // Determine whether this is the GNU C extension.
3511    QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3512                                               NewProto->getReturnType());
3513    bool LooseCompatible = !MergedReturn.isNull();
3514    for (unsigned Idx = 0End = Old->getNumParams();
3515         LooseCompatible && Idx != End; ++Idx) {
3516      ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3517      ParmVarDecl *NewParm = New->getParamDecl(Idx);
3518      if (Context.typesAreCompatible(OldParm->getType(),
3519                                     NewProto->getParamType(Idx))) {
3520        ArgTypes.push_back(NewParm->getType());
3521      } else if (Context.typesAreCompatible(OldParm->getType(),
3522                                            NewParm->getType(),
3523                                            /*CompareUnqualified=*/true)) {
3524        GNUCompatibleParamWarning Warn = { OldParmNewParm,
3525                                           NewProto->getParamType(Idx) };
3526        Warnings.push_back(Warn);
3527        ArgTypes.push_back(NewParm->getType());
3528      } else
3529        LooseCompatible = false;
3530    }
3531
3532    if (LooseCompatible) {
3533      for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3534        Diag(Warnings[Warn].NewParm->getLocation(),
3535             diag::ext_param_promoted_not_compatible_with_prototype)
3536          << Warnings[Warn].PromotedType
3537          << Warnings[Warn].OldParm->getType();
3538        if (Warnings[Warn].OldParm->getLocation().isValid())
3539          Diag(Warnings[Warn].OldParm->getLocation(),
3540               diag::note_previous_declaration);
3541      }
3542
3543      if (MergeTypeWithOld)
3544        New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3545                                             OldProto->getExtProtoInfo()));
3546      return MergeCompatibleFunctionDecls(NewOldSMergeTypeWithOld);
3547    }
3548
3549    // Fall through to diagnose conflicting types.
3550  }
3551
3552  // A function that has already been declared has been redeclared or
3553  // defined with a different type; show an appropriate diagnostic.
3554
3555  // If the previous declaration was an implicitly-generated builtin
3556  // declaration, then at the very least we should use a specialized note.
3557  unsigned BuiltinID;
3558  if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3559    // If it's actually a library-defined builtin function like 'malloc'
3560    // or 'printf', just warn about the incompatible redeclaration.
3561    if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3562      Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3563      Diag(OldLocation, diag::note_previous_builtin_declaration)
3564        << Old << Old->getType();
3565
3566      // If this is a global redeclaration, just forget hereafter
3567      // about the "builtin-ness" of the function.
3568      //
3569      // Doing this for local extern declarations is problematic.  If
3570      // the builtin declaration remains visible, a second invalid
3571      // local declaration will produce a hard error; if it doesn't
3572      // remain visible, a single bogus local redeclaration (which is
3573      // actually only a warning) could break all the downstream code.
3574      if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3575        New->getIdentifier()->revertBuiltin();
3576
3577      return false;
3578    }
3579
3580    PrevDiag = diag::note_previous_builtin_declaration;
3581  }
3582
3583  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3584  Diag(OldLocationPrevDiag) << Old << Old->getType();
3585  return true;
3586}
3587
3588/// Completes the merge of two function declarations that are
3589/// known to be compatible.
3590///
3591/// This routine handles the merging of attributes and other
3592/// properties of function declarations from the old declaration to
3593/// the new declaration, once we know that New is in fact a
3594/// redeclaration of Old.
3595///
3596/// \returns false
3597bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *NewFunctionDecl *Old,
3598                                        Scope *Sbool MergeTypeWithOld) {
3599  // Merge the attributes
3600  mergeDeclAttributes(NewOld);
3601
3602  // Merge "pure" flag.
3603  if (Old->isPure())
3604    New->setPure();
3605
3606  // Merge "used" flag.
3607  if (Old->getMostRecentDecl()->isUsed(false))
3608    New->setIsUsed();
3609
3610  // Merge attributes from the parameters.  These can mismatch with K&R
3611  // declarations.
3612  if (New->getNumParams() == Old->getNumParams())
3613      for (unsigned i = 0e = New->getNumParams(); i != e; ++i) {
3614        ParmVarDecl *NewParam = New->getParamDecl(i);
3615        ParmVarDecl *OldParam = Old->getParamDecl(i);
3616        mergeParamDeclAttributes(NewParamOldParam*this);
3617        mergeParamDeclTypes(NewParamOldParam*this);
3618      }
3619
3620  if (getLangOpts().CPlusPlus)
3621    return MergeCXXFunctionDecl(NewOldS);
3622
3623  // Merge the function types so the we get the composite types for the return
3624  // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3625  // was visible.
3626  QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3627  if (!Merged.isNull() && MergeTypeWithOld)
3628    New->setType(Merged);
3629
3630  return false;
3631}
3632
3633void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3634                                ObjCMethodDecl *oldMethod) {
3635  // Merge the attributes, including deprecated/unavailable
3636  AvailabilityMergeKind MergeKind =
3637    isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3638      ? AMK_ProtocolImplementation
3639      : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3640                                                       : AMK_Override;
3641
3642  mergeDeclAttributes(newMethodoldMethodMergeKind);
3643
3644  // Merge attributes from the parameters.
3645  ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3646                                       oe = oldMethod->param_end();
3647  for (ObjCMethodDecl::param_iterator
3648         ni = newMethod->param_begin(), ne = newMethod->param_end();
3649       ni != ne && oi != oe; ++ni, ++oi)
3650    mergeParamDeclAttributes(*ni, *oi*this);
3651
3652  CheckObjCMethodOverride(newMethodoldMethod);
3653}
3654
3655static void diagnoseVarDeclTypeMismatch(Sema &SVarDecl *NewVarDeclOld) {
3656  getType(), Old->getType())", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 3656, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3657
3658  S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3659         ? diag::err_redefinition_different_type
3660         : diag::err_redeclaration_different_type)
3661    << New->getDeclName() << New->getType() << Old->getType();
3662
3663  diag::kind PrevDiag;
3664  SourceLocation OldLocation;
3665  std::tie(PrevDiagOldLocation)
3666    = getNoteDiagForInvalidRedeclaration(OldNew);
3667  S.Diag(OldLocationPrevDiag);
3668  New->setInvalidDecl();
3669}
3670
3671/// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3672/// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3673/// emitting diagnostics as appropriate.
3674///
3675/// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3676/// to here in AddInitializerToDecl. We can't check them before the initializer
3677/// is attached.
3678void Sema::MergeVarDeclTypes(VarDecl *NewVarDecl *Old,
3679                             bool MergeTypeWithOld) {
3680  if (New->isInvalidDecl() || Old->isInvalidDecl())
3681    return;
3682
3683  QualType MergedT;
3684  if (getLangOpts().CPlusPlus) {
3685    if (New->getType()->isUndeducedType()) {
3686      // We don't know what the new type is until the initializer is attached.
3687      return;
3688    } else if (Context.hasSameType(New->getType(), Old->getType())) {
3689      // These could still be something that needs exception specs checked.
3690      return MergeVarDeclExceptionSpecs(NewOld);
3691    }
3692    // C++ [basic.link]p10:
3693    //   [...] the types specified by all declarations referring to a given
3694    //   object or function shall be identical, except that declarations for an
3695    //   array object can specify array types that differ by the presence or
3696    //   absence of a major array bound (8.3.4).
3697    else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3698      const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3699      const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3700
3701      // We are merging a variable declaration New into Old. If it has an array
3702      // bound, and that bound differs from Old's bound, we should diagnose the
3703      // mismatch.
3704      if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3705        for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3706             PrevVD = PrevVD->getPreviousDecl()) {
3707          const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3708          if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3709            continue;
3710
3711          if (!Context.hasSameType(NewArrayPrevVDTy))
3712            return diagnoseVarDeclTypeMismatch(*thisNewPrevVD);
3713        }
3714      }
3715
3716      if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3717        if (Context.hasSameType(OldArray->getElementType(),
3718                                NewArray->getElementType()))
3719          MergedT = New->getType();
3720      }
3721      // FIXME: Check visibility. New is hidden but has a complete type. If New
3722      // has no array bound, it should not inherit one from Old, if Old is not
3723      // visible.
3724      else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3725        if (Context.hasSameType(OldArray->getElementType(),
3726                                NewArray->getElementType()))
3727          MergedT = Old->getType();
3728      }
3729    }
3730    else if (New->getType()->isObjCObjectPointerType() &&
3731               Old->getType()->isObjCObjectPointerType()) {
3732      MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3733                                              Old->getType());
3734    }
3735  } else {
3736    // C 6.2.7p2:
3737    //   All declarations that refer to the same object or function shall have
3738    //   compatible type.
3739    MergedT = Context.mergeTypes(New->getType(), Old->getType());
3740  }
3741  if (MergedT.isNull()) {
3742    // It's OK if we couldn't merge types if either type is dependent, for a
3743    // block-scope variable. In other cases (static data members of class
3744    // templates, variable templates, ...), we require the types to be
3745    // equivalent.
3746    // FIXME: The C++ standard doesn't say anything about this.
3747    if ((New->getType()->isDependentType() ||
3748         Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3749      // If the old type was dependent, we can't merge with it, so the new type
3750      // becomes dependent for now. We'll reproduce the original type when we
3751      // instantiate the TypeSourceInfo for the variable.
3752      if (!New->getType()->isDependentType() && MergeTypeWithOld)
3753        New->setType(Context.DependentTy);
3754      return;
3755    }
3756    return diagnoseVarDeclTypeMismatch(*thisNewOld);
3757  }
3758
3759  // Don't actually update the type on the new declaration if the old
3760  // declaration was an extern declaration in a different scope.
3761  if (MergeTypeWithOld)
3762    New->setType(MergedT);
3763}
3764
3765static bool mergeTypeWithPrevious(Sema &SVarDecl *NewVDVarDecl *OldVD,
3766                                  LookupResult &Previous) {
3767  // C11 6.2.7p4:
3768  //   For an identifier with internal or external linkage declared
3769  //   in a scope in which a prior declaration of that identifier is
3770  //   visible, if the prior declaration specifies internal or
3771  //   external linkage, the type of the identifier at the later
3772  //   declaration becomes the composite type.
3773  //
3774  // If the variable isn't visible, we do not merge with its type.
3775  if (Previous.isShadowed())
3776    return false;
3777
3778  if (S.getLangOpts().CPlusPlus) {
3779    // C++11 [dcl.array]p3:
3780    //   If there is a preceding declaration of the entity in the same
3781    //   scope in which the bound was specified, an omitted array bound
3782    //   is taken to be the same as in that earlier declaration.
3783    return NewVD->isPreviousDeclInSameBlockScope() ||
3784           (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3785            !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3786  } else {
3787    // If the old declaration was function-local, don't merge with its
3788    // type unless we're in the same function.
3789    return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3790           OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3791  }
3792}
3793
3794/// MergeVarDecl - We just parsed a variable 'New' which has the same name
3795/// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3796/// situation, merging decls or emitting diagnostics as appropriate.
3797///
3798/// Tentative definition rules (C99 6.9.2p2) are checked by
3799/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3800/// definitions here, since the initializer hasn't been attached.
3801///
3802void Sema::MergeVarDecl(VarDecl *NewLookupResult &Previous) {
3803  // If the new decl is already invalid, don't do any other checking.
3804  if (New->isInvalidDecl())
3805    return;
3806
3807  if (!shouldLinkPossiblyHiddenDecl(PreviousNew))
3808    return;
3809
3810  VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3811
3812  // Verify the old decl was also a variable or variable template.
3813  VarDecl *Old = nullptr;
3814  VarTemplateDecl *OldTemplate = nullptr;
3815  if (Previous.isSingleResult()) {
3816    if (NewTemplate) {
3817      OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3818      Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3819
3820      if (auto *Shadow =
3821              dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3822        if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3823          return New->setInvalidDecl();
3824    } else {
3825      Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3826
3827      if (auto *Shadow =
3828              dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3829        if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3830          return New->setInvalidDecl();
3831    }
3832  }
3833  if (!Old) {
3834    Diag(New->getLocation(), diag::err_redefinition_different_kind)
3835        << New->getDeclName();
3836    notePreviousDefinition(Previous.getRepresentativeDecl(),
3837                           New->getLocation());
3838    return New->setInvalidDecl();
3839  }
3840
3841  // Ensure the template parameters are compatible.
3842  if (NewTemplate &&
3843      !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3844                                      OldTemplate->getTemplateParameters(),
3845                                      /*Complain=*/trueTPL_TemplateMatch))
3846    return New->setInvalidDecl();
3847
3848  // C++ [class.mem]p1:
3849  //   A member shall not be declared twice in the member-specification [...]
3850  //
3851  // Here, we need only consider static data members.
3852  if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3853    Diag(New->getLocation(), diag::err_duplicate_member)
3854      << New->getIdentifier();
3855    Diag(Old->getLocation(), diag::note_previous_declaration);
3856    New->setInvalidDecl();
3857  }
3858
3859  mergeDeclAttributes(NewOld);
3860  // Warn if an already-declared variable is made a weak_import in a subsequent
3861  // declaration
3862  if (New->hasAttr<WeakImportAttr>() &&
3863      Old->getStorageClass() == SC_None &&
3864      !Old->hasAttr<WeakImportAttr>()) {
3865    Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3866    notePreviousDefinition(OldNew->getLocation());
3867    // Remove weak_import attribute on new declaration.
3868    New->dropAttr<WeakImportAttr>();
3869  }
3870
3871  if (New->hasAttr<InternalLinkageAttr>() &&
3872      !Old->hasAttr<InternalLinkageAttr>()) {
3873    Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3874        << New->getDeclName();
3875    notePreviousDefinition(OldNew->getLocation());
3876    New->dropAttr<InternalLinkageAttr>();
3877  }
3878
3879  // Merge the types.
3880  VarDecl *MostRecent = Old->getMostRecentDecl();
3881  if (MostRecent != Old) {
3882    MergeVarDeclTypes(NewMostRecent,
3883                      mergeTypeWithPrevious(*thisNewMostRecentPrevious));
3884    if (New->isInvalidDecl())
3885      return;
3886  }
3887
3888  MergeVarDeclTypes(NewOldmergeTypeWithPrevious(*thisNewOldPrevious));
3889  if (New->isInvalidDecl())
3890    return;
3891
3892  diag::kind PrevDiag;
3893  SourceLocation OldLocation;
3894  std::tie(PrevDiagOldLocation) =
3895      getNoteDiagForInvalidRedeclaration(OldNew);
3896
3897  // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3898  if (New->getStorageClass() == SC_Static &&
3899      !New->isStaticDataMember() &&
3900      Old->hasExternalFormalLinkage()) {
3901    if (getLangOpts().MicrosoftExt) {
3902      Diag(New->getLocation(), diag::ext_static_non_static)
3903          << New->getDeclName();
3904      Diag(OldLocationPrevDiag);
3905    } else {
3906      Diag(New->getLocation(), diag::err_static_non_static)
3907          << New->getDeclName();
3908      Diag(OldLocationPrevDiag);
3909      return New->setInvalidDecl();
3910    }
3911  }
3912  // C99 6.2.2p4:
3913  //   For an identifier declared with the storage-class specifier
3914  //   extern in a scope in which a prior declaration of that
3915  //   identifier is visible,23) if the prior declaration specifies
3916  //   internal or external linkage, the linkage of the identifier at
3917  //   the later declaration is the same as the linkage specified at
3918  //   the prior declaration. If no prior declaration is visible, or
3919  //   if the prior declaration specifies no linkage, then the
3920  //   identifier has external linkage.
3921  if (New->hasExternalStorage() && Old->hasLinkage())
3922    /* Okay */;
3923  else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3924           !New->isStaticDataMember() &&
3925           Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3926    Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3927    Diag(OldLocationPrevDiag);
3928    return New->setInvalidDecl();
3929  }
3930
3931  // Check if extern is followed by non-extern and vice-versa.
3932  if (New->hasExternalStorage() &&
3933      !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3934    Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3935    Diag(OldLocationPrevDiag);
3936    return New->setInvalidDecl();
3937  }
3938  if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3939      !New->hasExternalStorage()) {
3940    Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3941    Diag(OldLocationPrevDiag);
3942    return New->setInvalidDecl();
3943  }
3944
3945  if (CheckRedeclarationModuleOwnership(NewOld))
3946    return;
3947
3948  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3949
3950  // FIXME: The test for external storage here seems wrong? We still
3951  // need to check for mismatches.
3952  if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3953      // Don't complain about out-of-line definitions of static members.
3954      !(Old->getLexicalDeclContext()->isRecord() &&
3955        !New->getLexicalDeclContext()->isRecord())) {
3956    Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3957    Diag(OldLocationPrevDiag);
3958    return New->setInvalidDecl();
3959  }
3960
3961  if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3962    if (VarDecl *Def = Old->getDefinition()) {
3963      // C++1z [dcl.fcn.spec]p4:
3964      //   If the definition of a variable appears in a translation unit before
3965      //   its first declaration as inline, the program is ill-formed.
3966      Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3967      Diag(Def->getLocation(), diag::note_previous_definition);
3968    }
3969  }
3970
3971  // If this redeclaration makes the variable inline, we may need to add it to
3972  // UndefinedButUsed.
3973  if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3974      !Old->getDefinition() && !New->isThisDeclarationADefinition())
3975    UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3976                                           SourceLocation()));
3977
3978  if (New->getTLSKind() != Old->getTLSKind()) {
3979    if (!Old->getTLSKind()) {
3980      Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3981      Diag(OldLocationPrevDiag);
3982    } else if (!New->getTLSKind()) {
3983      Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3984      Diag(OldLocationPrevDiag);
3985    } else {
3986      // Do not allow redeclaration to change the variable between requiring
3987      // static and dynamic initialization.
3988      // FIXME: GCC allows this, but uses the TLS keyword on the first
3989      // declaration to determine the kind. Do we need to be compatible here?
3990      Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3991        << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3992      Diag(OldLocationPrevDiag);
3993    }
3994  }
3995
3996  // C++ doesn't have tentative definitions, so go right ahead and check here.
3997  if (getLangOpts().CPlusPlus &&
3998      New->isThisDeclarationADefinition() == VarDecl::Definition) {
3999    if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4000        Old->getCanonicalDecl()->isConstexpr()) {
4001      // This definition won't be a definition any more once it's been merged.
4002      Diag(New->getLocation(),
4003           diag::warn_deprecated_redundant_constexpr_static_def);
4004    } else if (VarDecl *Def = Old->getDefinition()) {
4005      if (checkVarDeclRedefinition(DefNew))
4006        return;
4007    }
4008  }
4009
4010  if (haveIncompatibleLanguageLinkages(OldNew)) {
4011    Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4012    Diag(OldLocationPrevDiag);
4013    New->setInvalidDecl();
4014    return;
4015  }
4016
4017  // Merge "used" flag.
4018  if (Old->getMostRecentDecl()->isUsed(false))
4019    New->setIsUsed();
4020
4021  // Keep a chain of previous declarations.
4022  New->setPreviousDecl(Old);
4023  if (NewTemplate)
4024    NewTemplate->setPreviousDecl(OldTemplate);
4025  adjustDeclContextForDeclaratorDecl(NewOld);
4026
4027  // Inherit access appropriately.
4028  New->setAccess(Old->getAccess());
4029  if (NewTemplate)
4030    NewTemplate->setAccess(New->getAccess());
4031
4032  if (Old->isInline())
4033    New->setImplicitlyInline();
4034}
4035
4036void Sema::notePreviousDefinition(const NamedDecl *OldSourceLocation New) {
4037  SourceManager &SrcMgr = getSourceManager();
4038  auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4039  auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4040  auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4041  auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4042  auto &HSI = PP.getHeaderSearchInfo();
4043  StringRef HdrFilename =
4044      SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4045
4046  auto noteFromModuleOrInclude = [&](Module *Mod,
4047                                     SourceLocation IncLoc) -> bool {
4048    // Redefinition errors with modules are common with non modular mapped
4049    // headers, example: a non-modular header H in module A that also gets
4050    // included directly in a TU. Pointing twice to the same header/definition
4051    // is confusing, try to get better diagnostics when modules is on.
4052    if (IncLoc.isValid()) {
4053      if (Mod) {
4054        Diag(IncLoc, diag::note_redefinition_modules_same_file)
4055            << HdrFilename.str() << Mod->getFullModuleName();
4056        if (!Mod->DefinitionLoc.isInvalid())
4057          Diag(Mod->DefinitionLoc, diag::note_defined_here)
4058              << Mod->getFullModuleName();
4059      } else {
4060        Diag(IncLoc, diag::note_redefinition_include_same_file)
4061            << HdrFilename.str();
4062      }
4063      return true;
4064    }
4065
4066    return false;
4067  };
4068
4069  // Is it the same file and same offset? Provide more information on why
4070  // this leads to a redefinition error.
4071  bool EmittedDiag = false;
4072  if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4073    SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4074    SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4075    EmittedDiag = noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4076    EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4077
4078    // If the header has no guards, emit a note suggesting one.
4079    if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4080      Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4081
4082    if (EmittedDiag)
4083      return;
4084  }
4085
4086  // Redefinition coming from different files or couldn't do better above.
4087  if (Old->getLocation().isValid())
4088    Diag(Old->getLocation(), diag::note_previous_definition);
4089}
4090
4091/// We've just determined that \p Old and \p New both appear to be definitions
4092/// of the same variable. Either diagnose or fix the problem.
4093bool Sema::checkVarDeclRedefinition(VarDecl *OldVarDecl *New) {
4094  if (!hasVisibleDefinition(Old) &&
4095      (New->getFormalLinkage() == InternalLinkage ||
4096       New->isInline() ||
4097       New->getDescribedVarTemplate() ||
4098       New->getNumTemplateParameterLists() ||
4099       New->getDeclContext()->isDependentContext())) {
4100    // The previous definition is hidden, and multiple definitions are
4101    // permitted (in separate TUs). Demote this to a declaration.
4102    New->demoteThisDefinitionToDeclaration();
4103
4104    // Make the canonical definition visible.
4105    if (auto *OldTD = Old->getDescribedVarTemplate())
4106      makeMergedDefinitionVisible(OldTD);
4107    makeMergedDefinitionVisible(Old);
4108    return false;
4109  } else {
4110    Diag(New->getLocation(), diag::err_redefinition) << New;
4111    notePreviousDefinition(OldNew->getLocation());
4112    New->setInvalidDecl();
4113    return true;
4114  }
4115}
4116
4117/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4118/// no declarator (e.g. "struct foo;") is parsed.
4119Decl *
4120Sema::ParsedFreeStandingDeclSpec(Scope *SAccessSpecifier ASDeclSpec &DS,
4121                                 RecordDecl *&AnonRecord) {
4122  return ParsedFreeStandingDeclSpec(SASDS, MultiTemplateParamsArg(), false,
4123                                    AnonRecord);
4124}
4125
4126// The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4127// disambiguate entities defined in different scopes.
4128// While the VS2015 ABI fixes potential miscompiles, it is also breaks
4129// compatibility.
4130// We will pick our mangling number depending on which version of MSVC is being
4131// targeted.
4132static unsigned getMSManglingNumber(const LangOptions &LOScope *S) {
4133  return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
4134             ? S->getMSCurManglingNumber()
4135             : S->getMSLastManglingNumber();
4136}
4137
4138void Sema::handleTagNumbering(const TagDecl *TagScope *TagScope) {
4139  if (!Context.getLangOpts().CPlusPlus)
4140    return;
4141
4142  if (isa<CXXRecordDecl>(Tag->getParent())) {
4143    // If this tag is the direct child of a class, number it if
4144    // it is anonymous.
4145    if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4146      return;
4147    MangleNumberingContext &MCtx =
4148        Context.getManglingNumberContext(Tag->getParent());
4149    Context.setManglingNumber(
4150        TagMCtx.getManglingNumber(
4151                 TaggetMSManglingNumber(getLangOpts(), TagScope)));
4152    return;
4153  }
4154
4155  // If this tag isn't a direct child of a class, number it if it is local.
4156  Decl *ManglingContextDecl;
4157  if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4158          Tag->getDeclContext(), ManglingContextDecl)) {
4159    Context.setManglingNumber(
4160        TagMCtx->getManglingNumber(
4161                 TaggetMSManglingNumber(getLangOpts(), TagScope)));
4162  }
4163}
4164
4165void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
4166                                        TypedefNameDecl *NewTD) {
4167  if (TagFromDeclSpec->isInvalidDecl())
4168    return;
4169
4170  // Do nothing if the tag already has a name for linkage purposes.
4171  if (TagFromDeclSpec->hasNameForLinkage())
4172    return;
4173
4174  // A well-formed anonymous tag must always be a TUK_Definition.
4175  isThisDeclarationADefinition()", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 4175, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(TagFromDeclSpec->isThisDeclarationADefinition());
4176
4177  // The type must match the tag exactly;  no qualifiers allowed.
4178  if (!Context.hasSameType(NewTD->getUnderlyingType(),
4179                           Context.getTagDeclType(TagFromDeclSpec))) {
4180    if (getLangOpts().CPlusPlus)
4181      Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpecNewTD);
4182    return;
4183  }
4184
4185  // If we've already computed linkage for the anonymous tag, then
4186  // adding a typedef name for the anonymous decl can change that
4187  // linkage, which might be a serious problem.  Diagnose this as
4188  // unsupported and ignore the typedef name.  TODO: we should
4189  // pursue this as a language defect and establish a formal rule
4190  // for how to handle it.
4191  if (TagFromDeclSpec->hasLinkageBeenComputed()) {
4192    Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
4193
4194    SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
4195    tagLoc = getLocForEndOfToken(tagLoc);
4196
4197    llvm::SmallString<40textToInsert;
4198    textToInsert += ' ';
4199    textToInsert += NewTD->getIdentifier()->getName();
4200    Diag(tagLoc, diag::note_typedef_changes_linkage)
4201        << FixItHint::CreateInsertion(tagLoc, textToInsert);
4202    return;
4203  }
4204
4205  // Otherwise, set this is the anon-decl typedef for the tag.
4206  TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4207}
4208
4209static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
4210  switch (T) {
4211  case DeclSpec::TST_class:
4212    return 0;
4213  case DeclSpec::TST_struct:
4214    return 1;
4215  case DeclSpec::TST_interface:
4216    return 2;
4217  case DeclSpec::TST_union:
4218    return 3;
4219  case DeclSpec::TST_enum:
4220    return 4;
4221  default:
4222    llvm_unreachable("unexpected type specifier");
4223  }
4224}
4225
4226/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4227/// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4228/// parameters to cope with template friend declarations.
4229Decl *
4230Sema::ParsedFreeStandingDeclSpec(Scope *SAccessSpecifier ASDeclSpec &DS,
4231                                 MultiTemplateParamsArg TemplateParams,
4232                                 bool IsExplicitInstantiation,
4233                                 RecordDecl *&AnonRecord) {
4234  Decl *TagD = nullptr;
4235  TagDecl *Tag = nullptr;
4236  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4237      DS.getTypeSpecType() == DeclSpec::TST_struct ||
4238      DS.getTypeSpecType() == DeclSpec::TST_interface ||
4239      DS.getTypeSpecType() == DeclSpec::TST_union ||
4240      DS.getTypeSpecType() == DeclSpec::TST_enum) {
4241    TagD = DS.getRepAsDecl();
4242
4243    if (!TagD// We probably had an error
4244      return nullptr;
4245
4246    // Note that the above type specs guarantee that the
4247    // type rep is a Decl, whereas in many of the others
4248    // it's a Type.
4249    if (isa<TagDecl>(TagD))
4250      Tag = cast<TagDecl>(TagD);
4251    else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4252      Tag = CTD->getTemplatedDecl();
4253  }
4254
4255  if (Tag) {
4256    handleTagNumbering(TagS);
4257    Tag->setFreeStanding();
4258    if (Tag->isInvalidDecl())
4259      return Tag;
4260  }
4261
4262  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4263    // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4264    // or incomplete types shall not be restrict-qualified."
4265    if (TypeQuals & DeclSpec::TQ_restrict)
4266      Diag(DS.getRestrictSpecLoc(),
4267           diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4268           << DS.getSourceRange();
4269  }
4270
4271  if (DS.isInlineSpecified())
4272    Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4273        << getLangOpts().CPlusPlus17;
4274
4275  if (DS.isConstexprSpecified()) {
4276    // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4277    // and definitions of functions and variables.
4278    if (Tag)
4279      Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4280          << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
4281    else
4282      Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
4283    // Don't emit warnings after this error.
4284    return TagD;
4285  }
4286
4287  DiagnoseFunctionSpecifiers(DS);
4288
4289  if (DS.isFriendSpecified()) {
4290    // If we're dealing with a decl but not a TagDecl, assume that
4291    // whatever routines created it handled the friendship aspect.
4292    if (TagD && !Tag)
4293      return nullptr;
4294    return ActOnFriendTypeDecl(S, DS, TemplateParams);
4295  }
4296
4297  const CXXScopeSpec &SS = DS.getTypeSpecScope();
4298  bool IsExplicitSpecialization =
4299    !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4300  if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4301      !IsExplicitInstantiation && !IsExplicitSpecialization &&
4302      !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4303    // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4304    // nested-name-specifier unless it is an explicit instantiation
4305    // or an explicit specialization.
4306    //
4307    // FIXME: We allow class template partial specializations here too, per the
4308    // obvious intent of DR1819.
4309    //
4310    // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4311    Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4312        << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
4313    return nullptr;
4314  }
4315
4316  // Track whether this decl-specifier declares anything.
4317  bool DeclaresAnything = true;
4318
4319  // Handle anonymous struct definitions.
4320  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4321    if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4322        DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4323      if (getLangOpts().CPlusPlus ||
4324          Record->getDeclContext()->isRecord()) {
4325        // If CurContext is a DeclContext that can contain statements,
4326        // RecursiveASTVisitor won't visit the decls that
4327        // BuildAnonymousStructOrUnion() will put into CurContext.
4328        // Also store them here so that they can be part of the
4329        // DeclStmt that gets created in this case.
4330        // FIXME: Also return the IndirectFieldDecls created by
4331        // BuildAnonymousStructOr union, for the same reason?
4332        if (CurContext->isFunctionOrMethod())
4333          AnonRecord = Record;
4334        return BuildAnonymousStructOrUnion(SDSASRecord,
4335                                           Context.getPrintingPolicy());
4336      }
4337
4338      DeclaresAnything = false;
4339    }
4340  }
4341
4342  // C11 6.7.2.1p2:
4343  //   A struct-declaration that does not declare an anonymous structure or
4344  //   anonymous union shall contain a struct-declarator-list.
4345  //
4346  // This rule also existed in C89 and C99; the grammar for struct-declaration
4347  // did not permit a struct-declaration without a struct-declarator-list.
4348  if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4349      DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4350    // Check for Microsoft C extension: anonymous struct/union member.
4351    // Handle 2 kinds of anonymous struct/union:
4352    //   struct STRUCT;
4353    //   union UNION;
4354    // and
4355    //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4356    //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4357    if ((Tag && Tag->getDeclName()) ||
4358        DS.getTypeSpecType() == DeclSpec::TST_typename) {
4359      RecordDecl *Record = nullptr;
4360      if (Tag)
4361        Record = dyn_cast<RecordDecl>(Tag);
4362      else if (const RecordType *RT =
4363                   DS.getRepAsType().get()->getAsStructureType())
4364        Record = RT->getDecl();
4365      else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4366        Record = UT->getDecl();
4367
4368      if (Record && getLangOpts().MicrosoftExt) {
4369        Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4370            << Record->isUnion() << DS.getSourceRange();
4371        return BuildMicrosoftCAnonymousStruct(SDSRecord);
4372      }
4373
4374      DeclaresAnything = false;
4375    }
4376  }
4377
4378  // Skip all the checks below if we have a type error.
4379  if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4380      (TagD && TagD->isInvalidDecl()))
4381    return TagD;
4382
4383  if (getLangOpts().CPlusPlus &&
4384      DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4385    if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4386      if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4387          !Enum->getIdentifier() && !Enum->isInvalidDecl())
4388        DeclaresAnything = false;
4389
4390  if (!DS.isMissingDeclaratorOk()) {
4391    // Customize diagnostic for a typedef missing a name.
4392    if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4393      Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4394          << DS.getSourceRange();
4395    else
4396      DeclaresAnything = false;
4397  }
4398
4399  if (DS.isModulePrivateSpecified() &&
4400      Tag && Tag->getDeclContext()->isFunctionOrMethod())
4401    Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4402      << Tag->getTagKind()
4403      << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4404
4405  ActOnDocumentableDecl(TagD);
4406
4407  // C 6.7/2:
4408  //   A declaration [...] shall declare at least a declarator [...], a tag,
4409  //   or the members of an enumeration.
4410  // C++ [dcl.dcl]p3:
4411  //   [If there are no declarators], and except for the declaration of an
4412  //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4413  //   names into the program, or shall redeclare a name introduced by a
4414  //   previous declaration.
4415  if (!DeclaresAnything) {
4416    // In C, we allow this as a (popular) extension / bug. Don't bother
4417    // producing further diagnostics for redundant qualifiers after this.
4418    Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
4419    return TagD;
4420  }
4421
4422  // C++ [dcl.stc]p1:
4423  //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4424  //   init-declarator-list of the declaration shall not be empty.
4425  // C++ [dcl.fct.spec]p1:
4426  //   If a cv-qualifier appears in a decl-specifier-seq, the
4427  //   init-declarator-list of the declaration shall not be empty.
4428  //
4429  // Spurious qualifiers here appear to be valid in C.
4430  unsigned DiagID = diag::warn_standalone_specifier;
4431  if (getLangOpts().CPlusPlus)
4432    DiagID = diag::ext_standalone_specifier;
4433
4434  // Note that a linkage-specification sets a storage class, but
4435  // 'extern "C" struct foo;' is actually valid and not theoretically
4436  // useless.
4437  if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4438    if (SCS == DeclSpec::SCS_mutable)
4439      // Since mutable is not a viable storage class specifier in C, there is
4440      // no reason to treat it as an extension. Instead, diagnose as an error.
4441      Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4442    else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4443      Diag(DS.getStorageClassSpecLoc(), DiagID)
4444        << DeclSpec::getSpecifierName(SCS);
4445  }
4446
4447  if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4448    Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4449      << DeclSpec::getSpecifierName(TSCS);
4450  if (DS.getTypeQualifiers()) {
4451    if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4452      Diag(DS.getConstSpecLoc(), DiagID) << "const";
4453    if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4454      Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4455    // Restrict is covered above.
4456    if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4457      Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4458    if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4459      Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4460  }
4461
4462  // Warn about ignored type attributes, for example:
4463  // __attribute__((aligned)) struct A;
4464  // Attributes should be placed after tag to apply to type declaration.
4465  if (!DS.getAttributes().empty()) {
4466    DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4467    if (TypeSpecType == DeclSpec::TST_class ||
4468        TypeSpecType == DeclSpec::TST_struct ||
4469        TypeSpecType == DeclSpec::TST_interface ||
4470        TypeSpecType == DeclSpec::TST_union ||
4471        TypeSpecType == DeclSpec::TST_enum) {
4472      for (const ParsedAttr &AL : DS.getAttributes())
4473        Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
4474            << AL.getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4475    }
4476  }
4477
4478  return TagD;
4479}
4480
4481/// We are trying to inject an anonymous member into the given scope;
4482/// check if there's an existing declaration that can't be overloaded.
4483///
4484/// \return true if this is a forbidden redeclaration
4485static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4486                                         Scope *S,
4487                                         DeclContext *Owner,
4488                                         DeclarationName Name,
4489                                         SourceLocation NameLoc,
4490                                         bool IsUnion) {
4491  LookupResult R(SemaRefNameNameLocSema::LookupMemberName,
4492                 Sema::ForVisibleRedeclaration);
4493  if (!SemaRef.LookupName(RS)) return false;
4494
4495  // Pick a representative declaration.
4496  NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4497   (0) . __assert_fail ("PrevDecl && \"Expected a non-null Decl\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 4497, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(PrevDecl && "Expected a non-null Decl");
4498
4499  if (!SemaRef.isDeclInScope(PrevDeclOwnerS))
4500    return false;
4501
4502  SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4503    << IsUnion << Name;
4504  SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4505
4506  return true;
4507}
4508
4509/// InjectAnonymousStructOrUnionMembers - Inject the members of the
4510/// anonymous struct or union AnonRecord into the owning context Owner
4511/// and scope S. This routine will be invoked just after we realize
4512/// that an unnamed union or struct is actually an anonymous union or
4513/// struct, e.g.,
4514///
4515/// @code
4516/// union {
4517///   int i;
4518///   float f;
4519/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4520///    // f into the surrounding scope.x
4521/// @endcode
4522///
4523/// This routine is recursive, injecting the names of nested anonymous
4524/// structs/unions into the owning context and scope as well.
4525static bool
4526InjectAnonymousStructOrUnionMembers(Sema &SemaRefScope *SDeclContext *Owner,
4527                                    RecordDecl *AnonRecordAccessSpecifier AS,
4528                                    SmallVectorImpl<NamedDecl *> &Chaining) {
4529  bool Invalid = false;
4530
4531  // Look every FieldDecl and IndirectFieldDecl with a name.
4532  for (auto *D : AnonRecord->decls()) {
4533    if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4534        cast<NamedDecl>(D)->getDeclName()) {
4535      ValueDecl *VD = cast<ValueDecl>(D);
4536      if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4537                                       VD->getLocation(),
4538                                       AnonRecord->isUnion())) {
4539        // C++ [class.union]p2:
4540        //   The names of the members of an anonymous union shall be
4541        //   distinct from the names of any other entity in the
4542        //   scope in which the anonymous union is declared.
4543        Invalid = true;
4544      } else {
4545        // C++ [class.union]p2:
4546        //   For the purpose of name lookup, after the anonymous union
4547        //   definition, the members of the anonymous union are
4548        //   considered to have been defined in the scope in which the
4549        //   anonymous union is declared.
4550        unsigned OldChainingSize = Chaining.size();
4551        if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4552          Chaining.append(IF->chain_begin(), IF->chain_end());
4553        else
4554          Chaining.push_back(VD);
4555
4556        = 2", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 4556, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Chaining.size() >= 2);
4557        NamedDecl **NamedChain =
4558          new (SemaRef.Context)NamedDecl*[Chaining.size()];
4559        for (unsigned i = 0; i < Chaining.size(); i++)
4560          NamedChain[i] = Chaining[i];
4561
4562        IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4563            SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4564            VD->getType(), {NamedChain, Chaining.size()});
4565
4566        for (const auto *Attr : VD->attrs())
4567          IndirectField->addAttr(Attr->clone(SemaRef.Context));
4568
4569        IndirectField->setAccess(AS);
4570        IndirectField->setImplicit();
4571        SemaRef.PushOnScopeChains(IndirectField, S);
4572
4573        // That includes picking up the appropriate access specifier.
4574        if (AS != AS_none) IndirectField->setAccess(AS);
4575
4576        Chaining.resize(OldChainingSize);
4577      }
4578    }
4579  }
4580
4581  return Invalid;
4582}
4583
4584/// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4585/// a VarDecl::StorageClass. Any error reporting is up to the caller:
4586/// illegal input values are mapped to SC_None.
4587static StorageClass
4588StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4589  DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4590   (0) . __assert_fail ("StorageClassSpec != DeclSpec..SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 4591, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4591 (0) . __assert_fail ("StorageClassSpec != DeclSpec..SCS_typedef && \"Parser allowed 'typedef' as storage class VarDecl.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 4591, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "Parser allowed 'typedef' as storage class VarDecl.");
4592  switch (StorageClassSpec) {
4593  case DeclSpec::SCS_unspecified:    return SC_None;
4594  case DeclSpec::SCS_extern:
4595    if (DS.isExternInLinkageSpec())
4596      return SC_None;
4597    return SC_Extern;
4598  case DeclSpec::SCS_static:         return SC_Static;
4599  case DeclSpec::SCS_auto:           return SC_Auto;
4600  case DeclSpec::SCS_register:       return SC_Register;
4601  case DeclSpec::SCS_private_externreturn SC_PrivateExtern;
4602    // Illegal SCSs map to None: error reporting is up to the caller.
4603  case DeclSpec::SCS_mutable:        // Fall through.
4604  case DeclSpec::SCS_typedef:        return SC_None;
4605  }
4606  llvm_unreachable("unknown storage class specifier");
4607}
4608
4609static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4610  hasInClassInitializer()", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 4610, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Record->hasInClassInitializer());
4611
4612  for (const auto *I : Record->decls()) {
4613    const auto *FD = dyn_cast<FieldDecl>(I);
4614    if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4615      FD = IFD->getAnonField();
4616    if (FD && FD->hasInClassInitializer())
4617      return FD->getLocation();
4618  }
4619
4620  llvm_unreachable("couldn't find in-class initializer");
4621}
4622
4623static void checkDuplicateDefaultInit(Sema &SCXXRecordDecl *Parent,
4624                                      SourceLocation DefaultInitLoc) {
4625  if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4626    return;
4627
4628  S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4629  S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4630}
4631
4632static void checkDuplicateDefaultInit(Sema &SCXXRecordDecl *Parent,
4633                                      CXXRecordDecl *AnonUnion) {
4634  if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4635    return;
4636
4637  checkDuplicateDefaultInit(SParentfindDefaultInitializer(AnonUnion));
4638}
4639
4640/// BuildAnonymousStructOrUnion - Handle the declaration of an
4641/// anonymous structure or union. Anonymous unions are a C++ feature
4642/// (C++ [class.union]) and a C11 feature; anonymous structures
4643/// are a C11 feature and GNU C++ extension.
4644Decl *Sema::BuildAnonymousStructOrUnion(Scope *SDeclSpec &DS,
4645                                        AccessSpecifier AS,
4646                                        RecordDecl *Record,
4647                                        const PrintingPolicy &Policy) {
4648  DeclContext *Owner = Record->getDeclContext();
4649
4650  // Diagnose whether this anonymous struct/union is an extension.
4651  if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4652    Diag(Record->getLocation(), diag::ext_anonymous_union);
4653  else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4654    Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4655  else if (!Record->isUnion() && !getLangOpts().C11)
4656    Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4657
4658  // C and C++ require different kinds of checks for anonymous
4659  // structs/unions.
4660  bool Invalid = false;
4661  if (getLangOpts().CPlusPlus) {
4662    const char *PrevSpec = nullptr;
4663    unsigned DiagID;
4664    if (Record->isUnion()) {
4665      // C++ [class.union]p6:
4666      // C++17 [class.union.anon]p2:
4667      //   Anonymous unions declared in a named namespace or in the
4668      //   global namespace shall be declared static.
4669      DeclContext *OwnerScope = Owner->getRedeclContext();
4670      if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4671          (OwnerScope->isTranslationUnit() ||
4672           (OwnerScope->isNamespace() &&
4673            !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
4674        Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4675          << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4676
4677        // Recover by adding 'static'.
4678        DS.SetStorageClassSpec(*thisDeclSpec::SCS_staticSourceLocation(),
4679                               PrevSpecDiagIDPolicy);
4680      }
4681      // C++ [class.union]p6:
4682      //   A storage class is not allowed in a declaration of an
4683      //   anonymous union in a class scope.
4684      else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4685               isa<RecordDecl>(Owner)) {
4686        Diag(DS.getStorageClassSpecLoc(),
4687             diag::err_anonymous_union_with_storage_spec)
4688          << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4689
4690        // Recover by removing the storage specifier.
4691        DS.SetStorageClassSpec(*thisDeclSpec::SCS_unspecified,
4692                               SourceLocation(),
4693                               PrevSpecDiagIDContext.getPrintingPolicy());
4694      }
4695    }
4696
4697    // Ignore const/volatile/restrict qualifiers.
4698    if (DS.getTypeQualifiers()) {
4699      if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4700        Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4701          << Record->isUnion() << "const"
4702          << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4703      if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4704        Diag(DS.getVolatileSpecLoc(),
4705             diag::ext_anonymous_struct_union_qualified)
4706          << Record->isUnion() << "volatile"
4707          << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4708      if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4709        Diag(DS.getRestrictSpecLoc(),
4710             diag::ext_anonymous_struct_union_qualified)
4711          << Record->isUnion() << "restrict"
4712          << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4713      if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4714        Diag(DS.getAtomicSpecLoc(),
4715             diag::ext_anonymous_struct_union_qualified)
4716          << Record->isUnion() << "_Atomic"
4717          << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4718      if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4719        Diag(DS.getUnalignedSpecLoc(),
4720             diag::ext_anonymous_struct_union_qualified)
4721          << Record->isUnion() << "__unaligned"
4722          << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4723
4724      DS.ClearTypeQualifiers();
4725    }
4726
4727    // C++ [class.union]p2:
4728    //   The member-specification of an anonymous union shall only
4729    //   define non-static data members. [Note: nested types and
4730    //   functions cannot be declared within an anonymous union. ]
4731    for (auto *Mem : Record->decls()) {
4732      if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4733        // C++ [class.union]p3:
4734        //   An anonymous union shall not have private or protected
4735        //   members (clause 11).
4736        getAccess() != AS_none", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 4736, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(FD->getAccess() != AS_none);
4737        if (FD->getAccess() != AS_public) {
4738          Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4739            << Record->isUnion() << (FD->getAccess() == AS_protected);
4740          Invalid = true;
4741        }
4742
4743        // C++ [class.union]p1
4744        //   An object of a class with a non-trivial constructor, a non-trivial
4745        //   copy constructor, a non-trivial destructor, or a non-trivial copy
4746        //   assignment operator cannot be a member of a union, nor can an
4747        //   array of such objects.
4748        if (CheckNontrivialField(FD))
4749          Invalid = true;
4750      } else if (Mem->isImplicit()) {
4751        // Any implicit members are fine.
4752      } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4753        // This is a type that showed up in an
4754        // elaborated-type-specifier inside the anonymous struct or
4755        // union, but which actually declares a type outside of the
4756        // anonymous struct or union. It's okay.
4757      } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4758        if (!MemRecord->isAnonymousStructOrUnion() &&
4759            MemRecord->getDeclName()) {
4760          // Visual C++ allows type definition in anonymous struct or union.
4761          if (getLangOpts().MicrosoftExt)
4762            Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4763              << Record->isUnion();
4764          else {
4765            // This is a nested type declaration.
4766            Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4767              << Record->isUnion();
4768            Invalid = true;
4769          }
4770        } else {
4771          // This is an anonymous type definition within another anonymous type.
4772          // This is a popular extension, provided by Plan9, MSVC and GCC, but
4773          // not part of standard C++.
4774          Diag(MemRecord->getLocation(),
4775               diag::ext_anonymous_record_with_anonymous_type)
4776            << Record->isUnion();
4777        }
4778      } else if (isa<AccessSpecDecl>(Mem)) {
4779        // Any access specifier is fine.
4780      } else if (isa<StaticAssertDecl>(Mem)) {
4781        // In C++1z, static_assert declarations are also fine.
4782      } else {
4783        // We have something that isn't a non-static data
4784        // member. Complain about it.
4785        unsigned DK = diag::err_anonymous_record_bad_member;
4786        if (isa<TypeDecl>(Mem))
4787          DK = diag::err_anonymous_record_with_type;
4788        else if (isa<FunctionDecl>(Mem))
4789          DK = diag::err_anonymous_record_with_function;
4790        else if (isa<VarDecl>(Mem))
4791          DK = diag::err_anonymous_record_with_static;
4792
4793        // Visual C++ allows type definition in anonymous struct or union.
4794        if (getLangOpts().MicrosoftExt &&
4795            DK == diag::err_anonymous_record_with_type)
4796          Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4797            << Record->isUnion();
4798        else {
4799          Diag(Mem->getLocation(), DK) << Record->isUnion();
4800          Invalid = true;
4801        }
4802      }
4803    }
4804
4805    // C++11 [class.union]p8 (DR1460):
4806    //   At most one variant member of a union may have a
4807    //   brace-or-equal-initializer.
4808    if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4809        Owner->isRecord())
4810      checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4811                                cast<CXXRecordDecl>(Record));
4812  }
4813
4814  if (!Record->isUnion() && !Owner->isRecord()) {
4815    Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4816      << getLangOpts().CPlusPlus;
4817    Invalid = true;
4818  }
4819
4820  // Mock up a declarator.
4821  Declarator Dc(DSDeclaratorContext::MemberContext);
4822  TypeSourceInfo *TInfo = GetTypeForDeclarator(DcS);
4823   (0) . __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct/union\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 4823, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4824
4825  // Create a declaration for this anonymous struct/union.
4826  NamedDecl *Anon = nullptr;
4827  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4828    Anon = FieldDecl::Create(
4829        ContextOwningClassDS.getBeginLoc(), Record->getLocation(),
4830        /*IdentifierInfo=*/nullptrContext.getTypeDeclType(Record), TInfo,
4831        /*BitWidth=*/nullptr/*Mutable=*/false,
4832        /*InitStyle=*/ICIS_NoInit);
4833    Anon->setAccess(AS);
4834    if (getLangOpts().CPlusPlus)
4835      FieldCollector->Add(cast<FieldDecl>(Anon));
4836  } else {
4837    DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4838    StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4839    if (SCSpec == DeclSpec::SCS_mutable) {
4840      // mutable can only appear on non-static class members, so it's always
4841      // an error here
4842      Diag(Record->getLocation(), diag::err_mutable_nonmember);
4843      Invalid = true;
4844      SC = SC_None;
4845    }
4846
4847    Anon = VarDecl::Create(ContextOwnerDS.getBeginLoc(),
4848                           Record->getLocation(), /*IdentifierInfo=*/nullptr,
4849                           Context.getTypeDeclType(Record), TInfoSC);
4850
4851    // Default-initialize the implicit variable. This initialization will be
4852    // trivial in almost all cases, except if a union member has an in-class
4853    // initializer:
4854    //   union { int n = 0; };
4855    ActOnUninitializedDecl(Anon);
4856  }
4857  Anon->setImplicit();
4858
4859  // Mark this as an anonymous struct/union type.
4860  Record->setAnonymousStructOrUnion(true);
4861
4862  // Add the anonymous struct/union object to the current
4863  // context. We'll be referencing this object when we refer to one of
4864  // its members.
4865  Owner->addDecl(Anon);
4866
4867  // Inject the members of the anonymous struct/union into the owning
4868  // context and into the identifier resolver chain for name lookup
4869  // purposes.
4870  SmallVector<NamedDecl*, 2Chain;
4871  Chain.push_back(Anon);
4872
4873  if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4874    Invalid = true;
4875
4876  if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4877    if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4878      Decl *ManglingContextDecl;
4879      if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4880              NewVD->getDeclContext(), ManglingContextDecl)) {
4881        Context.setManglingNumber(
4882            NewVDMCtx->getManglingNumber(
4883                       NewVDgetMSManglingNumber(getLangOpts(), S)));
4884        Context.setStaticLocalNumber(NewVDMCtx->getStaticLocalNumber(NewVD));
4885      }
4886    }
4887  }
4888
4889  if (Invalid)
4890    Anon->setInvalidDecl();
4891
4892  return Anon;
4893}
4894
4895/// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4896/// Microsoft C anonymous structure.
4897/// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4898/// Example:
4899///
4900/// struct A { int a; };
4901/// struct B { struct A; int b; };
4902///
4903/// void foo() {
4904///   B var;
4905///   var.a = 3;
4906/// }
4907///
4908Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *SDeclSpec &DS,
4909                                           RecordDecl *Record) {
4910   (0) . __assert_fail ("Record && \"expected a record!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 4910, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Record && "expected a record!");
4911
4912  // Mock up a declarator.
4913  Declarator Dc(DSDeclaratorContext::TypeNameContext);
4914  TypeSourceInfo *TInfo = GetTypeForDeclarator(DcS);
4915   (0) . __assert_fail ("TInfo && \"couldn't build declarator info for anonymous struct\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 4915, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(TInfo && "couldn't build declarator info for anonymous struct");
4916
4917  auto *ParentDecl = cast<RecordDecl>(CurContext);
4918  QualType RecTy = Context.getTypeDeclType(Record);
4919
4920  // Create a declaration for this anonymous struct.
4921  NamedDecl *Anon =
4922      FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
4923                        /*IdentifierInfo=*/nullptr, RecTy, TInfo,
4924                        /*BitWidth=*/nullptr/*Mutable=*/false,
4925                        /*InitStyle=*/ICIS_NoInit);
4926  Anon->setImplicit();
4927
4928  // Add the anonymous struct object to the current context.
4929  CurContext->addDecl(Anon);
4930
4931  // Inject the members of the anonymous struct into the current
4932  // context and into the identifier resolver chain for name lookup
4933  // purposes.
4934  SmallVector<NamedDecl*, 2Chain;
4935  Chain.push_back(Anon);
4936
4937  RecordDecl *RecordDef = Record->getDefinition();
4938  if (RequireCompleteType(Anon->getLocation(), RecTy,
4939                          diag::err_field_incomplete) ||
4940      InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4941                                          AS_none, Chain)) {
4942    Anon->setInvalidDecl();
4943    ParentDecl->setInvalidDecl();
4944  }
4945
4946  return Anon;
4947}
4948
4949/// GetNameForDeclarator - Determine the full declaration name for the
4950/// given Declarator.
4951DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4952  return GetNameFromUnqualifiedId(D.getName());
4953}
4954
4955/// Retrieves the declaration name from a parsed unqualified-id.
4956DeclarationNameInfo
4957Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4958  DeclarationNameInfo NameInfo;
4959  NameInfo.setLoc(Name.StartLocation);
4960
4961  switch (Name.getKind()) {
4962
4963  case UnqualifiedIdKind::IK_ImplicitSelfParam:
4964  case UnqualifiedIdKind::IK_Identifier:
4965    NameInfo.setName(Name.Identifier);
4966    return NameInfo;
4967
4968  case UnqualifiedIdKind::IK_DeductionGuideName: {
4969    // C++ [temp.deduct.guide]p3:
4970    //   The simple-template-id shall name a class template specialization.
4971    //   The template-name shall be the same identifier as the template-name
4972    //   of the simple-template-id.
4973    // These together intend to imply that the template-name shall name a
4974    // class template.
4975    // FIXME: template<typename T> struct X {};
4976    //        template<typename T> using Y = X<T>;
4977    //        Y(int) -> Y<int>;
4978    //   satisfies these rules but does not name a class template.
4979    TemplateName TN = Name.TemplateName.get().get();
4980    auto *Template = TN.getAsTemplateDecl();
4981    if (!Template || !isa<ClassTemplateDecl>(Template)) {
4982      Diag(Name.StartLocation,
4983           diag::err_deduction_guide_name_not_class_template)
4984        << (int)getTemplateNameKindForDiagnostics(TN) << TN;
4985      if (Template)
4986        Diag(Template->getLocation(), diag::note_template_decl_here);
4987      return DeclarationNameInfo();
4988    }
4989
4990    NameInfo.setName(
4991        Context.DeclarationNames.getCXXDeductionGuideName(Template));
4992    return NameInfo;
4993  }
4994
4995  case UnqualifiedIdKind::IK_OperatorFunctionId:
4996    NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4997                                           Name.OperatorFunctionId.Operator));
4998    NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4999      = Name.OperatorFunctionId.SymbolLocations[0];
5000    NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
5001      = Name.EndLocation.getRawEncoding();
5002    return NameInfo;
5003
5004  case UnqualifiedIdKind::IK_LiteralOperatorId:
5005    NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
5006                                                           Name.Identifier));
5007    NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5008    return NameInfo;
5009
5010  case UnqualifiedIdKind::IK_ConversionFunctionId: {
5011    TypeSourceInfo *TInfo;
5012    QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5013    if (Ty.isNull())
5014      return DeclarationNameInfo();
5015    NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
5016                                               Context.getCanonicalType(Ty)));
5017    NameInfo.setNamedTypeInfo(TInfo);
5018    return NameInfo;
5019  }
5020
5021  case UnqualifiedIdKind::IK_ConstructorName: {
5022    TypeSourceInfo *TInfo;
5023    QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5024    if (Ty.isNull())
5025      return DeclarationNameInfo();
5026    NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5027                                              Context.getCanonicalType(Ty)));
5028    NameInfo.setNamedTypeInfo(TInfo);
5029    return NameInfo;
5030  }
5031
5032  case UnqualifiedIdKind::IK_ConstructorTemplateId: {
5033    // In well-formed code, we can only have a constructor
5034    // template-id that refers to the current context, so go there
5035    // to find the actual type being constructed.
5036    CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5037    if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5038      return DeclarationNameInfo();
5039
5040    // Determine the type of the class being constructed.
5041    QualType CurClassType = Context.getTypeDeclType(CurClass);
5042
5043    // FIXME: Check two things: that the template-id names the same type as
5044    // CurClassType, and that the template-id does not occur when the name
5045    // was qualified.
5046
5047    NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
5048                                    Context.getCanonicalType(CurClassType)));
5049    // FIXME: should we retrieve TypeSourceInfo?
5050    NameInfo.setNamedTypeInfo(nullptr);
5051    return NameInfo;
5052  }
5053
5054  case UnqualifiedIdKind::IK_DestructorName: {
5055    TypeSourceInfo *TInfo;
5056    QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5057    if (Ty.isNull())
5058      return DeclarationNameInfo();
5059    NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
5060                                              Context.getCanonicalType(Ty)));
5061    NameInfo.setNamedTypeInfo(TInfo);
5062    return NameInfo;
5063  }
5064
5065  case UnqualifiedIdKind::IK_TemplateId: {
5066    TemplateName TName = Name.TemplateId->Template.get();
5067    SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5068    return Context.getNameForTemplate(TNameTNameLoc);
5069  }
5070
5071  } // switch (Name.getKind())
5072
5073  llvm_unreachable("Unknown name kind");
5074}
5075
5076static QualType getCoreType(QualType Ty) {
5077  do {
5078    if (Ty->isPointerType() || Ty->isReferenceType())
5079      Ty = Ty->getPointeeType();
5080    else if (Ty->isArrayType())
5081      Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5082    else
5083      return Ty.withoutLocalFastQualifiers();
5084  } while (true);
5085}
5086
5087/// hasSimilarParameters - Determine whether the C++ functions Declaration
5088/// and Definition have "nearly" matching parameters. This heuristic is
5089/// used to improve diagnostics in the case where an out-of-line function
5090/// definition doesn't match any declaration within the class or namespace.
5091/// Also sets Params to the list of indices to the parameters that differ
5092/// between the declaration and the definition. If hasSimilarParameters
5093/// returns true and Params is empty, then all of the parameters match.
5094static bool hasSimilarParameters(ASTContext &Context,
5095                                     FunctionDecl *Declaration,
5096                                     FunctionDecl *Definition,
5097                                     SmallVectorImpl<unsigned> &Params) {
5098  Params.clear();
5099  if (Declaration->param_size() != Definition->param_size())
5100    return false;
5101  for (unsigned Idx = 0Idx < Declaration->param_size(); ++Idx) {
5102    QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5103    QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5104
5105    // The parameter types are identical
5106    if (Context.hasSameUnqualifiedType(DefParamTyDeclParamTy))
5107      continue;
5108
5109    QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5110    QualType DefParamBaseTy = getCoreType(DefParamTy);
5111    const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5112    const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5113
5114    if (Context.hasSameUnqualifiedType(DeclParamBaseTyDefParamBaseTy) ||
5115        (DeclTyName && DeclTyName == DefTyName))
5116      Params.push_back(Idx);
5117    else  // The two parameters aren't even close
5118      return false;
5119  }
5120
5121  return true;
5122}
5123
5124/// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5125/// declarator needs to be rebuilt in the current instantiation.
5126/// Any bits of declarator which appear before the name are valid for
5127/// consideration here.  That's specifically the type in the decl spec
5128/// and the base type in any member-pointer chunks.
5129static bool RebuildDeclaratorInCurrentInstantiation(Sema &SDeclarator &D,
5130                                                    DeclarationName Name) {
5131  // The types we specifically need to rebuild are:
5132  //   - typenames, typeofs, and decltypes
5133  //   - types which will become injected class names
5134  // Of course, we also need to rebuild any type referencing such a
5135  // type.  It's safest to just say "dependent", but we call out a
5136  // few cases here.
5137
5138  DeclSpec &DS = D.getMutableDeclSpec();
5139  switch (DS.getTypeSpecType()) {
5140  case DeclSpec::TST_typename:
5141  case DeclSpec::TST_typeofType:
5142  case DeclSpec::TST_underlyingType:
5143  case DeclSpec::TST_atomic: {
5144    // Grab the type from the parser.
5145    TypeSourceInfo *TSI = nullptr;
5146    QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5147    if (T.isNull() || !T->isDependentType()) break;
5148
5149    // Make sure there's a type source info.  This isn't really much
5150    // of a waste; most dependent types should have type source info
5151    // attached already.
5152    if (!TSI)
5153      TSI = S.Context.getTrivialTypeSourceInfo(TDS.getTypeSpecTypeLoc());
5154
5155    // Rebuild the type in the current instantiation.
5156    TSI = S.RebuildTypeInCurrentInstantiation(TSID.getIdentifierLoc(), Name);
5157    if (!TSIreturn true;
5158
5159    // Store the new type back in the decl spec.
5160    ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5161    DS.UpdateTypeRep(LocType);
5162    break;
5163  }
5164
5165  case DeclSpec::TST_decltype:
5166  case DeclSpec::TST_typeofExpr: {
5167    Expr *E = DS.getRepAsExpr();
5168    ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
5169    if (Result.isInvalid()) return true;
5170    DS.UpdateExprRep(Result.get());
5171    break;
5172  }
5173
5174  default:
5175    // Nothing to do for these decl specs.
5176    break;
5177  }
5178
5179  // It doesn't matter what order we do this in.
5180  for (unsigned I = 0E = D.getNumTypeObjects(); I != E; ++I) {
5181    DeclaratorChunk &Chunk = D.getTypeObject(I);
5182
5183    // The only type information in the declarator which can come
5184    // before the declaration name is the base type of a member
5185    // pointer.
5186    if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5187      continue;
5188
5189    // Rebuild the scope specifier in-place.
5190    CXXScopeSpec &SS = Chunk.Mem.Scope();
5191    if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
5192      return true;
5193  }
5194
5195  return false;
5196}
5197
5198Decl *Sema::ActOnDeclarator(Scope *SDeclarator &D) {
5199  D.setFunctionDefinitionKind(FDK_Declaration);
5200  Decl *Dcl = HandleDeclarator(SD, MultiTemplateParamsArg());
5201
5202  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5203      Dcl && Dcl->getDeclContext()->isFileContext())
5204    Dcl->setTopLevelDeclInObjCContainer();
5205
5206  if (getLangOpts().OpenCL)
5207    setCurrentOpenCLExtensionForDecl(Dcl);
5208
5209  return Dcl;
5210}
5211
5212/// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5213///   If T is the name of a class, then each of the following shall have a
5214///   name different from T:
5215///     - every static data member of class T;
5216///     - every member function of class T
5217///     - every member of class T that is itself a type;
5218/// \returns true if the declaration name violates these rules.
5219bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
5220                                   DeclarationNameInfo NameInfo) {
5221  DeclarationName Name = NameInfo.getName();
5222
5223  CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5224  while (Record && Record->isAnonymousStructOrUnion())
5225    Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5226  if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5227    Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5228    return true;
5229  }
5230
5231  return false;
5232}
5233
5234/// Diagnose a declaration whose declarator-id has the given
5235/// nested-name-specifier.
5236///
5237/// \param SS The nested-name-specifier of the declarator-id.
5238///
5239/// \param DC The declaration context to which the nested-name-specifier
5240/// resolves.
5241///
5242/// \param Name The name of the entity being declared.
5243///
5244/// \param Loc The location of the name of the entity being declared.
5245///
5246/// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5247/// we're declaring an explicit / partial specialization / instantiation.
5248///
5249/// \returns true if we cannot safely recover from this error, false otherwise.
5250bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SSDeclContext *DC,
5251                                        DeclarationName Name,
5252                                        SourceLocation Locbool IsTemplateId) {
5253  DeclContext *Cur = CurContext;
5254  while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5255    Cur = Cur->getParent();
5256
5257  // If the user provided a superfluous scope specifier that refers back to the
5258  // class in which the entity is already declared, diagnose and ignore it.
5259  //
5260  // class X {
5261  //   void X::f();
5262  // };
5263  //
5264  // Note, it was once ill-formed to give redundant qualification in all
5265  // contexts, but that rule was removed by DR482.
5266  if (Cur->Equals(DC)) {
5267    if (Cur->isRecord()) {
5268      Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5269                                      : diag::err_member_extra_qualification)
5270        << Name << FixItHint::CreateRemoval(SS.getRange());
5271      SS.clear();
5272    } else {
5273      Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5274    }
5275    return false;
5276  }
5277
5278  // Check whether the qualifying scope encloses the scope of the original
5279  // declaration. For a template-id, we perform the checks in
5280  // CheckTemplateSpecializationScope.
5281  if (!Cur->Encloses(DC) && !IsTemplateId) {
5282    if (Cur->isRecord())
5283      Diag(Loc, diag::err_member_qualification)
5284        << Name << SS.getRange();
5285    else if (isa<TranslationUnitDecl>(DC))
5286      Diag(Loc, diag::err_invalid_declarator_global_scope)
5287        << Name << SS.getRange();
5288    else if (isa<FunctionDecl>(Cur))
5289      Diag(Loc, diag::err_invalid_declarator_in_function)
5290        << Name << SS.getRange();
5291    else if (isa<BlockDecl>(Cur))
5292      Diag(Loc, diag::err_invalid_declarator_in_block)
5293        << Name << SS.getRange();
5294    else
5295      Diag(Loc, diag::err_invalid_declarator_scope)
5296      << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5297
5298    return true;
5299  }
5300
5301  if (Cur->isRecord()) {
5302    // Cannot qualify members within a class.
5303    Diag(Loc, diag::err_member_qualification)
5304      << Name << SS.getRange();
5305    SS.clear();
5306
5307    // C++ constructors and destructors with incorrect scopes can break
5308    // our AST invariants by having the wrong underlying types. If
5309    // that's the case, then drop this declaration entirely.
5310    if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5311         Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5312        !Context.hasSameType(Name.getCXXNameType(),
5313                             Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5314      return true;
5315
5316    return false;
5317  }
5318
5319  // C++11 [dcl.meaning]p1:
5320  //   [...] "The nested-name-specifier of the qualified declarator-id shall
5321  //   not begin with a decltype-specifer"
5322  NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5323  while (SpecLoc.getPrefix())
5324    SpecLoc = SpecLoc.getPrefix();
5325  if (dyn_cast_or_null<DecltypeType>(
5326        SpecLoc.getNestedNameSpecifier()->getAsType()))
5327    Diag(Loc, diag::err_decltype_in_declarator)
5328      << SpecLoc.getTypeLoc().getSourceRange();
5329
5330  return false;
5331}
5332
5333NamedDecl *Sema::HandleDeclarator(Scope *SDeclarator &D,
5334                                  MultiTemplateParamsArg TemplateParamLists) {
5335  // TODO: consider using NameInfo for diagnostic.
5336  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5337  DeclarationName Name = NameInfo.getName();
5338
5339  // All of these full declarators require an identifier.  If it doesn't have
5340  // one, the ParsedFreeStandingDeclSpec action should be used.
5341  if (D.isDecompositionDeclarator()) {
5342    return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5343  } else if (!Name) {
5344    if (!D.isInvalidType())  // Reject this if we think it is valid.
5345      Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5346          << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5347    return nullptr;
5348  } else if (DiagnoseUnexpandedParameterPack(NameInfoUPPC_DeclarationType))
5349    return nullptr;
5350
5351  // The scope passed in may not be a decl scope.  Zip up the scope tree until
5352  // we find one that is.
5353  while ((S->getFlags() & Scope::DeclScope) == 0 ||
5354         (S->getFlags() & Scope::TemplateParamScope) != 0)
5355    S = S->getParent();
5356
5357  DeclContext *DC = CurContext;
5358  if (D.getCXXScopeSpec().isInvalid())
5359    D.setInvalidType();
5360  else if (D.getCXXScopeSpec().isSet()) {
5361    if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5362                                        UPPC_DeclarationQualifier))
5363      return nullptr;
5364
5365    bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5366    DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5367    if (!DC || isa<EnumDecl>(DC)) {
5368      // If we could not compute the declaration context, it's because the
5369      // declaration context is dependent but does not refer to a class,
5370      // class template, or class template partial specialization. Complain
5371      // and return early, to avoid the coming semantic disaster.
5372      Diag(D.getIdentifierLoc(),
5373           diag::err_template_qualified_declarator_no_match)
5374        << D.getCXXScopeSpec().getScopeRep()
5375        << D.getCXXScopeSpec().getRange();
5376      return nullptr;
5377    }
5378    bool IsDependentContext = DC->isDependentContext();
5379
5380    if (!IsDependentContext &&
5381        RequireCompleteDeclContext(D.getCXXScopeSpec()DC))
5382      return nullptr;
5383
5384    // If a class is incomplete, do not parse entities inside it.
5385    if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5386      Diag(D.getIdentifierLoc(),
5387           diag::err_member_def_undefined_record)
5388        << Name << DC << D.getCXXScopeSpec().getRange();
5389      return nullptr;
5390    }
5391    if (!D.getDeclSpec().isFriendSpecified()) {
5392      if (diagnoseQualifiedDeclaration(
5393              D.getCXXScopeSpec()DCNameD.getIdentifierLoc(),
5394              D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId)) {
5395        if (DC->isRecord())
5396          return nullptr;
5397
5398        D.setInvalidType();
5399      }
5400    }
5401
5402    // Check whether we need to rebuild the type of the given
5403    // declaration in the current instantiation.
5404    if (EnteringContext && IsDependentContext &&
5405        TemplateParamLists.size() != 0) {
5406      ContextRAII SavedContext(*thisDC);
5407      if (RebuildDeclaratorInCurrentInstantiation(*thisDName))
5408        D.setInvalidType();
5409    }
5410  }
5411
5412  TypeSourceInfo *TInfo = GetTypeForDeclarator(DS);
5413  QualType R = TInfo->getType();
5414
5415  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5416                                      UPPC_DeclarationType))
5417    D.setInvalidType();
5418
5419  LookupResult Previous(*thisNameInfoLookupOrdinaryName,
5420                        forRedeclarationInCurContext());
5421
5422  // See if this is a redefinition of a variable in the same scope.
5423  if (!D.getCXXScopeSpec().isSet()) {
5424    bool IsLinkageLookup = false;
5425    bool CreateBuiltins = false;
5426
5427    // If the declaration we're planning to build will be a function
5428    // or object with linkage, then look for another declaration with
5429    // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5430    //
5431    // If the declaration we're planning to build will be declared with
5432    // external linkage in the translation unit, create any builtin with
5433    // the same name.
5434    if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5435      /* Do nothing*/;
5436    else if (CurContext->isFunctionOrMethod() &&
5437             (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5438              R->isFunctionType())) {
5439      IsLinkageLookup = true;
5440      CreateBuiltins =
5441          CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5442    } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5443               D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5444      CreateBuiltins = true;
5445
5446    if (IsLinkageLookup) {
5447      Previous.clear(LookupRedeclarationWithLinkage);
5448      Previous.setRedeclarationKind(ForExternalRedeclaration);
5449    }
5450
5451    LookupName(PreviousSCreateBuiltins);
5452  } else { // Something like "int foo::x;"
5453    LookupQualifiedName(PreviousDC);
5454
5455    // C++ [dcl.meaning]p1:
5456    //   When the declarator-id is qualified, the declaration shall refer to a
5457    //  previously declared member of the class or namespace to which the
5458    //  qualifier refers (or, in the case of a namespace, of an element of the
5459    //  inline namespace set of that namespace (7.3.1)) or to a specialization
5460    //  thereof; [...]
5461    //
5462    // Note that we already checked the context above, and that we do not have
5463    // enough information to make sure that Previous contains the declaration
5464    // we want to match. For example, given:
5465    //
5466    //   class X {
5467    //     void f();
5468    //     void f(float);
5469    //   };
5470    //
5471    //   void X::f(int) { } // ill-formed
5472    //
5473    // In this case, Previous will point to the overload set
5474    // containing the two f's declared in X, but neither of them
5475    // matches.
5476
5477    // C++ [dcl.meaning]p1:
5478    //   [...] the member shall not merely have been introduced by a
5479    //   using-declaration in the scope of the class or namespace nominated by
5480    //   the nested-name-specifier of the declarator-id.
5481    RemoveUsingDecls(Previous);
5482  }
5483
5484  if (Previous.isSingleResult() &&
5485      Previous.getFoundDecl()->isTemplateParameter()) {
5486    // Maybe we will complain about the shadowed template parameter.
5487    if (!D.isInvalidType())
5488      DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5489                                      Previous.getFoundDecl());
5490
5491    // Just pretend that we didn't see the previous declaration.
5492    Previous.clear();
5493  }
5494
5495  if (!R->isFunctionType() && DiagnoseClassNameShadow(DCNameInfo))
5496    // Forget that the previous declaration is the injected-class-name.
5497    Previous.clear();
5498
5499  // In C++, the previous declaration we find might be a tag type
5500  // (class or enum). In this case, the new declaration will hide the
5501  // tag type. Note that this applies to functions, function templates, and
5502  // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
5503  if (Previous.isSingleTagDecl() &&
5504      D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
5505      (TemplateParamLists.size() == 0 || R->isFunctionType()))
5506    Previous.clear();
5507
5508  // Check that there are no default arguments other than in the parameters
5509  // of a function declaration (C++ only).
5510  if (getLangOpts().CPlusPlus)
5511    CheckExtraCXXDefaultArguments(D);
5512
5513  NamedDecl *New;
5514
5515  bool AddToScope = true;
5516  if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5517    if (TemplateParamLists.size()) {
5518      Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5519      return nullptr;
5520    }
5521
5522    New = ActOnTypedefDeclarator(SDDCTInfoPrevious);
5523  } else if (R->isFunctionType()) {
5524    New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5525                                  TemplateParamLists,
5526                                  AddToScope);
5527  } else {
5528    New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5529                                  AddToScope);
5530  }
5531
5532  if (!New)
5533    return nullptr;
5534
5535  // If this has an identifier and is not a function template specialization,
5536  // add it to the scope stack.
5537  if (New->getDeclName() && AddToScope)
5538    PushOnScopeChains(NewS);
5539
5540  if (isInOpenMPDeclareTargetContext())
5541    checkDeclIsAllowedInOpenMPTarget(nullptrNew);
5542
5543  return New;
5544}
5545
5546/// Helper method to turn variable array types into constant array
5547/// types in certain situations which would otherwise be errors (for
5548/// GCC compatibility).
5549static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5550                                                    ASTContext &Context,
5551                                                    bool &SizeIsNegative,
5552                                                    llvm::APSInt &Oversized) {
5553  // This method tries to turn a variable array into a constant
5554  // array even when the size isn't an ICE.  This is necessary
5555  // for compatibility with code that depends on gcc's buggy
5556  // constant expression folding, like struct {char x[(int)(char*)2];}
5557  SizeIsNegative = false;
5558  Oversized = 0;
5559
5560  if (T->isDependentType())
5561    return QualType();
5562
5563  QualifierCollector Qs;
5564  const Type *Ty = Qs.strip(T);
5565
5566  if (const PointerTypePTy = dyn_cast<PointerType>(Ty)) {
5567    QualType Pointee = PTy->getPointeeType();
5568    QualType FixedType =
5569        TryToFixInvalidVariablyModifiedType(PointeeContextSizeIsNegative,
5570                                            Oversized);
5571    if (FixedType.isNull()) return FixedType;
5572    FixedType = Context.getPointerType(FixedType);
5573    return Qs.apply(ContextFixedType);
5574  }
5575  if (const ParenTypePTy = dyn_cast<ParenType>(Ty)) {
5576    QualType Inner = PTy->getInnerType();
5577    QualType FixedType =
5578        TryToFixInvalidVariablyModifiedType(InnerContextSizeIsNegative,
5579                                            Oversized);
5580    if (FixedType.isNull()) return FixedType;
5581    FixedType = Context.getParenType(FixedType);
5582    return Qs.apply(ContextFixedType);
5583  }
5584
5585  const VariableArrayTypeVLATy = dyn_cast<VariableArrayType>(T);
5586  if (!VLATy)
5587    return QualType();
5588  // FIXME: We should probably handle this case
5589  if (VLATy->getElementType()->isVariablyModifiedType())
5590    return QualType();
5591
5592  Expr::EvalResult Result;
5593  if (!VLATy->getSizeExpr() ||
5594      !VLATy->getSizeExpr()->EvaluateAsInt(ResultContext))
5595    return QualType();
5596
5597  llvm::APSInt Res = Result.Val.getInt();
5598
5599  // Check whether the array size is negative.
5600  if (Res.isSigned() && Res.isNegative()) {
5601    SizeIsNegative = true;
5602    return QualType();
5603  }
5604
5605  // Check whether the array is too large to be addressed.
5606  unsigned ActiveSizeBits
5607    = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5608                                              Res);
5609  if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5610    Oversized = Res;
5611    return QualType();
5612  }
5613
5614  return Context.getConstantArrayType(VLATy->getElementType(),
5615                                      Res, ArrayType::Normal, 0);
5616}
5617
5618static void
5619FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTLTypeLoc DstTL) {
5620  SrcTL = SrcTL.getUnqualifiedLoc();
5621  DstTL = DstTL.getUnqualifiedLoc();
5622  if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5623    PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5624    FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5625                                      DstPTL.getPointeeLoc());
5626    DstPTL.setStarLoc(SrcPTL.getStarLoc());
5627    return;
5628  }
5629  if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5630    ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5631    FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5632                                      DstPTL.getInnerLoc());
5633    DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5634    DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5635    return;
5636  }
5637  ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5638  ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5639  TypeLoc SrcElemTL = SrcATL.getElementLoc();
5640  TypeLoc DstElemTL = DstATL.getElementLoc();
5641  DstElemTL.initializeFullCopy(SrcElemTL);
5642  DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5643  DstATL.setSizeExpr(SrcATL.getSizeExpr());
5644  DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5645}
5646
5647/// Helper method to turn variable array types into constant array
5648/// types in certain situations which would otherwise be errors (for
5649/// GCC compatibility).
5650static TypeSourceInfo*
5651TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5652                                              ASTContext &Context,
5653                                              bool &SizeIsNegative,
5654                                              llvm::APSInt &Oversized) {
5655  QualType FixedTy
5656    = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5657                                          SizeIsNegativeOversized);
5658  if (FixedTy.isNull())
5659    return nullptr;
5660  TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5661  FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5662                                    FixedTInfo->getTypeLoc());
5663  return FixedTInfo;
5664}
5665
5666/// Register the given locally-scoped extern "C" declaration so
5667/// that it can be found later for redeclarations. We include any extern "C"
5668/// declaration that is not visible in the translation unit here, not just
5669/// function-scope declarations.
5670void
5671Sema::RegisterLocallyScopedExternCDecl(NamedDecl *NDScope *S) {
5672  if (!getLangOpts().CPlusPlus &&
5673      ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5674    // Don't need to track declarations in the TU in C.
5675    return;
5676
5677  // Note that we have a locally-scoped external with this name.
5678  Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5679}
5680
5681NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5682  // FIXME: We can have multiple results via __attribute__((overloadable)).
5683  auto Result = Context.getExternCContextDecl()->lookup(Name);
5684  return Result.empty() ? nullptr : *Result.begin();
5685}
5686
5687/// Diagnose function specifiers on a declaration of an identifier that
5688/// does not identify a function.
5689void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5690  // FIXME: We should probably indicate the identifier in question to avoid
5691  // confusion for constructs like "virtual int a(), b;"
5692  if (DS.isVirtualSpecified())
5693    Diag(DS.getVirtualSpecLoc(),
5694         diag::err_virtual_non_function);
5695
5696  if (DS.isExplicitSpecified())
5697    Diag(DS.getExplicitSpecLoc(),
5698         diag::err_explicit_non_function);
5699
5700  if (DS.isNoreturnSpecified())
5701    Diag(DS.getNoreturnSpecLoc(),
5702         diag::err_noreturn_non_function);
5703}
5704
5705NamedDecl*
5706Sema::ActOnTypedefDeclarator(ScopeSDeclaratorDDeclContextDC,
5707                             TypeSourceInfo *TInfoLookupResult &Previous) {
5708  // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5709  if (D.getCXXScopeSpec().isSet()) {
5710    Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5711      << D.getCXXScopeSpec().getRange();
5712    D.setInvalidType();
5713    // Pretend we didn't see the scope specifier.
5714    DC = CurContext;
5715    Previous.clear();
5716  }
5717
5718  DiagnoseFunctionSpecifiers(D.getDeclSpec());
5719
5720  if (D.getDeclSpec().isInlineSpecified())
5721    Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5722        << getLangOpts().CPlusPlus17;
5723  if (D.getDeclSpec().isConstexprSpecified())
5724    Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5725      << 1;
5726
5727  if (D.getName().Kind != UnqualifiedIdKind::IK_Identifier) {
5728    if (D.getName().Kind == UnqualifiedIdKind::IK_DeductionGuideName)
5729      Diag(D.getName().StartLocation,
5730           diag::err_deduction_guide_invalid_specifier)
5731          << "typedef";
5732    else
5733      Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5734          << D.getName().getSourceRange();
5735    return nullptr;
5736  }
5737
5738  TypedefDecl *NewTD = ParseTypedefDecl(SDTInfo->getType(), TInfo);
5739  if (!NewTDreturn nullptr;
5740
5741  // Handle attributes prior to checking for duplicates in MergeVarDecl
5742  ProcessDeclAttributes(SNewTDD);
5743
5744  CheckTypedefForVariablyModifiedType(SNewTD);
5745
5746  bool Redeclaration = D.isRedeclaration();
5747  NamedDecl *ND = ActOnTypedefNameDecl(SDCNewTDPreviousRedeclaration);
5748  D.setRedeclaration(Redeclaration);
5749  return ND;
5750}
5751
5752void
5753Sema::CheckTypedefForVariablyModifiedType(Scope *STypedefNameDecl *NewTD) {
5754  // C99 6.7.7p2: If a typedef name specifies a variably modified type
5755  // then it shall have block scope.
5756  // Note that variably modified types must be fixed before merging the decl so
5757  // that redeclarations will match.
5758  TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5759  QualType T = TInfo->getType();
5760  if (T->isVariablyModifiedType()) {
5761    setFunctionHasBranchProtectedScope();
5762
5763    if (S->getFnParent() == nullptr) {
5764      bool SizeIsNegative;
5765      llvm::APSInt Oversized;
5766      TypeSourceInfo *FixedTInfo =
5767        TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5768                                                      SizeIsNegative,
5769                                                      Oversized);
5770      if (FixedTInfo) {
5771        Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5772        NewTD->setTypeSourceInfo(FixedTInfo);
5773      } else {
5774        if (SizeIsNegative)
5775          Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5776        else if (T->isVariableArrayType())
5777          Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5778        else if (Oversized.getBoolValue())
5779          Diag(NewTD->getLocation(), diag::err_array_too_large)
5780            << Oversized.toString(10);
5781        else
5782          Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5783        NewTD->setInvalidDecl();
5784      }
5785    }
5786  }
5787}
5788
5789/// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5790/// declares a typedef-name, either using the 'typedef' type specifier or via
5791/// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5792NamedDecl*
5793Sema::ActOnTypedefNameDecl(Scope *SDeclContext *DCTypedefNameDecl *NewTD,
5794                           LookupResult &Previousbool &Redeclaration) {
5795
5796  // Find the shadowed declaration before filtering for scope.
5797  NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTDPrevious);
5798
5799  // Merge the decl with the existing one if appropriate. If the decl is
5800  // in an outer scope, it isn't the same thing.
5801  FilterLookupForScope(PreviousDCS/*ConsiderLinkage*/false,
5802                       /*AllowInlineNamespace*/false);
5803  filterNonConflictingPreviousTypedefDecls(*thisNewTDPrevious);
5804  if (!Previous.empty()) {
5805    Redeclaration = true;
5806    MergeTypedefNameDecl(SNewTDPrevious);
5807  }
5808
5809  if (ShadowedDecl && !Redeclaration)
5810    CheckShadow(NewTDShadowedDeclPrevious);
5811
5812  // If this is the C FILE type, notify the AST context.
5813  if (IdentifierInfo *II = NewTD->getIdentifier())
5814    if (!NewTD->isInvalidDecl() &&
5815        NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5816      if (II->isStr("FILE"))
5817        Context.setFILEDecl(NewTD);
5818      else if (II->isStr("jmp_buf"))
5819        Context.setjmp_bufDecl(NewTD);
5820      else if (II->isStr("sigjmp_buf"))
5821        Context.setsigjmp_bufDecl(NewTD);
5822      else if (II->isStr("ucontext_t"))
5823        Context.setucontext_tDecl(NewTD);
5824    }
5825
5826  return NewTD;
5827}
5828
5829/// Determines whether the given declaration is an out-of-scope
5830/// previous declaration.
5831///
5832/// This routine should be invoked when name lookup has found a
5833/// previous declaration (PrevDecl) that is not in the scope where a
5834/// new declaration by the same name is being introduced. If the new
5835/// declaration occurs in a local scope, previous declarations with
5836/// linkage may still be considered previous declarations (C99
5837/// 6.2.2p4-5, C++ [basic.link]p6).
5838///
5839/// \param PrevDecl the previous declaration found by name
5840/// lookup
5841///
5842/// \param DC the context in which the new declaration is being
5843/// declared.
5844///
5845/// \returns true if PrevDecl is an out-of-scope previous declaration
5846/// for a new delcaration with the same name.
5847static bool
5848isOutOfScopePreviousDeclaration(NamedDecl *PrevDeclDeclContext *DC,
5849                                ASTContext &Context) {
5850  if (!PrevDecl)
5851    return false;
5852
5853  if (!PrevDecl->hasLinkage())
5854    return false;
5855
5856  if (Context.getLangOpts().CPlusPlus) {
5857    // C++ [basic.link]p6:
5858    //   If there is a visible declaration of an entity with linkage
5859    //   having the same name and type, ignoring entities declared
5860    //   outside the innermost enclosing namespace scope, the block
5861    //   scope declaration declares that same entity and receives the
5862    //   linkage of the previous declaration.
5863    DeclContext *OuterContext = DC->getRedeclContext();
5864    if (!OuterContext->isFunctionOrMethod())
5865      // This rule only applies to block-scope declarations.
5866      return false;
5867
5868    DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5869    if (PrevOuterContext->isRecord())
5870      // We found a member function: ignore it.
5871      return false;
5872
5873    // Find the innermost enclosing namespace for the new and
5874    // previous declarations.
5875    OuterContext = OuterContext->getEnclosingNamespaceContext();
5876    PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5877
5878    // The previous declaration is in a different namespace, so it
5879    // isn't the same function.
5880    if (!OuterContext->Equals(PrevOuterContext))
5881      return false;
5882  }
5883
5884  return true;
5885}
5886
5887static void SetNestedNameSpecifier(Sema &SDeclaratorDecl *DDDeclarator &D) {
5888  CXXScopeSpec &SS = D.getCXXScopeSpec();
5889  if (!SS.isSet()) return;
5890  DD->setQualifierInfo(SS.getWithLocInContext(S.Context));
5891}
5892
5893bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5894  QualType type = decl->getType();
5895  Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5896  if (lifetime == Qualifiers::OCL_Autoreleasing) {
5897    // Various kinds of declaration aren't allowed to be __autoreleasing.
5898    unsigned kind = -1U;
5899    if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5900      if (var->hasAttr<BlocksAttr>())
5901        kind = 0// __block
5902      else if (!var->hasLocalStorage())
5903        kind = 1// global
5904    } else if (isa<ObjCIvarDecl>(decl)) {
5905      kind = 3// ivar
5906    } else if (isa<FieldDecl>(decl)) {
5907      kind = 2// field
5908    }
5909
5910    if (kind != -1U) {
5911      Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5912        << kind;
5913    }
5914  } else if (lifetime == Qualifiers::OCL_None) {
5915    // Try to infer lifetime.
5916    if (!type->isObjCLifetimeType())
5917      return false;
5918
5919    lifetime = type->getObjCARCImplicitLifetime();
5920    type = Context.getLifetimeQualifiedType(typelifetime);
5921    decl->setType(type);
5922  }
5923
5924  if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5925    // Thread-local variables cannot have lifetime.
5926    if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5927        var->getTLSKind()) {
5928      Diag(var->getLocation(), diag::err_arc_thread_ownership)
5929        << var->getType();
5930      return true;
5931    }
5932  }
5933
5934  return false;
5935}
5936
5937static void checkAttributesAfterMerging(Sema &SNamedDecl &ND) {
5938  // Ensure that an auto decl is deduced otherwise the checks below might cache
5939  // the wrong linkage.
5940  assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5941
5942  // 'weak' only applies to declarations with external linkage.
5943  if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5944    if (!ND.isExternallyVisible()) {
5945      S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5946      ND.dropAttr<WeakAttr>();
5947    }
5948  }
5949  if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5950    if (ND.isExternallyVisible()) {
5951      S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5952      ND.dropAttr<WeakRefAttr>();
5953      ND.dropAttr<AliasAttr>();
5954    }
5955  }
5956
5957  if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5958    if (VD->hasInit()) {
5959      if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5960         (0) . __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 5961, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(VD->isThisDeclarationADefinition() &&
5961 (0) . __assert_fail ("VD->isThisDeclarationADefinition() && !VD->isExternallyVisible() && \"Broken AliasAttr handled late!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 5961, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">               !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5962        S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5963        VD->dropAttr<AliasAttr>();
5964      }
5965    }
5966  }
5967
5968  // 'selectany' only applies to externally visible variable declarations.
5969  // It does not apply to functions.
5970  if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5971    if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5972      S.Diag(Attr->getLocation(),
5973             diag::err_attribute_selectany_non_extern_data);
5974      ND.dropAttr<SelectAnyAttr>();
5975    }
5976  }
5977
5978  if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5979    auto *VD = dyn_cast<VarDecl>(&ND);
5980    bool IsAnonymousNS = false;
5981    bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5982    if (VD) {
5983      const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
5984      while (NS && !IsAnonymousNS) {
5985        IsAnonymousNS = NS->isAnonymousNamespace();
5986        NS = dyn_cast<NamespaceDecl>(NS->getParent());
5987      }
5988    }
5989    // dll attributes require external linkage. Static locals may have external
5990    // linkage but still cannot be explicitly imported or exported.
5991    // In Microsoft mode, a variable defined in anonymous namespace must have
5992    // external linkage in order to be exported.
5993    bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
5994    if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
5995        (!AnonNSInMicrosoftMode &&
5996         (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
5997      S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5998        << &ND << Attr;
5999      ND.setInvalidDecl();
6000    }
6001  }
6002
6003  // Virtual functions cannot be marked as 'notail'.
6004  if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
6005    if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
6006      if (MD->isVirtual()) {
6007        S.Diag(ND.getLocation(),
6008               diag::err_invalid_attribute_on_virtual_function)
6009            << Attr;
6010        ND.dropAttr<NotTailCalledAttr>();
6011      }
6012
6013  // Check the attributes on the function type, if any.
6014  if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6015    // Don't declare this variable in the second operand of the for-statement;
6016    // GCC miscompiles that by ending its lifetime before evaluating the
6017    // third operand. See gcc.gnu.org/PR86769.
6018    AttributedTypeLoc ATL;
6019    for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6020         (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6021         TL = ATL.getModifiedLoc()) {
6022      // The [[lifetimebound]] attribute can be applied to the implicit object
6023      // parameter of a non-static member function (other than a ctor or dtor)
6024      // by applying it to the function type.
6025      if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6026        const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6027        if (!MD || MD->isStatic()) {
6028          S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6029              << !MD << A->getRange();
6030        } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6031          S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6032              << isa<CXXDestructorDecl>(MD) << A->getRange();
6033        }
6034      }
6035    }
6036  }
6037}
6038
6039static void checkDLLAttributeRedeclaration(Sema &SNamedDecl *OldDecl,
6040                                           NamedDecl *NewDecl,
6041                                           bool IsSpecialization,
6042                                           bool IsDefinition) {
6043  if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6044    return;
6045
6046  bool IsTemplate = false;
6047  if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6048    OldDecl = OldTD->getTemplatedDecl();
6049    IsTemplate = true;
6050    if (!IsSpecialization)
6051      IsDefinition = false;
6052  }
6053  if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6054    NewDecl = NewTD->getTemplatedDecl();
6055    IsTemplate = true;
6056  }
6057
6058  if (!OldDecl || !NewDecl)
6059    return;
6060
6061  const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6062  const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6063  const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6064  const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6065
6066  // dllimport and dllexport are inheritable attributes so we have to exclude
6067  // inherited attribute instances.
6068  bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6069                    (NewExportAttr && !NewExportAttr->isInherited());
6070
6071  // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6072  // the only exception being explicit specializations.
6073  // Implicitly generated declarations are also excluded for now because there
6074  // is no other way to switch these to use dllimport or dllexport.
6075  bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6076
6077  if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6078    // Allow with a warning for free functions and global variables.
6079    bool JustWarn = false;
6080    if (!OldDecl->isCXXClassMember()) {
6081      auto *VD = dyn_cast<VarDecl>(OldDecl);
6082      if (VD && !VD->getDescribedVarTemplate())
6083        JustWarn = true;
6084      auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6085      if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6086        JustWarn = true;
6087    }
6088
6089    // We cannot change a declaration that's been used because IR has already
6090    // been emitted. Dllimported functions will still work though (modulo
6091    // address equality) as they can use the thunk.
6092    if (OldDecl->isUsed())
6093      if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6094        JustWarn = false;
6095
6096    unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6097                               : diag::err_attribute_dll_redeclaration;
6098    S.Diag(NewDecl->getLocation(), DiagID)
6099        << NewDecl
6100        << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6101    S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6102    if (!JustWarn) {
6103      NewDecl->setInvalidDecl();
6104      return;
6105    }
6106  }
6107
6108  // A redeclaration is not allowed to drop a dllimport attribute, the only
6109  // exceptions being inline function definitions (except for function
6110  // templates), local extern declarations, qualified friend declarations or
6111  // special MSVC extension: in the last case, the declaration is treated as if
6112  // it were marked dllexport.
6113  bool IsInline = falseIsStaticDataMember = falseIsQualifiedFriend = false;
6114  bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6115  if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6116    // Ignore static data because out-of-line definitions are diagnosed
6117    // separately.
6118    IsStaticDataMember = VD->isStaticDataMember();
6119    IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6120                   VarDecl::DeclarationOnly;
6121  } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6122    IsInline = FD->isInlined();
6123    IsQualifiedFriend = FD->getQualifier() &&
6124                        FD->getFriendObjectKind() == Decl::FOK_Declared;
6125  }
6126
6127  if (OldImportAttr && !HasNewAttr &&
6128      (!IsInline || (IsMicrosoft && IsTemplate)) && !IsStaticDataMember &&
6129      !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6130    if (IsMicrosoft && IsDefinition) {
6131      S.Diag(NewDecl->getLocation(),
6132             diag::warn_redeclaration_without_import_attribute)
6133          << NewDecl;
6134      S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6135      NewDecl->dropAttr<DLLImportAttr>();
6136      NewDecl->addAttr(::new (S.Context) DLLExportAttr(
6137          NewImportAttr->getRange(), S.Context,
6138          NewImportAttr->getSpellingListIndex()));
6139    } else {
6140      S.Diag(NewDecl->getLocation(),
6141             diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6142          << NewDecl << OldImportAttr;
6143      S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6144      S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6145      OldDecl->dropAttr<DLLImportAttr>();
6146      NewDecl->dropAttr<DLLImportAttr>();
6147    }
6148  } else if (IsInline && OldImportAttr && !IsMicrosoft) {
6149    // In MinGW, seeing a function declared inline drops the dllimport
6150    // attribute.
6151    OldDecl->dropAttr<DLLImportAttr>();
6152    NewDecl->dropAttr<DLLImportAttr>();
6153    S.Diag(NewDecl->getLocation(),
6154           diag::warn_dllimport_dropped_from_inline_function)
6155        << NewDecl << OldImportAttr;
6156  }
6157
6158  // A specialization of a class template member function is processed here
6159  // since it's a redeclaration. If the parent class is dllexport, the
6160  // specialization inherits that attribute. This doesn't happen automatically
6161  // since the parent class isn't instantiated until later.
6162  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6163    if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6164        !NewImportAttr && !NewExportAttr) {
6165      if (const DLLExportAttr *ParentExportAttr =
6166              MD->getParent()->getAttr<DLLExportAttr>()) {
6167        DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6168        NewAttr->setInherited(true);
6169        NewDecl->addAttr(NewAttr);
6170      }
6171    }
6172  }
6173}
6174
6175/// Given that we are within the definition of the given function,
6176/// will that definition behave like C99's 'inline', where the
6177/// definition is discarded except for optimization purposes?
6178static bool isFunctionDefinitionDiscarded(Sema &SFunctionDecl *FD) {
6179  // Try to avoid calling GetGVALinkageForFunction.
6180
6181  // All cases of this require the 'inline' keyword.
6182  if (!FD->isInlined()) return false;
6183
6184  // This is only possible in C++ with the gnu_inline attribute.
6185  if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6186    return false;
6187
6188  // Okay, go ahead and call the relatively-more-expensive function.
6189  return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
6190}
6191
6192/// Determine whether a variable is extern "C" prior to attaching
6193/// an initializer. We can't just call isExternC() here, because that
6194/// will also compute and cache whether the declaration is externally
6195/// visible, which might change when we attach the initializer.
6196///
6197/// This can only be used if the declaration is known to not be a
6198/// redeclaration of an internal linkage declaration.
6199///
6200/// For instance:
6201///
6202///   auto x = []{};
6203///
6204/// Attaching the initializer here makes this declaration not externally
6205/// visible, because its type has internal linkage.
6206///
6207/// FIXME: This is a hack.
6208template<typename T>
6209static bool isIncompleteDeclExternC(Sema &Sconst T *D) {
6210  if (S.getLangOpts().CPlusPlus) {
6211    // In C++, the overloadable attribute negates the effects of extern "C".
6212    if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6213      return false;
6214
6215    // So do CUDA's host/device attributes.
6216    if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6217                                 D->template hasAttr<CUDAHostAttr>()))
6218      return false;
6219  }
6220  return D->isExternC();
6221}
6222
6223static bool shouldConsiderLinkage(const VarDecl *VD) {
6224  const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6225  if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6226      isa<OMPDeclareMapperDecl>(DC))
6227    return VD->hasExternalStorage();
6228  if (DC->isFileContext())
6229    return true;
6230  if (DC->isRecord())
6231    return false;
6232  llvm_unreachable("Unexpected context");
6233}
6234
6235static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6236  const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6237  if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6238      isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6239    return true;
6240  if (DC->isRecord())
6241    return false;
6242  llvm_unreachable("Unexpected context");
6243}
6244
6245static bool hasParsedAttr(Scope *Sconst Declarator &PD,
6246                          ParsedAttr::Kind Kind) {
6247  // Check decl attributes on the DeclSpec.
6248  if (PD.getDeclSpec().getAttributes().hasAttribute(Kind))
6249    return true;
6250
6251  // Walk the declarator structure, checking decl attributes that were in a type
6252  // position to the decl itself.
6253  for (unsigned I = 0E = PD.getNumTypeObjects(); I != E; ++I) {
6254    if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6255      return true;
6256  }
6257
6258  // Finally, check attributes on the decl itself.
6259  return PD.getAttributes().hasAttribute(Kind);
6260}
6261
6262/// Adjust the \c DeclContext for a function or variable that might be a
6263/// function-local external declaration.
6264bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
6265  if (!DC->isFunctionOrMethod())
6266    return false;
6267
6268  // If this is a local extern function or variable declared within a function
6269  // template, don't add it into the enclosing namespace scope until it is
6270  // instantiated; it might have a dependent type right now.
6271  if (DC->isDependentContext())
6272    return true;
6273
6274  // C++11 [basic.link]p7:
6275  //   When a block scope declaration of an entity with linkage is not found to
6276  //   refer to some other declaration, then that entity is a member of the
6277  //   innermost enclosing namespace.
6278  //
6279  // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6280  // semantically-enclosing namespace, not a lexically-enclosing one.
6281  while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6282    DC = DC->getParent();
6283  return true;
6284}
6285
6286/// Returns true if given declaration has external C language linkage.
6287static bool isDeclExternC(const Decl *D) {
6288  if (const auto *FD = dyn_cast<FunctionDecl>(D))
6289    return FD->isExternC();
6290  if (const auto *VD = dyn_cast<VarDecl>(D))
6291    return VD->isExternC();
6292
6293  llvm_unreachable("Unknown type of decl!");
6294}
6295
6296NamedDecl *Sema::ActOnVariableDeclarator(
6297    Scope *SDeclarator &DDeclContext *DCTypeSourceInfo *TInfo,
6298    LookupResult &PreviousMultiTemplateParamsArg TemplateParamLists,
6299    bool &AddToScopeArrayRef<BindingDecl *> Bindings) {
6300  QualType R = TInfo->getType();
6301  DeclarationName Name = GetNameForDeclarator(D).getName();
6302
6303  IdentifierInfo *II = Name.getAsIdentifierInfo();
6304
6305  if (D.isDecompositionDeclarator()) {
6306    // Take the name of the first declarator as our name for diagnostic
6307    // purposes.
6308    auto &Decomp = D.getDecompositionDeclarator();
6309    if (!Decomp.bindings().empty()) {
6310      II = Decomp.bindings()[0].Name;
6311      Name = II;
6312    }
6313  } else if (!II) {
6314    Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
6315    return nullptr;
6316  }
6317
6318  if (getLangOpts().OpenCL) {
6319    // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6320    // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6321    // argument.
6322    if (R->isImageType() || R->isPipeType()) {
6323      Diag(D.getIdentifierLoc(),
6324           diag::err_opencl_type_can_only_be_used_as_function_parameter)
6325          << R;
6326      D.setInvalidType();
6327      return nullptr;
6328    }
6329
6330    // OpenCL v1.2 s6.9.r:
6331    // The event type cannot be used to declare a program scope variable.
6332    // OpenCL v2.0 s6.9.q:
6333    // The clk_event_t and reserve_id_t types cannot be declared in program scope.
6334    if (NULL == S->getParent()) {
6335      if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6336        Diag(D.getIdentifierLoc(),
6337             diag::err_invalid_type_for_program_scope_var) << R;
6338        D.setInvalidType();
6339        return nullptr;
6340      }
6341    }
6342
6343    // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
6344    QualType NR = R;
6345    while (NR->isPointerType()) {
6346      if (NR->isFunctionPointerType()) {
6347        Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer);
6348        D.setInvalidType();
6349        break;
6350      }
6351      NR = NR->getPointeeType();
6352    }
6353
6354    if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
6355      // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
6356      // half array type (unless the cl_khr_fp16 extension is enabled).
6357      if (Context.getBaseElementType(R)->isHalfType()) {
6358        Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
6359        D.setInvalidType();
6360      }
6361    }
6362
6363    if (R->isSamplerT()) {
6364      // OpenCL v1.2 s6.9.b p4:
6365      // The sampler type cannot be used with the __local and __global address
6366      // space qualifiers.
6367      if (R.getAddressSpace() == LangAS::opencl_local ||
6368          R.getAddressSpace() == LangAS::opencl_global) {
6369        Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
6370      }
6371
6372      // OpenCL v1.2 s6.12.14.1:
6373      // A global sampler must be declared with either the constant address
6374      // space qualifier or with the const qualifier.
6375      if (DC->isTranslationUnit() &&
6376          !(R.getAddressSpace() == LangAS::opencl_constant ||
6377          R.isConstQualified())) {
6378        Diag(D.getIdentifierLoc(), diag::err_opencl_nonconst_global_sampler);
6379        D.setInvalidType();
6380      }
6381    }
6382
6383    // OpenCL v1.2 s6.9.r:
6384    // The event type cannot be used with the __local, __constant and __global
6385    // address space qualifiers.
6386    if (R->isEventT()) {
6387      if (R.getAddressSpace() != LangAS::opencl_private) {
6388        Diag(D.getBeginLoc(), diag::err_event_t_addr_space_qual);
6389        D.setInvalidType();
6390      }
6391    }
6392
6393    // OpenCL C++ 1.0 s2.9: the thread_local storage qualifier is not
6394    // supported.  OpenCL C does not support thread_local either, and
6395    // also reject all other thread storage class specifiers.
6396    DeclSpec::TSCS TSC = D.getDeclSpec().getThreadStorageClassSpec();
6397    if (TSC != TSCS_unspecified) {
6398      bool IsCXX = getLangOpts().OpenCLCPlusPlus;
6399      Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6400           diag::err_opencl_unknown_type_specifier)
6401          << IsCXX << getLangOpts().getOpenCLVersionTuple().getAsString()
6402          << DeclSpec::getSpecifierName(TSC) << 1;
6403      D.setInvalidType();
6404      return nullptr;
6405    }
6406  }
6407
6408  DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6409  StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6410
6411  // dllimport globals without explicit storage class are treated as extern. We
6412  // have to change the storage class this early to get the right DeclContext.
6413  if (SC == SC_None && !DC->isRecord() &&
6414      hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
6415      !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
6416    SC = SC_Extern;
6417
6418  DeclContext *OriginalDC = DC;
6419  bool IsLocalExternDecl = SC == SC_Extern &&
6420                           adjustContextForLocalExternDecl(DC);
6421
6422  if (SCSpec == DeclSpec::SCS_mutable) {
6423    // mutable can only appear on non-static class members, so it's always
6424    // an error here
6425    Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6426    D.setInvalidType();
6427    SC = SC_None;
6428  }
6429
6430  if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6431      !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6432                              D.getDeclSpec().getStorageClassSpecLoc())) {
6433    // In C++11, the 'register' storage class specifier is deprecated.
6434    // Suppress the warning in system macros, it's used in macros in some
6435    // popular C system headers, such as in glibc's htonl() macro.
6436    Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6437         getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
6438                                   : diag::warn_deprecated_register)
6439      << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6440  }
6441
6442  DiagnoseFunctionSpecifiers(D.getDeclSpec());
6443
6444  if (!DC->isRecord() && S->getFnParent() == nullptr) {
6445    // C99 6.9p2: The storage-class specifiers auto and register shall not
6446    // appear in the declaration specifiers in an external declaration.
6447    // Global Register+Asm is a GNU extension we support.
6448    if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6449      Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6450      D.setInvalidType();
6451    }
6452  }
6453
6454  bool IsMemberSpecialization = false;
6455  bool IsVariableTemplateSpecialization = false;
6456  bool IsPartialSpecialization = false;
6457  bool IsVariableTemplate = false;
6458  VarDecl *NewVD = nullptr;
6459  VarTemplateDecl *NewTemplate = nullptr;
6460  TemplateParameterList *TemplateParams = nullptr;
6461  if (!getLangOpts().CPlusPlus) {
6462    NewVD = VarDecl::Create(ContextDCD.getBeginLoc(), D.getIdentifierLoc(),
6463                            IIRTInfoSC);
6464
6465    if (R->getContainedDeducedType())
6466      ParsingInitForAutoVars.insert(NewVD);
6467
6468    if (D.isInvalidType())
6469      NewVD->setInvalidDecl();
6470  } else {
6471    bool Invalid = false;
6472
6473    if (DC->isRecord() && !CurContext->isRecord()) {
6474      // This is an out-of-line definition of a static data member.
6475      switch (SC) {
6476      case SC_None:
6477        break;
6478      case SC_Static:
6479        Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6480             diag::err_static_out_of_line)
6481          << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6482        break;
6483      case SC_Auto:
6484      case SC_Register:
6485      case SC_Extern:
6486        // [dcl.stc] p2: The auto or register specifiers shall be applied only
6487        // to names of variables declared in a block or to function parameters.
6488        // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6489        // of class members
6490
6491        Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6492             diag::err_storage_class_for_static_member)
6493          << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6494        break;
6495      case SC_PrivateExtern:
6496        llvm_unreachable("C storage class in c++!");
6497      }
6498    }
6499
6500    if (SC == SC_Static && CurContext->isRecord()) {
6501      if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6502        if (RD->isLocalClass())
6503          Diag(D.getIdentifierLoc(),
6504               diag::err_static_data_member_not_allowed_in_local_class)
6505            << Name << RD->getDeclName();
6506
6507        // C++98 [class.union]p1: If a union contains a static data member,
6508        // the program is ill-formed. C++11 drops this restriction.
6509        if (RD->isUnion())
6510          Diag(D.getIdentifierLoc(),
6511               getLangOpts().CPlusPlus11
6512                 ? diag::warn_cxx98_compat_static_data_member_in_union
6513                 : diag::ext_static_data_member_in_union) << Name;
6514        // We conservatively disallow static data members in anonymous structs.
6515        else if (!RD->getDeclName())
6516          Diag(D.getIdentifierLoc(),
6517               diag::err_static_data_member_not_allowed_in_anon_struct)
6518            << Name << RD->isUnion();
6519      }
6520    }
6521
6522    // Match up the template parameter lists with the scope specifier, then
6523    // determine whether we have a template or a template specialization.
6524    TemplateParams = MatchTemplateParametersToScopeSpecifier(
6525        D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
6526        D.getCXXScopeSpec(),
6527        D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
6528            ? D.getName().TemplateId
6529            : nullptr,
6530        TemplateParamLists,
6531        /*never a friend*/ false, IsMemberSpecialization, Invalid);
6532
6533    if (TemplateParams) {
6534      if (!TemplateParams->size() &&
6535          D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
6536        // There is an extraneous 'template<>' for this variable. Complain
6537        // about it, but allow the declaration of the variable.
6538        Diag(TemplateParams->getTemplateLoc(),
6539             diag::err_template_variable_noparams)
6540          << II
6541          << SourceRange(TemplateParams->getTemplateLoc(),
6542                         TemplateParams->getRAngleLoc());
6543        TemplateParams = nullptr;
6544      } else {
6545        if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
6546          // This is an explicit specialization or a partial specialization.
6547          // FIXME: Check that we can declare a specialization here.
6548          IsVariableTemplateSpecialization = true;
6549          IsPartialSpecialization = TemplateParams->size() > 0;
6550        } else { // if (TemplateParams->size() > 0)
6551          // This is a template declaration.
6552          IsVariableTemplate = true;
6553
6554          // Check that we can declare a template here.
6555          if (CheckTemplateDeclScope(STemplateParams))
6556            return nullptr;
6557
6558          // Only C++1y supports variable templates (N3651).
6559          Diag(D.getIdentifierLoc(),
6560               getLangOpts().CPlusPlus14
6561                   ? diag::warn_cxx11_compat_variable_template
6562                   : diag::ext_variable_template);
6563        }
6564      }
6565    } else {
6566      ' for this decl") ? static_cast (0) . __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind..IK_TemplateId) && \"should have a 'template<>' for this decl\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 6568, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert((Invalid ||
6567' for this decl") ? static_cast (0) . __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind..IK_TemplateId) && \"should have a 'template<>' for this decl\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 6568, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">              D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) &&
6568' for this decl") ? static_cast (0) . __assert_fail ("(Invalid || D.getName().getKind() != UnqualifiedIdKind..IK_TemplateId) && \"should have a 'template<>' for this decl\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 6568, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">             "should have a 'template<>' for this decl");
6569    }
6570
6571    if (IsVariableTemplateSpecialization) {
6572      SourceLocation TemplateKWLoc =
6573          TemplateParamLists.size() > 0
6574              ? TemplateParamLists[0]->getTemplateLoc()
6575              : SourceLocation();
6576      DeclResult Res = ActOnVarTemplateSpecialization(
6577          SDTInfoTemplateKWLocTemplateParamsSC,
6578          IsPartialSpecialization);
6579      if (Res.isInvalid())
6580        return nullptr;
6581      NewVD = cast<VarDecl>(Res.get());
6582      AddToScope = false;
6583    } else if (D.isDecompositionDeclarator()) {
6584      NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
6585                                        D.getIdentifierLoc(), R, TInfo, SC,
6586                                        Bindings);
6587    } else
6588      NewVD = VarDecl::Create(ContextDCD.getBeginLoc(),
6589                              D.getIdentifierLoc(), IIRTInfoSC);
6590
6591    // If this is supposed to be a variable template, create it as such.
6592    if (IsVariableTemplate) {
6593      NewTemplate =
6594          VarTemplateDecl::Create(ContextDCD.getIdentifierLoc(), Name,
6595                                  TemplateParamsNewVD);
6596      NewVD->setDescribedVarTemplate(NewTemplate);
6597    }
6598
6599    // If this decl has an auto type in need of deduction, make a note of the
6600    // Decl so we can diagnose uses of it in its own initializer.
6601    if (R->getContainedDeducedType())
6602      ParsingInitForAutoVars.insert(NewVD);
6603
6604    if (D.isInvalidType() || Invalid) {
6605      NewVD->setInvalidDecl();
6606      if (NewTemplate)
6607        NewTemplate->setInvalidDecl();
6608    }
6609
6610    SetNestedNameSpecifier(*thisNewVDD);
6611
6612    // If we have any template parameter lists that don't directly belong to
6613    // the variable (matching the scope specifier), store them.
6614    unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6615    if (TemplateParamLists.size() > VDTemplateParamLists)
6616      NewVD->setTemplateParameterListsInfo(
6617          Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6618
6619    if (D.getDeclSpec().isConstexprSpecified()) {
6620      NewVD->setConstexpr(true);
6621      // C++1z [dcl.spec.constexpr]p1:
6622      //   A static data member declared with the constexpr specifier is
6623      //   implicitly an inline variable.
6624      if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus17)
6625        NewVD->setImplicitlyInline();
6626    }
6627  }
6628
6629  if (D.getDeclSpec().isInlineSpecified()) {
6630    if (!getLangOpts().CPlusPlus) {
6631      Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6632          << 0;
6633    } else if (CurContext->isFunctionOrMethod()) {
6634      // 'inline' is not allowed on block scope variable declaration.
6635      Diag(D.getDeclSpec().getInlineSpecLoc(),
6636           diag::err_inline_declaration_block_scope) << Name
6637        << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6638    } else {
6639      Diag(D.getDeclSpec().getInlineSpecLoc(),
6640           getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
6641                                     : diag::ext_inline_variable);
6642      NewVD->setInlineSpecified();
6643    }
6644  }
6645
6646  // Set the lexical context. If the declarator has a C++ scope specifier, the
6647  // lexical context will be different from the semantic context.
6648  NewVD->setLexicalDeclContext(CurContext);
6649  if (NewTemplate)
6650    NewTemplate->setLexicalDeclContext(CurContext);
6651
6652  if (IsLocalExternDecl) {
6653    if (D.isDecompositionDeclarator())
6654      for (auto *B : Bindings)
6655        B->setLocalExternDecl();
6656    else
6657      NewVD->setLocalExternDecl();
6658  }
6659
6660  bool EmitTLSUnsupportedError = false;
6661  if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6662    // C++11 [dcl.stc]p4:
6663    //   When thread_local is applied to a variable of block scope the
6664    //   storage-class-specifier static is implied if it does not appear
6665    //   explicitly.
6666    // Core issue: 'static' is not implied if the variable is declared
6667    //   'extern'.
6668    if (NewVD->hasLocalStorage() &&
6669        (SCSpec != DeclSpec::SCS_unspecified ||
6670         TSCS != DeclSpec::TSCS_thread_local ||
6671         !DC->isFunctionOrMethod()))
6672      Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6673           diag::err_thread_non_global)
6674        << DeclSpec::getSpecifierName(TSCS);
6675    else if (!Context.getTargetInfo().isTLSSupported()) {
6676      if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6677        // Postpone error emission until we've collected attributes required to
6678        // figure out whether it's a host or device variable and whether the
6679        // error should be ignored.
6680        EmitTLSUnsupportedError = true;
6681        // We still need to mark the variable as TLS so it shows up in AST with
6682        // proper storage class for other tools to use even if we're not going
6683        // to emit any code for it.
6684        NewVD->setTSCSpec(TSCS);
6685      } else
6686        Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6687             diag::err_thread_unsupported);
6688    } else
6689      NewVD->setTSCSpec(TSCS);
6690  }
6691
6692  // C99 6.7.4p3
6693  //   An inline definition of a function with external linkage shall
6694  //   not contain a definition of a modifiable object with static or
6695  //   thread storage duration...
6696  // We only apply this when the function is required to be defined
6697  // elsewhere, i.e. when the function is not 'extern inline'.  Note
6698  // that a local variable with thread storage duration still has to
6699  // be marked 'static'.  Also note that it's possible to get these
6700  // semantics in C++ using __attribute__((gnu_inline)).
6701  if (SC == SC_Static && S->getFnParent() != nullptr &&
6702      !NewVD->getType().isConstQualified()) {
6703    FunctionDecl *CurFD = getCurFunctionDecl();
6704    if (CurFD && isFunctionDefinitionDiscarded(*thisCurFD)) {
6705      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6706           diag::warn_static_local_in_extern_inline);
6707      MaybeSuggestAddingStaticToDecl(CurFD);
6708    }
6709  }
6710
6711  if (D.getDeclSpec().isModulePrivateSpecified()) {
6712    if (IsVariableTemplateSpecialization)
6713      Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6714          << (IsPartialSpecialization ? 1 : 0)
6715          << FixItHint::CreateRemoval(
6716                 D.getDeclSpec().getModulePrivateSpecLoc());
6717    else if (IsMemberSpecialization)
6718      Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6719        << 2
6720        << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6721    else if (NewVD->hasLocalStorage())
6722      Diag(NewVD->getLocation(), diag::err_module_private_local)
6723        << 0 << NewVD->getDeclName()
6724        << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6725        << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6726    else {
6727      NewVD->setModulePrivate();
6728      if (NewTemplate)
6729        NewTemplate->setModulePrivate();
6730      for (auto *B : Bindings)
6731        B->setModulePrivate();
6732    }
6733  }
6734
6735  // Handle attributes prior to checking for duplicates in MergeVarDecl
6736  ProcessDeclAttributes(SNewVDD);
6737
6738  if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice) {
6739    if (EmitTLSUnsupportedError &&
6740        ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
6741         (getLangOpts().OpenMPIsDevice &&
6742          NewVD->hasAttr<OMPDeclareTargetDeclAttr>())))
6743      Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6744           diag::err_thread_unsupported);
6745    // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6746    // storage [duration]."
6747    if (SC == SC_None && S->getFnParent() != nullptr &&
6748        (NewVD->hasAttr<CUDASharedAttr>() ||
6749         NewVD->hasAttr<CUDAConstantAttr>())) {
6750      NewVD->setStorageClass(SC_Static);
6751    }
6752  }
6753
6754  // Ensure that dllimport globals without explicit storage class are treated as
6755  // extern. The storage class is set above using parsed attributes. Now we can
6756  // check the VarDecl itself.
6757  hasAttr() || NewVD->getAttr()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 6759, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!NewVD->hasAttr<DLLImportAttr>() ||
6758hasAttr() || NewVD->getAttr()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 6759, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6759hasAttr() || NewVD->getAttr()->isInherited() || NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 6759, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6760
6761  // In auto-retain/release, infer strong retension for variables of
6762  // retainable type.
6763  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6764    NewVD->setInvalidDecl();
6765
6766  // Handle GNU asm-label extension (encoded as an attribute).
6767  if (Expr *E = (Expr*)D.getAsmLabel()) {
6768    // The parser guarantees this is a string.
6769    StringLiteral *SE = cast<StringLiteral>(E);
6770    StringRef Label = SE->getString();
6771    if (S->getFnParent() != nullptr) {
6772      switch (SC) {
6773      case SC_None:
6774      case SC_Auto:
6775        Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6776        break;
6777      case SC_Register:
6778        // Local Named register
6779        if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6780            DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6781          Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6782        break;
6783      case SC_Static:
6784      case SC_Extern:
6785      case SC_PrivateExtern:
6786        break;
6787      }
6788    } else if (SC == SC_Register) {
6789      // Global Named register
6790      if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6791        const auto &TI = Context.getTargetInfo();
6792        bool HasSizeMismatch;
6793
6794        if (!TI.isValidGCCRegisterName(Label))
6795          Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6796        else if (!TI.validateGlobalRegisterVariable(Label,
6797                                                    Context.getTypeSize(R),
6798                                                    HasSizeMismatch))
6799          Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6800        else if (HasSizeMismatch)
6801          Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6802      }
6803
6804      if (!R->isIntegralType(Context) && !R->isPointerType()) {
6805        Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
6806        NewVD->setInvalidDecl(true);
6807      }
6808    }
6809
6810    NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6811                                                Context, Label, 0));
6812  } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6813    llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6814      ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6815    if (I != ExtnameUndeclaredIdentifiers.end()) {
6816      if (isDeclExternC(NewVD)) {
6817        NewVD->addAttr(I->second);
6818        ExtnameUndeclaredIdentifiers.erase(I);
6819      } else
6820        Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6821            << /*Variable*/1 << NewVD;
6822    }
6823  }
6824
6825  // Find the shadowed declaration before filtering for scope.
6826  NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6827                                ? getShadowedDeclaration(NewVDPrevious)
6828                                : nullptr;
6829
6830  // Don't consider existing declarations that are in a different
6831  // scope and are out-of-semantic-context declarations (if the new
6832  // declaration has linkage).
6833  FilterLookupForScope(PreviousOriginalDCSshouldConsiderLinkage(NewVD),
6834                       D.getCXXScopeSpec().isNotEmpty() ||
6835                       IsMemberSpecialization ||
6836                       IsVariableTemplateSpecialization);
6837
6838  // Check whether the previous declaration is in the same block scope. This
6839  // affects whether we merge types with it, per C++11 [dcl.array]p3.
6840  if (getLangOpts().CPlusPlus &&
6841      NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6842    NewVD->setPreviousDeclInSameBlockScope(
6843        Previous.isSingleResult() && !Previous.isShadowed() &&
6844        isDeclInScope(Previous.getFoundDecl(), OriginalDCSfalse));
6845
6846  if (!getLangOpts().CPlusPlus) {
6847    D.setRedeclaration(CheckVariableDeclaration(NewVDPrevious));
6848  } else {
6849    // If this is an explicit specialization of a static data member, check it.
6850    if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
6851        CheckMemberSpecialization(NewVDPrevious))
6852      NewVD->setInvalidDecl();
6853
6854    // Merge the decl with the existing one if appropriate.
6855    if (!Previous.empty()) {
6856      if (Previous.isSingleResult() &&
6857          isa<FieldDecl>(Previous.getFoundDecl()) &&
6858          D.getCXXScopeSpec().isSet()) {
6859        // The user tried to define a non-static data member
6860        // out-of-line (C++ [dcl.meaning]p1).
6861        Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6862          << D.getCXXScopeSpec().getRange();
6863        Previous.clear();
6864        NewVD->setInvalidDecl();
6865      }
6866    } else if (D.getCXXScopeSpec().isSet()) {
6867      // No previous declaration in the qualifying scope.
6868      Diag(D.getIdentifierLoc(), diag::err_no_member)
6869        << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6870        << D.getCXXScopeSpec().getRange();
6871      NewVD->setInvalidDecl();
6872    }
6873
6874    if (!IsVariableTemplateSpecialization)
6875      D.setRedeclaration(CheckVariableDeclaration(NewVDPrevious));
6876
6877    if (NewTemplate) {
6878      VarTemplateDecl *PrevVarTemplate =
6879          NewVD->getPreviousDecl()
6880              ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6881              : nullptr;
6882
6883      // Check the template parameter list of this declaration, possibly
6884      // merging in the template parameter list from the previous variable
6885      // template declaration.
6886      if (CheckTemplateParameterList(
6887              TemplateParams,
6888              PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6889                              : nullptr,
6890              (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6891               DC->isDependentContext())
6892                  ? TPC_ClassTemplateMember
6893                  : TPC_VarTemplate))
6894        NewVD->setInvalidDecl();
6895
6896      // If we are providing an explicit specialization of a static variable
6897      // template, make a note of that.
6898      if (PrevVarTemplate &&
6899          PrevVarTemplate->getInstantiatedFromMemberTemplate())
6900        PrevVarTemplate->setMemberSpecialization();
6901    }
6902  }
6903
6904  // Diagnose shadowed variables iff this isn't a redeclaration.
6905  if (ShadowedDecl && !D.isRedeclaration())
6906    CheckShadow(NewVDShadowedDeclPrevious);
6907
6908  ProcessPragmaWeak(SNewVD);
6909
6910  // If this is the first declaration of an extern C variable, update
6911  // the map of such variables.
6912  if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6913      isIncompleteDeclExternC(*thisNewVD))
6914    RegisterLocallyScopedExternCDecl(NewVDS);
6915
6916  if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6917    Decl *ManglingContextDecl;
6918    if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6919            NewVD->getDeclContext(), ManglingContextDecl)) {
6920      Context.setManglingNumber(
6921          NewVDMCtx->getManglingNumber(
6922                     NewVDgetMSManglingNumber(getLangOpts(), S)));
6923      Context.setStaticLocalNumber(NewVDMCtx->getStaticLocalNumber(NewVD));
6924    }
6925  }
6926
6927  // Special handling of variable named 'main'.
6928  if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6929      NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6930      !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6931
6932    // C++ [basic.start.main]p3
6933    // A program that declares a variable main at global scope is ill-formed.
6934    if (getLangOpts().CPlusPlus)
6935      Diag(D.getBeginLoc(), diag::err_main_global_variable);
6936
6937    // In C, and external-linkage variable named main results in undefined
6938    // behavior.
6939    else if (NewVD->hasExternalFormalLinkage())
6940      Diag(D.getBeginLoc(), diag::warn_main_redefined);
6941  }
6942
6943  if (D.isRedeclaration() && !Previous.empty()) {
6944    NamedDecl *Prev = Previous.getRepresentativeDecl();
6945    checkDLLAttributeRedeclaration(*thisPrevNewVDIsMemberSpecialization,
6946                                   D.isFunctionDefinition());
6947  }
6948
6949  if (NewTemplate) {
6950    if (NewVD->isInvalidDecl())
6951      NewTemplate->setInvalidDecl();
6952    ActOnDocumentableDecl(NewTemplate);
6953    return NewTemplate;
6954  }
6955
6956  if (IsMemberSpecialization && !NewVD->isInvalidDecl())
6957    CompleteMemberSpecialization(NewVDPrevious);
6958
6959  return NewVD;
6960}
6961
6962/// Enum describing the %select options in diag::warn_decl_shadow.
6963enum ShadowedDeclKind {
6964  SDK_Local,
6965  SDK_Global,
6966  SDK_StaticMember,
6967  SDK_Field,
6968  SDK_Typedef,
6969  SDK_Using
6970};
6971
6972/// Determine what kind of declaration we're shadowing.
6973static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6974                                                const DeclContext *OldDC) {
6975  if (isa<TypeAliasDecl>(ShadowedDecl))
6976    return SDK_Using;
6977  else if (isa<TypedefDecl>(ShadowedDecl))
6978    return SDK_Typedef;
6979  else if (isa<RecordDecl>(OldDC))
6980    return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6981
6982  return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6983}
6984
6985/// Return the location of the capture if the given lambda captures the given
6986/// variable \p VD, or an invalid source location otherwise.
6987static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6988                                         const VarDecl *VD) {
6989  for (const Capture &Capture : LSI->Captures) {
6990    if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6991      return Capture.getLocation();
6992  }
6993  return SourceLocation();
6994}
6995
6996static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags,
6997                                     const LookupResult &R) {
6998  // Only diagnose if we're shadowing an unambiguous field or variable.
6999  if (R.getResultKind() != LookupResult::Found)
7000    return false;
7001
7002  // Return false if warning is ignored.
7003  return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7004}
7005
7006/// Return the declaration shadowed by the given variable \p D, or null
7007/// if it doesn't shadow any declaration or shadowing warnings are disabled.
7008NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
7009                                        const LookupResult &R) {
7010  if (!shouldWarnIfShadowedDecl(DiagsR))
7011    return nullptr;
7012
7013  // Don't diagnose declarations at file scope.
7014  if (D->hasGlobalStorage())
7015    return nullptr;
7016
7017  NamedDecl *ShadowedDecl = R.getFoundDecl();
7018  return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
7019             ? ShadowedDecl
7020             : nullptr;
7021}
7022
7023/// Return the declaration shadowed by the given typedef \p D, or null
7024/// if it doesn't shadow any declaration or shadowing warnings are disabled.
7025NamedDecl *Sema::getShadowedDeclaration(const TypedefNameDecl *D,
7026                                        const LookupResult &R) {
7027  // Don't warn if typedef declaration is part of a class
7028  if (D->getDeclContext()->isRecord())
7029    return nullptr;
7030
7031  if (!shouldWarnIfShadowedDecl(DiagsR))
7032    return nullptr;
7033
7034  NamedDecl *ShadowedDecl = R.getFoundDecl();
7035  return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7036}
7037
7038/// Diagnose variable or built-in function shadowing.  Implements
7039/// -Wshadow.
7040///
7041/// This method is called whenever a VarDecl is added to a "useful"
7042/// scope.
7043///
7044/// \param ShadowedDecl the declaration that is shadowed by the given variable
7045/// \param R the lookup of the name
7046///
7047void Sema::CheckShadow(NamedDecl *DNamedDecl *ShadowedDecl,
7048                       const LookupResult &R) {
7049  DeclContext *NewDC = D->getDeclContext();
7050
7051  if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7052    // Fields are not shadowed by variables in C++ static methods.
7053    if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7054      if (MD->isStatic())
7055        return;
7056
7057    // Fields shadowed by constructor parameters are a special case. Usually
7058    // the constructor initializes the field with the parameter.
7059    if (isa<CXXConstructorDecl>(NewDC))
7060      if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7061        // Remember that this was shadowed so we can either warn about its
7062        // modification or its existence depending on warning settings.
7063        ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7064        return;
7065      }
7066  }
7067
7068  if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7069    if (shadowedVar->isExternC()) {
7070      // For shadowing external vars, make sure that we point to the global
7071      // declaration, not a locally scoped extern declaration.
7072      for (auto I : shadowedVar->redecls())
7073        if (I->isFileVarDecl()) {
7074          ShadowedDecl = I;
7075          break;
7076        }
7077    }
7078
7079  DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7080
7081  unsigned WarningDiag = diag::warn_decl_shadow;
7082  SourceLocation CaptureLoc;
7083  if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7084      isa<CXXMethodDecl>(NewDC)) {
7085    if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7086      if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7087        if (RD->getLambdaCaptureDefault() == LCD_None) {
7088          // Try to avoid warnings for lambdas with an explicit capture list.
7089          const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7090          // Warn only when the lambda captures the shadowed decl explicitly.
7091          CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7092          if (CaptureLoc.isInvalid())
7093            WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7094        } else {
7095          // Remember that this was shadowed so we can avoid the warning if the
7096          // shadowed decl isn't captured and the warning settings allow it.
7097          cast<LambdaScopeInfo>(getCurFunction())
7098              ->ShadowingDecls.push_back(
7099                  {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7100          return;
7101        }
7102      }
7103
7104      if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7105        // A variable can't shadow a local variable in an enclosing scope, if
7106        // they are separated by a non-capturing declaration context.
7107        for (DeclContext *ParentDC = NewDC;
7108             ParentDC && !ParentDC->Equals(OldDC);
7109             ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7110          // Only block literals, captured statements, and lambda expressions
7111          // can capture; other scopes don't.
7112          if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7113              !isLambdaCallOperator(ParentDC)) {
7114            return;
7115          }
7116        }
7117      }
7118    }
7119  }
7120
7121  // Only warn about certain kinds of shadowing for class members.
7122  if (NewDC && NewDC->isRecord()) {
7123    // In particular, don't warn about shadowing non-class members.
7124    if (!OldDC->isRecord())
7125      return;
7126
7127    // TODO: should we warn about static data members shadowing
7128    // static data members from base classes?
7129
7130    // TODO: don't diagnose for inaccessible shadowed members.
7131    // This is hard to do perfectly because we might friend the
7132    // shadowing context, but that's just a false negative.
7133  }
7134
7135
7136  DeclarationName Name = R.getLookupName();
7137
7138  // Emit warning and note.
7139  if (getSourceManager().isInSystemMacro(R.getNameLoc()))
7140    return;
7141  ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDeclOldDC);
7142  Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7143  if (!CaptureLoc.isInvalid())
7144    Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7145        << Name << /*explicitly*/ 1;
7146  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7147}
7148
7149/// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7150/// when these variables are captured by the lambda.
7151void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
7152  for (const auto &Shadow : LSI->ShadowingDecls) {
7153    const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7154    // Try to avoid the warning when the shadowed decl isn't captured.
7155    SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7156    const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7157    Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7158                                       ? diag::warn_decl_shadow_uncaptured_local
7159                                       : diag::warn_decl_shadow)
7160        << Shadow.VD->getDeclName()
7161        << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7162    if (!CaptureLoc.isInvalid())
7163      Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7164          << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7165    Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7166  }
7167}
7168
7169/// Check -Wshadow without the advantage of a previous lookup.
7170void Sema::CheckShadow(Scope *SVarDecl *D) {
7171  if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7172    return;
7173
7174  LookupResult R(*thisD->getDeclName(), D->getLocation(),
7175                 Sema::LookupOrdinaryNameSema::ForVisibleRedeclaration);
7176  LookupName(RS);
7177  if (NamedDecl *ShadowedDecl = getShadowedDeclaration(DR))
7178    CheckShadow(DShadowedDeclR);
7179}
7180
7181/// Check if 'E', which is an expression that is about to be modified, refers
7182/// to a constructor parameter that shadows a field.
7183void Sema::CheckShadowingDeclModification(Expr *ESourceLocation Loc) {
7184  // Quickly ignore expressions that can't be shadowing ctor parameters.
7185  if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
7186    return;
7187  E = E->IgnoreParenImpCasts();
7188  auto *DRE = dyn_cast<DeclRefExpr>(E);
7189  if (!DRE)
7190    return;
7191  const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
7192  auto I = ShadowingDecls.find(D);
7193  if (I == ShadowingDecls.end())
7194    return;
7195  const NamedDecl *ShadowedDecl = I->second;
7196  const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7197  Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
7198  Diag(D->getLocation(), diag::note_var_declared_here) << D;
7199  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7200
7201  // Avoid issuing multiple warnings about the same decl.
7202  ShadowingDecls.erase(I);
7203}
7204
7205/// Check for conflict between this global or extern "C" declaration and
7206/// previous global or extern "C" declarations. This is only used in C++.
7207template<typename T>
7208static bool checkGlobalOrExternCConflict(
7209    Sema &Sconst T *NDbool IsGlobalLookupResult &Previous) {
7210   (0) . __assert_fail ("S.getLangOpts().CPlusPlus && \"only C++ has extern \\\"C\\\"\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 7210, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
7211  NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
7212
7213  if (!Prev && IsGlobal && !isIncompleteDeclExternC(SND)) {
7214    // The common case: this global doesn't conflict with any extern "C"
7215    // declaration.
7216    return false;
7217  }
7218
7219  if (Prev) {
7220    if (!IsGlobal || isIncompleteDeclExternC(SND)) {
7221      // Both the old and new declarations have C language linkage. This is a
7222      // redeclaration.
7223      Previous.clear();
7224      Previous.addDecl(Prev);
7225      return true;
7226    }
7227
7228    // This is a global, non-extern "C" declaration, and there is a previous
7229    // non-global extern "C" declaration. Diagnose if this is a variable
7230    // declaration.
7231    if (!isa<VarDecl>(ND))
7232      return false;
7233  } else {
7234    // The declaration is extern "C". Check for any declaration in the
7235    // translation unit which might conflict.
7236    if (IsGlobal) {
7237      // We have already performed the lookup into the translation unit.
7238      IsGlobal = false;
7239      for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7240           I != E; ++I) {
7241        if (isa<VarDecl>(*I)) {
7242          Prev = *I;
7243          break;
7244        }
7245      }
7246    } else {
7247      DeclContext::lookup_result R =
7248          S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
7249      for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
7250           I != E; ++I) {
7251        if (isa<VarDecl>(*I)) {
7252          Prev = *I;
7253          break;
7254        }
7255        // FIXME: If we have any other entity with this name in global scope,
7256        // the declaration is ill-formed, but that is a defect: it breaks the
7257        // 'stat' hack, for instance. Only variables can have mangled name
7258        // clashes with extern "C" declarations, so only they deserve a
7259        // diagnostic.
7260      }
7261    }
7262
7263    if (!Prev)
7264      return false;
7265  }
7266
7267  // Use the first declaration's location to ensure we point at something which
7268  // is lexically inside an extern "C" linkage-spec.
7269   (0) . __assert_fail ("Prev && \"should have found a previous declaration to diagnose\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 7269, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Prev && "should have found a previous declaration to diagnose");
7270  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
7271    Prev = FD->getFirstDecl();
7272  else
7273    Prev = cast<VarDecl>(Prev)->getFirstDecl();
7274
7275  S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
7276    << IsGlobal << ND;
7277  S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
7278    << IsGlobal;
7279  return false;
7280}
7281
7282/// Apply special rules for handling extern "C" declarations. Returns \c true
7283/// if we have found that this is a redeclaration of some prior entity.
7284///
7285/// Per C++ [dcl.link]p6:
7286///   Two declarations [for a function or variable] with C language linkage
7287///   with the same name that appear in different scopes refer to the same
7288///   [entity]. An entity with C language linkage shall not be declared with
7289///   the same name as an entity in global scope.
7290template<typename T>
7291static bool checkForConflictWithNonVisibleExternC(Sema &Sconst T *ND,
7292                                                  LookupResult &Previous) {
7293  if (!S.getLangOpts().CPlusPlus) {
7294    // In C, when declaring a global variable, look for a corresponding 'extern'
7295    // variable declared in function scope. We don't need this in C++, because
7296    // we find local extern decls in the surrounding file-scope DeclContext.
7297    if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
7298      if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
7299        Previous.clear();
7300        Previous.addDecl(Prev);
7301        return true;
7302      }
7303    }
7304    return false;
7305  }
7306
7307  // A declaration in the translation unit can conflict with an extern "C"
7308  // declaration.
7309  if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
7310    return checkGlobalOrExternCConflict(SND/*IsGlobal*/truePrevious);
7311
7312  // An extern "C" declaration can conflict with a declaration in the
7313  // translation unit or can be a redeclaration of an extern "C" declaration
7314  // in another scope.
7315  if (isIncompleteDeclExternC(S,ND))
7316    return checkGlobalOrExternCConflict(SND/*IsGlobal*/falsePrevious);
7317
7318  // Neither global nor extern "C": nothing to do.
7319  return false;
7320}
7321
7322void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
7323  // If the decl is already known invalid, don't check it.
7324  if (NewVD->isInvalidDecl())
7325    return;
7326
7327  QualType T = NewVD->getType();
7328
7329  // Defer checking an 'auto' type until its initializer is attached.
7330  if (T->isUndeducedType())
7331    return;
7332
7333  if (NewVD->hasAttrs())
7334    CheckAlignasUnderalignment(NewVD);
7335
7336  if (T->isObjCObjectType()) {
7337    Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
7338      << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
7339    T = Context.getObjCObjectPointerType(T);
7340    NewVD->setType(T);
7341  }
7342
7343  // Emit an error if an address space was applied to decl with local storage.
7344  // This includes arrays of objects with address space qualifiers, but not
7345  // automatic variables that point to other address spaces.
7346  // ISO/IEC TR 18037 S5.1.2
7347  if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
7348      T.getAddressSpace() != LangAS::Default) {
7349    Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
7350    NewVD->setInvalidDecl();
7351    return;
7352  }
7353
7354  // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
7355  // scope.
7356  if (getLangOpts().OpenCLVersion == 120 &&
7357      !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
7358      NewVD->isStaticLocal()) {
7359    Diag(NewVD->getLocation(), diag::err_static_function_scope);
7360    NewVD->setInvalidDecl();
7361    return;
7362  }
7363
7364  if (getLangOpts().OpenCL) {
7365    // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
7366    if (NewVD->hasAttr<BlocksAttr>()) {
7367      Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
7368      return;
7369    }
7370
7371    if (T->isBlockPointerType()) {
7372      // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
7373      // can't use 'extern' storage class.
7374      if (!T.isConstQualified()) {
7375        Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
7376            << 0 /*const*/;
7377        NewVD->setInvalidDecl();
7378        return;
7379      }
7380      if (NewVD->hasExternalStorage()) {
7381        Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
7382        NewVD->setInvalidDecl();
7383        return;
7384      }
7385    }
7386    // OpenCL C v1.2 s6.5 - All program scope variables must be declared in the
7387    // __constant address space.
7388    // OpenCL C v2.0 s6.5.1 - Variables defined at program scope and static
7389    // variables inside a function can also be declared in the global
7390    // address space.
7391    // OpenCL C++ v1.0 s2.5 inherits rule from OpenCL C v2.0 and allows local
7392    // address space additionally.
7393    // FIXME: Add local AS for OpenCL C++.
7394    if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7395        NewVD->hasExternalStorage()) {
7396      if (!T->isSamplerT() &&
7397          !(T.getAddressSpace() == LangAS::opencl_constant ||
7398            (T.getAddressSpace() == LangAS::opencl_global &&
7399             (getLangOpts().OpenCLVersion == 200 ||
7400              getLangOpts().OpenCLCPlusPlus)))) {
7401        int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7402        if (getLangOpts().OpenCLVersion == 200 || getLangOpts().OpenCLCPlusPlus)
7403          Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7404              << Scope << "global or constant";
7405        else
7406          Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7407              << Scope << "constant";
7408        NewVD->setInvalidDecl();
7409        return;
7410      }
7411    } else {
7412      if (T.getAddressSpace() == LangAS::opencl_global) {
7413        Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7414            << 1 /*is any function*/ << "global";
7415        NewVD->setInvalidDecl();
7416        return;
7417      }
7418      if (T.getAddressSpace() == LangAS::opencl_constant ||
7419          T.getAddressSpace() == LangAS::opencl_local) {
7420        FunctionDecl *FD = getCurFunctionDecl();
7421        // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
7422        // in functions.
7423        if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7424          if (T.getAddressSpace() == LangAS::opencl_constant)
7425            Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7426                << 0 /*non-kernel only*/ << "constant";
7427          else
7428            Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7429                << 0 /*non-kernel only*/ << "local";
7430          NewVD->setInvalidDecl();
7431          return;
7432        }
7433        // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
7434        // in the outermost scope of a kernel function.
7435        if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
7436          if (!getCurScope()->isFunctionScope()) {
7437            if (T.getAddressSpace() == LangAS::opencl_constant)
7438              Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7439                  << "constant";
7440            else
7441              Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
7442                  << "local";
7443            NewVD->setInvalidDecl();
7444            return;
7445          }
7446        }
7447      } else if (T.getAddressSpace() != LangAS::opencl_private) {
7448        // Do not allow other address spaces on automatic variable.
7449        Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
7450        NewVD->setInvalidDecl();
7451        return;
7452      }
7453    }
7454  }
7455
7456  if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7457      && !NewVD->hasAttr<BlocksAttr>()) {
7458    if (getLangOpts().getGC() != LangOptions::NonGC)
7459      Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7460    else {
7461      assert(!getLangOpts().ObjCAutoRefCount);
7462      Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7463    }
7464  }
7465
7466  bool isVM = T->isVariablyModifiedType();
7467  if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7468      NewVD->hasAttr<BlocksAttr>())
7469    setFunctionHasBranchProtectedScope();
7470
7471  if ((isVM && NewVD->hasLinkage()) ||
7472      (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7473    bool SizeIsNegative;
7474    llvm::APSInt Oversized;
7475    TypeSourceInfo *FixedTInfo = TryToFixInvalidVariablyModifiedTypeSourceInfo(
7476        NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
7477    QualType FixedT;
7478    if (FixedTInfo &&  T == NewVD->getTypeSourceInfo()->getType())
7479      FixedT = FixedTInfo->getType();
7480    else if (FixedTInfo) {
7481      // Type and type-as-written are canonically different. We need to fix up
7482      // both types separately.
7483      FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
7484                                                   Oversized);
7485    }
7486    if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
7487      const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7488      // FIXME: This won't give the correct result for
7489      // int a[10][n];
7490      SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7491
7492      if (NewVD->isFileVarDecl())
7493        Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7494        << SizeRange;
7495      else if (NewVD->isStaticLocal())
7496        Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7497        << SizeRange;
7498      else
7499        Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7500        << SizeRange;
7501      NewVD->setInvalidDecl();
7502      return;
7503    }
7504
7505    if (!FixedTInfo) {
7506      if (NewVD->isFileVarDecl())
7507        Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7508      else
7509        Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7510      NewVD->setInvalidDecl();
7511      return;
7512    }
7513
7514    Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7515    NewVD->setType(FixedT);
7516    NewVD->setTypeSourceInfo(FixedTInfo);
7517  }
7518
7519  if (T->isVoidType()) {
7520    // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7521    //                    of objects and functions.
7522    if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7523      Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7524        << T;
7525      NewVD->setInvalidDecl();
7526      return;
7527    }
7528  }
7529
7530  if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7531    Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7532    NewVD->setInvalidDecl();
7533    return;
7534  }
7535
7536  if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7537    Diag(NewVD->getLocation(), diag::err_block_on_vm);
7538    NewVD->setInvalidDecl();
7539    return;
7540  }
7541
7542  if (NewVD->isConstexpr() && !T->isDependentType() &&
7543      RequireLiteralType(NewVD->getLocation(), T,
7544                         diag::err_constexpr_var_non_literal)) {
7545    NewVD->setInvalidDecl();
7546    return;
7547  }
7548}
7549
7550/// Perform semantic checking on a newly-created variable
7551/// declaration.
7552///
7553/// This routine performs all of the type-checking required for a
7554/// variable declaration once it has been built. It is used both to
7555/// check variables after they have been parsed and their declarators
7556/// have been translated into a declaration, and to check variables
7557/// that have been instantiated from a template.
7558///
7559/// Sets NewVD->isInvalidDecl() if an error was encountered.
7560///
7561/// Returns true if the variable declaration is a redeclaration.
7562bool Sema::CheckVariableDeclaration(VarDecl *NewVDLookupResult &Previous) {
7563  CheckVariableDeclarationType(NewVD);
7564
7565  // If the decl is already known invalid, don't check it.
7566  if (NewVD->isInvalidDecl())
7567    return false;
7568
7569  // If we did not find anything by this name, look for a non-visible
7570  // extern "C" declaration with the same name.
7571  if (Previous.empty() &&
7572      checkForConflictWithNonVisibleExternC(*thisNewVDPrevious))
7573    Previous.setShadowed();
7574
7575  if (!Previous.empty()) {
7576    MergeVarDecl(NewVDPrevious);
7577    return true;
7578  }
7579  return false;
7580}
7581
7582namespace {
7583struct FindOverriddenMethod {
7584  Sema *S;
7585  CXXMethodDecl *Method;
7586
7587  /// Member lookup function that determines whether a given C++
7588  /// method overrides a method in a base class, to be used with
7589  /// CXXRecordDecl::lookupInBases().
7590  bool operator()(const CXXBaseSpecifier *SpecifierCXXBasePath &Path) {
7591    RecordDecl *BaseRecord =
7592        Specifier->getType()->getAs<RecordType>()->getDecl();
7593
7594    DeclarationName Name = Method->getDeclName();
7595
7596    // FIXME: Do we care about other names here too?
7597    if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7598      // We really want to find the base class destructor here.
7599      QualType T = S->Context.getTypeDeclType(BaseRecord);
7600      CanQualType CT = S->Context.getCanonicalType(T);
7601
7602      Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7603    }
7604
7605    for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7606         Path.Decls = Path.Decls.slice(1)) {
7607      NamedDecl *D = Path.Decls.front();
7608      if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7609        if (MD->isVirtual() && !S->IsOverload(MethodMDfalse))
7610          return true;
7611      }
7612    }
7613
7614    return false;
7615  }
7616};
7617
7618enum OverrideErrorKind { OEK_AllOEK_NonDeletedOEK_Deleted };
7619// end anonymous namespace
7620
7621/// Report an error regarding overriding, along with any relevant
7622/// overridden methods.
7623///
7624/// \param DiagID the primary error to report.
7625/// \param MD the overriding method.
7626/// \param OEK which overrides to include as notes.
7627static void ReportOverrides(SemaSunsigned DiagIDconst CXXMethodDecl *MD,
7628                            OverrideErrorKind OEK = OEK_All) {
7629  S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7630  for (const CXXMethodDecl *O : MD->overridden_methods()) {
7631    // This check (& the OEK parameter) could be replaced by a predicate, but
7632    // without lambdas that would be overkill. This is still nicer than writing
7633    // out the diag loop 3 times.
7634    if ((OEK == OEK_All) ||
7635        (OEK == OEK_NonDeleted && !O->isDeleted()) ||
7636        (OEK == OEK_Deleted && O->isDeleted()))
7637      S.Diag(O->getLocation(), diag::note_overridden_virtual_function);
7638  }
7639}
7640
7641/// AddOverriddenMethods - See if a method overrides any in the base classes,
7642/// and if so, check that it's a valid override and remember it.
7643bool Sema::AddOverriddenMethods(CXXRecordDecl *DCCXXMethodDecl *MD) {
7644  // Look for methods in base classes that this method might override.
7645  CXXBasePaths Paths;
7646  FindOverriddenMethod FOM;
7647  FOM.Method = MD;
7648  FOM.S = this;
7649  bool hasDeletedOverridenMethods = false;
7650  bool hasNonDeletedOverridenMethods = false;
7651  bool AddedAny = false;
7652  if (DC->lookupInBases(FOMPaths)) {
7653    for (auto *I : Paths.found_decls()) {
7654      if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7655        MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7656        if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7657            !CheckOverridingFunctionAttributes(MD, OldMD) &&
7658            !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7659            !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7660          hasDeletedOverridenMethods |= OldMD->isDeleted();
7661          hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7662          AddedAny = true;
7663        }
7664      }
7665    }
7666  }
7667
7668  if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7669    ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7670  }
7671  if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7672    ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7673  }
7674
7675  return AddedAny;
7676}
7677
7678namespace {
7679  // Struct for holding all of the extra arguments needed by
7680  // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7681  struct ActOnFDArgs {
7682    Scope *S;
7683    Declarator &D;
7684    MultiTemplateParamsArg TemplateParamLists;
7685    bool AddToScope;
7686  };
7687// end anonymous namespace
7688
7689namespace {
7690
7691// Callback to only accept typo corrections that have a non-zero edit distance.
7692// Also only accept corrections that have the same parent decl.
7693class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
7694 public:
7695  DifferentNameValidatorCCC(ASTContext &ContextFunctionDecl *TypoFD,
7696                            CXXRecordDecl *Parent)
7697      : Context(Context), OriginalFD(TypoFD),
7698        ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7699
7700  bool ValidateCandidate(const TypoCorrection &candidate) override {
7701    if (candidate.getEditDistance() == 0)
7702      return false;
7703
7704    SmallVector<unsigned1MismatchedParams;
7705    for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7706                                          CDeclEnd = candidate.end();
7707         CDecl != CDeclEnd; ++CDecl) {
7708      FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7709
7710      if (FD && !FD->hasBody() &&
7711          hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7712        if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7713          CXXRecordDecl *Parent = MD->getParent();
7714          if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7715            return true;
7716        } else if (!ExpectedParent) {
7717          return true;
7718        }
7719      }
7720    }
7721
7722    return false;
7723  }
7724
7725  std::unique_ptr<CorrectionCandidateCallbackclone() override {
7726    return llvm::make_unique<DifferentNameValidatorCCC>(*this);
7727  }
7728
7729 private:
7730  ASTContext &Context;
7731  FunctionDecl *OriginalFD;
7732  CXXRecordDecl *ExpectedParent;
7733};
7734
7735// end anonymous namespace
7736
7737void Sema::MarkTypoCorrectedFunctionDefinition(const NamedDecl *F) {
7738  TypoCorrectedFunctionDefinitions.insert(F);
7739}
7740
7741/// Generate diagnostics for an invalid function redeclaration.
7742///
7743/// This routine handles generating the diagnostic messages for an invalid
7744/// function redeclaration, including finding possible similar declarations
7745/// or performing typo correction if there are no previous declarations with
7746/// the same name.
7747///
7748/// Returns a NamedDecl iff typo correction was performed and substituting in
7749/// the new declaration name does not cause new errors.
7750static NamedDecl *DiagnoseInvalidRedeclaration(
7751    Sema &SemaRefLookupResult &PreviousFunctionDecl *NewFD,
7752    ActOnFDArgs &ExtraArgsbool IsLocalFriendScope *S) {
7753  DeclarationName Name = NewFD->getDeclName();
7754  DeclContext *NewDC = NewFD->getDeclContext();
7755  SmallVector<unsigned1MismatchedParams;
7756  SmallVector<std::pair<FunctionDecl *, unsigned>, 1NearMatches;
7757  TypoCorrection Correction;
7758  bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7759  unsigned DiagMsg =
7760    IsLocalFriend ? diag::err_no_matching_local_friend :
7761    NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
7762    diag::err_member_decl_does_not_match;
7763  LookupResult Prev(SemaRefNameNewFD->getLocation(),
7764                    IsLocalFriend ? Sema::LookupLocalFriendName
7765                                  : Sema::LookupOrdinaryName,
7766                    Sema::ForVisibleRedeclaration);
7767
7768  NewFD->setInvalidDecl();
7769  if (IsLocalFriend)
7770    SemaRef.LookupName(PrevS);
7771  else
7772    SemaRef.LookupQualifiedName(PrevNewDC);
7773   (0) . __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 7774, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!Prev.isAmbiguous() &&
7774 (0) . __assert_fail ("!Prev.isAmbiguous() && \"Cannot have an ambiguity in previous-declaration lookup\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 7774, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "Cannot have an ambiguity in previous-declaration lookup");
7775  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7776  DifferentNameValidatorCCC CCC(SemaRef.ContextNewFD,
7777                                MD ? MD->getParent() : nullptr);
7778  if (!Prev.empty()) {
7779    for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7780         Func != FuncEnd; ++Func) {
7781      FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7782      if (FD &&
7783          hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7784        // Add 1 to the index so that 0 can mean the mismatch didn't
7785        // involve a parameter
7786        unsigned ParamNum =
7787            MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7788        NearMatches.push_back(std::make_pair(FD, ParamNum));
7789      }
7790    }
7791  // If the qualified name lookup yielded nothing, try typo correction
7792  } else if ((Correction = SemaRef.CorrectTypo(
7793                  Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7794                  &ExtraArgs.D.getCXXScopeSpec(), CCCSema::CTK_ErrorRecovery,
7795                  IsLocalFriend ? nullptr : NewDC))) {
7796    // Set up everything for the call to ActOnFunctionDeclarator
7797    ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7798                              ExtraArgs.D.getIdentifierLoc());
7799    Previous.clear();
7800    Previous.setLookupName(Correction.getCorrection());
7801    for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7802                                    CDeclEnd = Correction.end();
7803         CDecl != CDeclEnd; ++CDecl) {
7804      FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7805      if (FD && !FD->hasBody() &&
7806          hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7807        Previous.addDecl(FD);
7808      }
7809    }
7810    bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7811
7812    NamedDecl *Result;
7813    // Retry building the function declaration with the new previous
7814    // declarations, and with errors suppressed.
7815    {
7816      // Trap errors.
7817      Sema::SFINAETrap Trap(SemaRef);
7818
7819      // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7820      // pieces need to verify the typo-corrected C++ declaration and hopefully
7821      // eliminate the need for the parameter pack ExtraArgs.
7822      Result = SemaRef.ActOnFunctionDeclarator(
7823          ExtraArgs.SExtraArgs.D,
7824          Correction.getCorrectionDecl()->getDeclContext(),
7825          NewFD->getTypeSourceInfo(), PreviousExtraArgs.TemplateParamLists,
7826          ExtraArgs.AddToScope);
7827
7828      if (Trap.hasErrorOccurred())
7829        Result = nullptr;
7830    }
7831
7832    if (Result) {
7833      // Determine which correction we picked.
7834      Decl *Canonical = Result->getCanonicalDecl();
7835      for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7836           I != E; ++I)
7837        if ((*I)->getCanonicalDecl() == Canonical)
7838          Correction.setCorrectionDecl(*I);
7839
7840      // Let Sema know about the correction.
7841      SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
7842      SemaRef.diagnoseTypo(
7843          Correction,
7844          SemaRef.PDiag(IsLocalFriend
7845                          ? diag::err_no_matching_local_friend_suggest
7846                          : diag::err_member_decl_does_not_match_suggest)
7847            << Name << NewDC << IsDefinition);
7848      return Result;
7849    }
7850
7851    // Pretend the typo correction never occurred
7852    ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7853                              ExtraArgs.D.getIdentifierLoc());
7854    ExtraArgs.D.setRedeclaration(wasRedeclaration);
7855    Previous.clear();
7856    Previous.setLookupName(Name);
7857  }
7858
7859  SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7860      << Name << NewDC << IsDefinition << NewFD->getLocation();
7861
7862  bool NewFDisConst = false;
7863  if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7864    NewFDisConst = NewMD->isConst();
7865
7866  for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7867       NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7868       NearMatch != NearMatchEnd; ++NearMatch) {
7869    FunctionDecl *FD = NearMatch->first;
7870    CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7871    bool FDisConst = MD && MD->isConst();
7872    bool IsMember = MD || !IsLocalFriend;
7873
7874    // FIXME: These notes are poorly worded for the local friend case.
7875    if (unsigned Idx = NearMatch->second) {
7876      ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7877      SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7878      if (Loc.isInvalid()) Loc = FD->getLocation();
7879      SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7880                                 : diag::note_local_decl_close_param_match)
7881        << Idx << FDParam->getType()
7882        << NewFD->getParamDecl(Idx - 1)->getType();
7883    } else if (FDisConst != NewFDisConst) {
7884      SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7885          << NewFDisConst << FD->getSourceRange().getEnd();
7886    } else
7887      SemaRef.Diag(FD->getLocation(),
7888                   IsMember ? diag::note_member_def_close_match
7889                            : diag::note_local_decl_close_match);
7890  }
7891  return nullptr;
7892}
7893
7894static StorageClass getFunctionStorageClass(Sema &SemaRefDeclarator &D) {
7895  switch (D.getDeclSpec().getStorageClassSpec()) {
7896  default: llvm_unreachable("Unknown storage class!");
7897  case DeclSpec::SCS_auto:
7898  case DeclSpec::SCS_register:
7899  case DeclSpec::SCS_mutable:
7900    SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7901                 diag::err_typecheck_sclass_func);
7902    D.getMutableDeclSpec().ClearStorageClassSpecs();
7903    D.setInvalidType();
7904    break;
7905  case DeclSpec::SCS_unspecifiedbreak;
7906  case DeclSpec::SCS_extern:
7907    if (D.getDeclSpec().isExternInLinkageSpec())
7908      return SC_None;
7909    return SC_Extern;
7910  case DeclSpec::SCS_static: {
7911    if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7912      // C99 6.7.1p5:
7913      //   The declaration of an identifier for a function that has
7914      //   block scope shall have no explicit storage-class specifier
7915      //   other than extern
7916      // See also (C++ [dcl.stc]p4).
7917      SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7918                   diag::err_static_block_func);
7919      break;
7920    } else
7921      return SC_Static;
7922  }
7923  case DeclSpec::SCS_private_externreturn SC_PrivateExtern;
7924  }
7925
7926  // No explicit storage class has already been returned
7927  return SC_None;
7928}
7929
7930static FunctionDeclCreateNewFunctionDecl(Sema &SemaRefDeclarator &D,
7931                                           DeclContext *DCQualType &R,
7932                                           TypeSourceInfo *TInfo,
7933                                           StorageClass SC,
7934                                           bool &IsVirtualOkay) {
7935  DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7936  DeclarationName Name = NameInfo.getName();
7937
7938  FunctionDecl *NewFD = nullptr;
7939  bool isInline = D.getDeclSpec().isInlineSpecified();
7940
7941  if (!SemaRef.getLangOpts().CPlusPlus) {
7942    // Determine whether the function was written with a
7943    // prototype. This true when:
7944    //   - there is a prototype in the declarator, or
7945    //   - the type R of the function is some kind of typedef or other non-
7946    //     attributed reference to a type name (which eventually refers to a
7947    //     function type).
7948    bool HasPrototype =
7949      (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7950      (!R->getAsAdjusted<FunctionType>() && R->isFunctionProtoType());
7951
7952    NewFD = FunctionDecl::Create(SemaRef.ContextDCD.getBeginLoc(), NameInfo,
7953                                 RTInfoSCisInlineHasPrototypefalse);
7954    if (D.isInvalidType())
7955      NewFD->setInvalidDecl();
7956
7957    return NewFD;
7958  }
7959
7960  bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7961  bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7962
7963  // Check that the return type is not an abstract class type.
7964  // For record types, this is done by the AbstractClassUsageDiagnoser once
7965  // the class has been completely parsed.
7966  if (!DC->isRecord() &&
7967      SemaRef.RequireNonAbstractType(
7968          D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7969          diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7970    D.setInvalidType();
7971
7972  if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7973    // This is a C++ constructor declaration.
7974     (0) . __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 7975, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(DC->isRecord() &&
7975 (0) . __assert_fail ("DC->isRecord() && \"Constructors can only be declared in a member context\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 7975, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           "Constructors can only be declared in a member context");
7976
7977    R = SemaRef.CheckConstructorDeclarator(DRSC);
7978    return CXXConstructorDecl::Create(
7979        SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfoR,
7980        TInfoisExplicitisInline,
7981        /*isImplicitlyDeclared=*/falseisConstexpr);
7982
7983  } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7984    // This is a C++ destructor declaration.
7985    if (DC->isRecord()) {
7986      R = SemaRef.CheckDestructorDeclarator(DRSC);
7987      CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7988      CXXDestructorDecl *NewDD =
7989          CXXDestructorDecl::Create(SemaRef.ContextRecordD.getBeginLoc(),
7990                                    NameInfoRTInfoisInline,
7991                                    /*isImplicitlyDeclared=*/false);
7992
7993      // If the destructor needs an implicit exception specification, set it
7994      // now. FIXME: It'd be nice to be able to create the right type to start
7995      // with, but the type needs to reference the destructor declaration.
7996      if (SemaRef.getLangOpts().CPlusPlus11)
7997        SemaRef.AdjustDestructorExceptionSpec(NewDD);
7998
7999      IsVirtualOkay = true;
8000      return NewDD;
8001
8002    } else {
8003      SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8004      D.setInvalidType();
8005
8006      // Create a FunctionDecl to satisfy the function definition parsing
8007      // code path.
8008      return FunctionDecl::Create(SemaRef.ContextDCD.getBeginLoc(),
8009                                  D.getIdentifierLoc(), NameRTInfoSC,
8010                                  isInline,
8011                                  /*hasPrototype=*/trueisConstexpr);
8012    }
8013
8014  } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8015    if (!DC->isRecord()) {
8016      SemaRef.Diag(D.getIdentifierLoc(),
8017           diag::err_conv_function_not_member);
8018      return nullptr;
8019    }
8020
8021    SemaRef.CheckConversionDeclarator(DRSC);
8022    IsVirtualOkay = true;
8023    return CXXConversionDecl::Create(
8024        SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfoR,
8025        TInfoisInlineisExplicitisConstexprSourceLocation());
8026
8027  } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8028    SemaRef.CheckDeductionGuideDeclarator(DRSC);
8029
8030    return CXXDeductionGuideDecl::Create(SemaRef.ContextDCD.getBeginLoc(),
8031                                         isExplicitNameInfoRTInfo,
8032                                         D.getEndLoc());
8033  } else if (DC->isRecord()) {
8034    // If the name of the function is the same as the name of the record,
8035    // then this must be an invalid constructor that has a return type.
8036    // (The parser checks for a return type and makes the declarator a
8037    // constructor if it has no return type).
8038    if (Name.getAsIdentifierInfo() &&
8039        Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8040      SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8041        << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8042        << SourceRange(D.getIdentifierLoc());
8043      return nullptr;
8044    }
8045
8046    // This is a C++ method declaration.
8047    CXXMethodDecl *Ret = CXXMethodDecl::Create(
8048        SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfoR,
8049        TInfoSCisInlineisConstexprSourceLocation());
8050    IsVirtualOkay = !Ret->isStatic();
8051    return Ret;
8052  } else {
8053    bool isFriend =
8054        SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8055    if (!isFriend && SemaRef.CurContext->isRecord())
8056      return nullptr;
8057
8058    // Determine whether the function was written with a
8059    // prototype. This true when:
8060    //   - we're in C++ (where every function has a prototype),
8061    return FunctionDecl::Create(SemaRef.ContextDCD.getBeginLoc(), NameInfo,
8062                                RTInfoSCisInlinetrue /*HasPrototype*/,
8063                                isConstexpr);
8064  }
8065}
8066
8067enum OpenCLParamType {
8068  ValidKernelParam,
8069  PtrPtrKernelParam,
8070  PtrKernelParam,
8071  InvalidAddrSpacePtrKernelParam,
8072  InvalidKernelParam,
8073  RecordKernelParam
8074};
8075
8076static bool isOpenCLSizeDependentType(ASTContext &CQualType Ty) {
8077  // Size dependent types are just typedefs to normal integer types
8078  // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8079  // integers other than by their names.
8080  StringRef SizeTypeNames[] = {"size_t""intptr_t""uintptr_t""ptrdiff_t"};
8081
8082  // Remove typedefs one by one until we reach a typedef
8083  // for a size dependent type.
8084  QualType DesugaredTy = Ty;
8085  do {
8086    ArrayRef<StringRefNames(SizeTypeNames);
8087    auto Match =
8088        std::find(Names.begin(), Names.end(), DesugaredTy.getAsString());
8089    if (Names.end() != Match)
8090      return true;
8091
8092    Ty = DesugaredTy;
8093    DesugaredTy = Ty.getSingleStepDesugaredType(C);
8094  } while (DesugaredTy != Ty);
8095
8096  return false;
8097}
8098
8099static OpenCLParamType getOpenCLKernelParameterType(Sema &SQualType PT) {
8100  if (PT->isPointerType()) {
8101    QualType PointeeType = PT->getPointeeType();
8102    if (PointeeType->isPointerType())
8103      return PtrPtrKernelParam;
8104    if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8105        PointeeType.getAddressSpace() == LangAS::opencl_private ||
8106        PointeeType.getAddressSpace() == LangAS::Default)
8107      return InvalidAddrSpacePtrKernelParam;
8108    return PtrKernelParam;
8109  }
8110
8111  // OpenCL v1.2 s6.9.k:
8112  // Arguments to kernel functions in a program cannot be declared with the
8113  // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8114  // uintptr_t or a struct and/or union that contain fields declared to be one
8115  // of these built-in scalar types.
8116  if (isOpenCLSizeDependentType(S.getASTContext()PT))
8117    return InvalidKernelParam;
8118
8119  if (PT->isImageType())
8120    return PtrKernelParam;
8121
8122  if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8123    return InvalidKernelParam;
8124
8125  // OpenCL extension spec v1.2 s9.5:
8126  // This extension adds support for half scalar and vector types as built-in
8127  // types that can be used for arithmetic operations, conversions etc.
8128  if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
8129    return InvalidKernelParam;
8130
8131  if (PT->isRecordType())
8132    return RecordKernelParam;
8133
8134  // Look into an array argument to check if it has a forbidden type.
8135  if (PT->isArrayType()) {
8136    const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8137    // Call ourself to check an underlying type of an array. Since the
8138    // getPointeeOrArrayElementType returns an innermost type which is not an
8139    // array, this recursive call only happens once.
8140    return getOpenCLKernelParameterType(SQualType(UnderlyingTy0));
8141  }
8142
8143  return ValidKernelParam;
8144}
8145
8146static void checkIsValidOpenCLKernelParameter(
8147  Sema &S,
8148  Declarator &D,
8149  ParmVarDecl *Param,
8150  llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
8151  QualType PT = Param->getType();
8152
8153  // Cache the valid types we encounter to avoid rechecking structs that are
8154  // used again
8155  if (ValidTypes.count(PT.getTypePtr()))
8156    return;
8157
8158  switch (getOpenCLKernelParameterType(SPT)) {
8159  case PtrPtrKernelParam:
8160    // OpenCL v1.2 s6.9.a:
8161    // A kernel function argument cannot be declared as a
8162    // pointer to a pointer type.
8163    S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
8164    D.setInvalidType();
8165    return;
8166
8167  case InvalidAddrSpacePtrKernelParam:
8168    // OpenCL v1.0 s6.5:
8169    // __kernel function arguments declared to be a pointer of a type can point
8170    // to one of the following address spaces only : __global, __local or
8171    // __constant.
8172    S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
8173    D.setInvalidType();
8174    return;
8175
8176    // OpenCL v1.2 s6.9.k:
8177    // Arguments to kernel functions in a program cannot be declared with the
8178    // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8179    // uintptr_t or a struct and/or union that contain fields declared to be
8180    // one of these built-in scalar types.
8181
8182  case InvalidKernelParam:
8183    // OpenCL v1.2 s6.8 n:
8184    // A kernel function argument cannot be declared
8185    // of event_t type.
8186    // Do not diagnose half type since it is diagnosed as invalid argument
8187    // type for any function elsewhere.
8188    if (!PT->isHalfType()) {
8189      S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8190
8191      // Explain what typedefs are involved.
8192      const TypedefType *Typedef = nullptr;
8193      while ((Typedef = PT->getAs<TypedefType>())) {
8194        SourceLocation Loc = Typedef->getDecl()->getLocation();
8195        // SourceLocation may be invalid for a built-in type.
8196        if (Loc.isValid())
8197          S.Diag(Loc, diag::note_entity_declared_at) << PT;
8198        PT = Typedef->desugar();
8199      }
8200    }
8201
8202    D.setInvalidType();
8203    return;
8204
8205  case PtrKernelParam:
8206  case ValidKernelParam:
8207    ValidTypes.insert(PT.getTypePtr());
8208    return;
8209
8210  case RecordKernelParam:
8211    break;
8212  }
8213
8214  // Track nested structs we will inspect
8215  SmallVector<const Decl *, 4VisitStack;
8216
8217  // Track where we are in the nested structs. Items will migrate from
8218  // VisitStack to HistoryStack as we do the DFS for bad field.
8219  SmallVector<const FieldDecl *, 4HistoryStack;
8220  HistoryStack.push_back(nullptr);
8221
8222  // At this point we already handled everything except of a RecordType or
8223  // an ArrayType of a RecordType.
8224   (0) . __assert_fail ("(PT->isArrayType() || PT->isRecordType()) && \"Unexpected type.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 8224, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
8225  const RecordType *RecTy =
8226      PT->getPointeeOrArrayElementType()->getAs<RecordType>();
8227  const RecordDecl *OrigRecDecl = RecTy->getDecl();
8228
8229  VisitStack.push_back(RecTy->getDecl());
8230   (0) . __assert_fail ("VisitStack.back() && \"First decl null?\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 8230, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(VisitStack.back() && "First decl null?");
8231
8232  do {
8233    const Decl *Next = VisitStack.pop_back_val();
8234    if (!Next) {
8235      assert(!HistoryStack.empty());
8236      // Found a marker, we have gone up a level
8237      if (const FieldDecl *Hist = HistoryStack.pop_back_val())
8238        ValidTypes.insert(Hist->getType().getTypePtr());
8239
8240      continue;
8241    }
8242
8243    // Adds everything except the original parameter declaration (which is not a
8244    // field itself) to the history stack.
8245    const RecordDecl *RD;
8246    if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
8247      HistoryStack.push_back(Field);
8248
8249      QualType FieldTy = Field->getType();
8250      // Other field types (known to be valid or invalid) are handled while we
8251      // walk around RecordDecl::fields().
8252       (0) . __assert_fail ("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 8253, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
8253 (0) . __assert_fail ("(FieldTy->isArrayType() || FieldTy->isRecordType()) && \"Unexpected type.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 8253, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">             "Unexpected type.");
8254      const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
8255
8256      RD = FieldRecTy->castAs<RecordType>()->getDecl();
8257    } else {
8258      RD = cast<RecordDecl>(Next);
8259    }
8260
8261    // Add a null marker so we know when we've gone back up a level
8262    VisitStack.push_back(nullptr);
8263
8264    for (const auto *FD : RD->fields()) {
8265      QualType QT = FD->getType();
8266
8267      if (ValidTypes.count(QT.getTypePtr()))
8268        continue;
8269
8270      OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
8271      if (ParamType == ValidKernelParam)
8272        continue;
8273
8274      if (ParamType == RecordKernelParam) {
8275        VisitStack.push_back(FD);
8276        continue;
8277      }
8278
8279      // OpenCL v1.2 s6.9.p:
8280      // Arguments to kernel functions that are declared to be a struct or union
8281      // do not allow OpenCL objects to be passed as elements of the struct or
8282      // union.
8283      if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
8284          ParamType == InvalidAddrSpacePtrKernelParam) {
8285        S.Diag(Param->getLocation(),
8286               diag::err_record_with_pointers_kernel_param)
8287          << PT->isUnionType()
8288          << PT;
8289      } else {
8290        S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
8291      }
8292
8293      S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
8294          << OrigRecDecl->getDeclName();
8295
8296      // We have an error, now let's go back up through history and show where
8297      // the offending field came from
8298      for (ArrayRef<const FieldDecl *>::const_iterator
8299               I = HistoryStack.begin() + 1,
8300               E = HistoryStack.end();
8301           I != E; ++I) {
8302        const FieldDecl *OuterField = *I;
8303        S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
8304          << OuterField->getType();
8305      }
8306
8307      S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
8308        << QT->isPointerType()
8309        << QT;
8310      D.setInvalidType();
8311      return;
8312    }
8313  } while (!VisitStack.empty());
8314}
8315
8316/// Find the DeclContext in which a tag is implicitly declared if we see an
8317/// elaborated type specifier in the specified context, and lookup finds
8318/// nothing.
8319static DeclContext *getTagInjectionContext(DeclContext *DC) {
8320  while (!DC->isFileContext() && !DC->isFunctionOrMethod())
8321    DC = DC->getParent();
8322  return DC;
8323}
8324
8325/// Find the Scope in which a tag is implicitly declared if we see an
8326/// elaborated type specifier in the specified context, and lookup finds
8327/// nothing.
8328static Scope *getTagInjectionScope(Scope *Sconst LangOptions &LangOpts) {
8329  while (S->isClassScope() ||
8330         (LangOpts.CPlusPlus &&
8331          S->isFunctionPrototypeScope()) ||
8332         ((S->getFlags() & Scope::DeclScope) == 0) ||
8333         (S->getEntity() && S->getEntity()->isTransparentContext()))
8334    S = S->getParent();
8335  return S;
8336}
8337
8338NamedDecl*
8339Sema::ActOnFunctionDeclarator(Scope *SDeclarator &DDeclContext *DC,
8340                              TypeSourceInfo *TInfoLookupResult &Previous,
8341                              MultiTemplateParamsArg TemplateParamLists,
8342                              bool &AddToScope) {
8343  QualType R = TInfo->getType();
8344
8345  isFunctionType()", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 8345, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(R->isFunctionType());
8346
8347  // TODO: consider using NameInfo for diagnostic.
8348  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
8349  DeclarationName Name = NameInfo.getName();
8350  StorageClass SC = getFunctionStorageClass(*thisD);
8351
8352  if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
8353    Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
8354         diag::err_invalid_thread)
8355      << DeclSpec::getSpecifierName(TSCS);
8356
8357  if (D.isFirstDeclarationOfMember())
8358    adjustMemberFunctionCC(RD.isStaticMember(), D.isCtorOrDtor(),
8359                           D.getIdentifierLoc());
8360
8361  bool isFriend = false;
8362  FunctionTemplateDecl *FunctionTemplate = nullptr;
8363  bool isMemberSpecialization = false;
8364  bool isFunctionTemplateSpecialization = false;
8365
8366  bool isDependentClassScopeExplicitSpecialization = false;
8367  bool HasExplicitTemplateArgs = false;
8368  TemplateArgumentListInfo TemplateArgs;
8369
8370  bool isVirtualOkay = false;
8371
8372  DeclContext *OriginalDC = DC;
8373  bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
8374
8375  FunctionDecl *NewFD = CreateNewFunctionDecl(*thisDDCRTInfoSC,
8376                                              isVirtualOkay);
8377  if (!NewFDreturn nullptr;
8378
8379  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
8380    NewFD->setTopLevelDeclInObjCContainer();
8381
8382  // Set the lexical context. If this is a function-scope declaration, or has a
8383  // C++ scope specifier, or is the object of a friend declaration, the lexical
8384  // context will be different from the semantic context.
8385  NewFD->setLexicalDeclContext(CurContext);
8386
8387  if (IsLocalExternDecl)
8388    NewFD->setLocalExternDecl();
8389
8390  if (getLangOpts().CPlusPlus) {
8391    bool isInline = D.getDeclSpec().isInlineSpecified();
8392    bool isVirtual = D.getDeclSpec().isVirtualSpecified();
8393    bool isExplicit = D.getDeclSpec().isExplicitSpecified();
8394    bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
8395    isFriend = D.getDeclSpec().isFriendSpecified();
8396    if (isFriend && !isInline && D.isFunctionDefinition()) {
8397      // C++ [class.friend]p5
8398      //   A function can be defined in a friend declaration of a
8399      //   class . . . . Such a function is implicitly inline.
8400      NewFD->setImplicitlyInline();
8401    }
8402
8403    // If this is a method defined in an __interface, and is not a constructor
8404    // or an overloaded operator, then set the pure flag (isVirtual will already
8405    // return true).
8406    if (const CXXRecordDecl *Parent =
8407          dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
8408      if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
8409        NewFD->setPure(true);
8410
8411      // C++ [class.union]p2
8412      //   A union can have member functions, but not virtual functions.
8413      if (isVirtual && Parent->isUnion())
8414        Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
8415    }
8416
8417    SetNestedNameSpecifier(*thisNewFDD);
8418    isMemberSpecialization = false;
8419    isFunctionTemplateSpecialization = false;
8420    if (D.isInvalidType())
8421      NewFD->setInvalidDecl();
8422
8423    // Match up the template parameter lists with the scope specifier, then
8424    // determine whether we have a template or a template specialization.
8425    bool Invalid = false;
8426    if (TemplateParameterList *TemplateParams =
8427            MatchTemplateParametersToScopeSpecifier(
8428                D.getDeclSpec().getBeginLoc(), D.getIdentifierLoc(),
8429                D.getCXXScopeSpec(),
8430                D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
8431                    ? D.getName().TemplateId
8432                    : nullptr,
8433                TemplateParamLists, isFriend, isMemberSpecialization,
8434                Invalid)) {
8435      if (TemplateParams->size() > 0) {
8436        // This is a function template
8437
8438        // Check that we can declare a template here.
8439        if (CheckTemplateDeclScope(STemplateParams))
8440          NewFD->setInvalidDecl();
8441
8442        // A destructor cannot be a template.
8443        if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8444          Diag(NewFD->getLocation(), diag::err_destructor_template);
8445          NewFD->setInvalidDecl();
8446        }
8447
8448        // If we're adding a template to a dependent context, we may need to
8449        // rebuilding some of the types used within the template parameter list,
8450        // now that we know what the current instantiation is.
8451        if (DC->isDependentContext()) {
8452          ContextRAII SavedContext(*thisDC);
8453          if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
8454            Invalid = true;
8455        }
8456
8457        FunctionTemplate = FunctionTemplateDecl::Create(ContextDC,
8458                                                        NewFD->getLocation(),
8459                                                        NameTemplateParams,
8460                                                        NewFD);
8461        FunctionTemplate->setLexicalDeclContext(CurContext);
8462        NewFD->setDescribedFunctionTemplate(FunctionTemplate);
8463
8464        // For source fidelity, store the other template param lists.
8465        if (TemplateParamLists.size() > 1) {
8466          NewFD->setTemplateParameterListsInfo(Context,
8467                                               TemplateParamLists.drop_back(1));
8468        }
8469      } else {
8470        // This is a function template specialization.
8471        isFunctionTemplateSpecialization = true;
8472        // For source fidelity, store all the template param lists.
8473        if (TemplateParamLists.size() > 0)
8474          NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8475
8476        // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
8477        if (isFriend) {
8478          // We want to remove the "template<>", found here.
8479          SourceRange RemoveRange = TemplateParams->getSourceRange();
8480
8481          // If we remove the template<> and the name is not a
8482          // template-id, we're actually silently creating a problem:
8483          // the friend declaration will refer to an untemplated decl,
8484          // and clearly the user wants a template specialization.  So
8485          // we need to insert '<>' after the name.
8486          SourceLocation InsertLoc;
8487          if (D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
8488            InsertLoc = D.getName().getSourceRange().getEnd();
8489            InsertLoc = getLocForEndOfToken(InsertLoc);
8490          }
8491
8492          Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8493            << Name << RemoveRange
8494            << FixItHint::CreateRemoval(RemoveRange)
8495            << FixItHint::CreateInsertion(InsertLoc, "<>");
8496        }
8497      }
8498    } else {
8499      // All template param lists were matched against the scope specifier:
8500      // this is NOT (an explicit specialization of) a template.
8501      if (TemplateParamLists.size() > 0)
8502        // For source fidelity, store all the template param lists.
8503        NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8504    }
8505
8506    if (Invalid) {
8507      NewFD->setInvalidDecl();
8508      if (FunctionTemplate)
8509        FunctionTemplate->setInvalidDecl();
8510    }
8511
8512    // C++ [dcl.fct.spec]p5:
8513    //   The virtual specifier shall only be used in declarations of
8514    //   nonstatic class member functions that appear within a
8515    //   member-specification of a class declaration; see 10.3.
8516    //
8517    if (isVirtual && !NewFD->isInvalidDecl()) {
8518      if (!isVirtualOkay) {
8519        Diag(D.getDeclSpec().getVirtualSpecLoc(),
8520             diag::err_virtual_non_function);
8521      } else if (!CurContext->isRecord()) {
8522        // 'virtual' was specified outside of the class.
8523        Diag(D.getDeclSpec().getVirtualSpecLoc(),
8524             diag::err_virtual_out_of_class)
8525          << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8526      } else if (NewFD->getDescribedFunctionTemplate()) {
8527        // C++ [temp.mem]p3:
8528        //  A member function template shall not be virtual.
8529        Diag(D.getDeclSpec().getVirtualSpecLoc(),
8530             diag::err_virtual_member_function_template)
8531          << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8532      } else {
8533        // Okay: Add virtual to the method.
8534        NewFD->setVirtualAsWritten(true);
8535      }
8536
8537      if (getLangOpts().CPlusPlus14 &&
8538          NewFD->getReturnType()->isUndeducedType())
8539        Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8540    }
8541
8542    if (getLangOpts().CPlusPlus14 &&
8543        (NewFD->isDependentContext() ||
8544         (isFriend && CurContext->isDependentContext())) &&
8545        NewFD->getReturnType()->isUndeducedType()) {
8546      // If the function template is referenced directly (for instance, as a
8547      // member of the current instantiation), pretend it has a dependent type.
8548      // This is not really justified by the standard, but is the only sane
8549      // thing to do.
8550      // FIXME: For a friend function, we have not marked the function as being
8551      // a friend yet, so 'isDependentContext' on the FD doesn't work.
8552      const FunctionProtoType *FPT =
8553          NewFD->getType()->castAs<FunctionProtoType>();
8554      QualType Result =
8555          SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8556      NewFD->setType(Context.getFunctionType(ResultFPT->getParamTypes(),
8557                                             FPT->getExtProtoInfo()));
8558    }
8559
8560    // C++ [dcl.fct.spec]p3:
8561    //  The inline specifier shall not appear on a block scope function
8562    //  declaration.
8563    if (isInline && !NewFD->isInvalidDecl()) {
8564      if (CurContext->isFunctionOrMethod()) {
8565        // 'inline' is not allowed on block scope function declaration.
8566        Diag(D.getDeclSpec().getInlineSpecLoc(),
8567             diag::err_inline_declaration_block_scope) << Name
8568          << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8569      }
8570    }
8571
8572    // C++ [dcl.fct.spec]p6:
8573    //  The explicit specifier shall be used only in the declaration of a
8574    //  constructor or conversion function within its class definition;
8575    //  see 12.3.1 and 12.3.2.
8576    if (isExplicit && !NewFD->isInvalidDecl() &&
8577        !isa<CXXDeductionGuideDecl>(NewFD)) {
8578      if (!CurContext->isRecord()) {
8579        // 'explicit' was specified outside of the class.
8580        Diag(D.getDeclSpec().getExplicitSpecLoc(),
8581             diag::err_explicit_out_of_class)
8582          << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8583      } else if (!isa<CXXConstructorDecl>(NewFD) &&
8584                 !isa<CXXConversionDecl>(NewFD)) {
8585        // 'explicit' was specified on a function that wasn't a constructor
8586        // or conversion function.
8587        Diag(D.getDeclSpec().getExplicitSpecLoc(),
8588             diag::err_explicit_non_ctor_or_conv_function)
8589          << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8590      }
8591    }
8592
8593    if (isConstexpr) {
8594      // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8595      // are implicitly inline.
8596      NewFD->setImplicitlyInline();
8597
8598      // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8599      // be either constructors or to return a literal type. Therefore,
8600      // destructors cannot be declared constexpr.
8601      if (isa<CXXDestructorDecl>(NewFD))
8602        Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8603    }
8604
8605    // If __module_private__ was specified, mark the function accordingly.
8606    if (D.getDeclSpec().isModulePrivateSpecified()) {
8607      if (isFunctionTemplateSpecialization) {
8608        SourceLocation ModulePrivateLoc
8609          = D.getDeclSpec().getModulePrivateSpecLoc();
8610        Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8611          << 0
8612          << FixItHint::CreateRemoval(ModulePrivateLoc);
8613      } else {
8614        NewFD->setModulePrivate();
8615        if (FunctionTemplate)
8616          FunctionTemplate->setModulePrivate();
8617      }
8618    }
8619
8620    if (isFriend) {
8621      if (FunctionTemplate) {
8622        FunctionTemplate->setObjectOfFriendDecl();
8623        FunctionTemplate->setAccess(AS_public);
8624      }
8625      NewFD->setObjectOfFriendDecl();
8626      NewFD->setAccess(AS_public);
8627    }
8628
8629    // If a function is defined as defaulted or deleted, mark it as such now.
8630    // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8631    // definition kind to FDK_Definition.
8632    switch (D.getFunctionDefinitionKind()) {
8633      case FDK_Declaration:
8634      case FDK_Definition:
8635        break;
8636
8637      case FDK_Defaulted:
8638        NewFD->setDefaulted();
8639        break;
8640
8641      case FDK_Deleted:
8642        NewFD->setDeletedAsWritten();
8643        break;
8644    }
8645
8646    if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8647        D.isFunctionDefinition()) {
8648      // C++ [class.mfct]p2:
8649      //   A member function may be defined (8.4) in its class definition, in
8650      //   which case it is an inline member function (7.1.2)
8651      NewFD->setImplicitlyInline();
8652    }
8653
8654    if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8655        !CurContext->isRecord()) {
8656      // C++ [class.static]p1:
8657      //   A data or function member of a class may be declared static
8658      //   in a class definition, in which case it is a static member of
8659      //   the class.
8660
8661      // Complain about the 'static' specifier if it's on an out-of-line
8662      // member function definition.
8663
8664      // MSVC permits the use of a 'static' storage specifier on an out-of-line
8665      // member function template declaration, warn about this.
8666      Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8667           NewFD->getDescribedFunctionTemplate() && getLangOpts().MSVCCompat
8668           ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
8669        << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8670    }
8671
8672    // C++11 [except.spec]p15:
8673    //   A deallocation function with no exception-specification is treated
8674    //   as if it were specified with noexcept(true).
8675    const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8676    if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8677         Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8678        getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8679      NewFD->setType(Context.getFunctionType(
8680          FPT->getReturnType(), FPT->getParamTypes(),
8681          FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8682  }
8683
8684  // Filter out previous declarations that don't match the scope.
8685  FilterLookupForScope(PreviousOriginalDCSshouldConsiderLinkage(NewFD),
8686                       D.getCXXScopeSpec().isNotEmpty() ||
8687                       isMemberSpecialization ||
8688                       isFunctionTemplateSpecialization);
8689
8690  // Handle GNU asm-label extension (encoded as an attribute).
8691  if (Expr *E = (Expr*) D.getAsmLabel()) {
8692    // The parser guarantees this is a string.
8693    StringLiteral *SE = cast<StringLiteral>(E);
8694    NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8695                                                SE->getString(), 0));
8696  } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8697    llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8698      ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8699    if (I != ExtnameUndeclaredIdentifiers.end()) {
8700      if (isDeclExternC(NewFD)) {
8701        NewFD->addAttr(I->second);
8702        ExtnameUndeclaredIdentifiers.erase(I);
8703      } else
8704        Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8705            << /*Variable*/0 << NewFD;
8706    }
8707  }
8708
8709  // Copy the parameter declarations from the declarator D to the function
8710  // declaration NewFD, if they are available.  First scavenge them into Params.
8711  SmallVector<ParmVarDecl*, 16Params;
8712  unsigned FTIIdx;
8713  if (D.isFunctionDeclarator(FTIIdx)) {
8714    DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8715
8716    // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8717    // function that takes no arguments, not a function that takes a
8718    // single void argument.
8719    // We let through "const void" here because Sema::GetTypeForDeclarator
8720    // already checks for that case.
8721    if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8722      for (unsigned i = 0e = FTI.NumParamsi != e; ++i) {
8723        ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8724         (0) . __assert_fail ("Param->getDeclContext() != NewFD && \"Was set before ?\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 8724, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Param->getDeclContext() != NewFD && "Was set before ?");
8725        Param->setDeclContext(NewFD);
8726        Params.push_back(Param);
8727
8728        if (Param->isInvalidDecl())
8729          NewFD->setInvalidDecl();
8730      }
8731    }
8732
8733    if (!getLangOpts().CPlusPlus) {
8734      // In C, find all the tag declarations from the prototype and move them
8735      // into the function DeclContext. Remove them from the surrounding tag
8736      // injection context of the function, which is typically but not always
8737      // the TU.
8738      DeclContext *PrototypeTagContext =
8739          getTagInjectionContext(NewFD->getLexicalDeclContext());
8740      for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8741        auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8742
8743        // We don't want to reparent enumerators. Look at their parent enum
8744        // instead.
8745        if (!TD) {
8746          if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8747            TD = cast<EnumDecl>(ECD->getDeclContext());
8748        }
8749        if (!TD)
8750          continue;
8751        DeclContext *TagDC = TD->getLexicalDeclContext();
8752        if (!TagDC->containsDecl(TD))
8753          continue;
8754        TagDC->removeDecl(TD);
8755        TD->setDeclContext(NewFD);
8756        NewFD->addDecl(TD);
8757
8758        // Preserve the lexical DeclContext if it is not the surrounding tag
8759        // injection context of the FD. In this example, the semantic context of
8760        // E will be f and the lexical context will be S, while both the
8761        // semantic and lexical contexts of S will be f:
8762        //   void f(struct S { enum E { a } f; } s);
8763        if (TagDC != PrototypeTagContext)
8764          TD->setLexicalDeclContext(TagDC);
8765      }
8766    }
8767  } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8768    // When we're declaring a function with a typedef, typeof, etc as in the
8769    // following example, we'll need to synthesize (unnamed)
8770    // parameters for use in the declaration.
8771    //
8772    // @code
8773    // typedef void fn(int);
8774    // fn f;
8775    // @endcode
8776
8777    // Synthesize a parameter for each argument type.
8778    for (const auto &AI : FT->param_types()) {
8779      ParmVarDecl *Param =
8780          BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8781      Param->setScopeInfo(0, Params.size());
8782      Params.push_back(Param);
8783    }
8784  } else {
8785     (0) . __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 8786, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8786 (0) . __assert_fail ("R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 && \"Should not need args for typedef of non-prototype fn\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 8786, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           "Should not need args for typedef of non-prototype fn");
8787  }
8788
8789  // Finally, we know we have the right number of parameters, install them.
8790  NewFD->setParams(Params);
8791
8792  if (D.getDeclSpec().isNoreturnSpecified())
8793    NewFD->addAttr(
8794        ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8795                                       Context, 0));
8796
8797  // Functions returning a variably modified type violate C99 6.7.5.2p2
8798  // because all functions have linkage.
8799  if (!NewFD->isInvalidDecl() &&
8800      NewFD->getReturnType()->isVariablyModifiedType()) {
8801    Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8802    NewFD->setInvalidDecl();
8803  }
8804
8805  // Apply an implicit SectionAttr if '#pragma clang section text' is active
8806  if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
8807      !NewFD->hasAttr<SectionAttr>()) {
8808    NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(Context,
8809                                                 PragmaClangTextSection.SectionName,
8810                                                 PragmaClangTextSection.PragmaLocation));
8811  }
8812
8813  // Apply an implicit SectionAttr if #pragma code_seg is active.
8814  if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8815      !NewFD->hasAttr<SectionAttr>()) {
8816    NewFD->addAttr(
8817        SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8818                                    CodeSegStack.CurrentValue->getString(),
8819                                    CodeSegStack.CurrentPragmaLocation));
8820    if (UnifySection(CodeSegStack.CurrentValue->getString(),
8821                     ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8822                         ASTContext::PSF_Read,
8823                     NewFD))
8824      NewFD->dropAttr<SectionAttr>();
8825  }
8826
8827  // Apply an implicit CodeSegAttr from class declspec or
8828  // apply an implicit SectionAttr from #pragma code_seg if active.
8829  if (!NewFD->hasAttr<CodeSegAttr>()) {
8830    if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
8831                                                                 D.isFunctionDefinition())) {
8832      NewFD->addAttr(SAttr);
8833    }
8834  }
8835
8836  // Handle attributes.
8837  ProcessDeclAttributes(SNewFDD);
8838
8839  if (getLangOpts().OpenCL) {
8840    // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8841    // type declaration will generate a compilation error.
8842    LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
8843    if (AddressSpace != LangAS::Default) {
8844      Diag(NewFD->getLocation(),
8845           diag::err_opencl_return_value_with_address_space);
8846      NewFD->setInvalidDecl();
8847    }
8848  }
8849
8850  if (!getLangOpts().CPlusPlus) {
8851    // Perform semantic checking on the function declaration.
8852    if (!NewFD->isInvalidDecl() && NewFD->isMain())
8853      CheckMain(NewFDD.getDeclSpec());
8854
8855    if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8856      CheckMSVCRTEntryPoint(NewFD);
8857
8858    if (!NewFD->isInvalidDecl())
8859      D.setRedeclaration(CheckFunctionDeclaration(SNewFDPrevious,
8860                                                  isMemberSpecialization));
8861    else if (!Previous.empty())
8862      // Recover gracefully from an invalid redeclaration.
8863      D.setRedeclaration(true);
8864     (0) . __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult..FoundOverloaded) && \"previous declaration set still overloaded\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 8866, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8865 (0) . __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult..FoundOverloaded) && \"previous declaration set still overloaded\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 8866, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">            Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8866 (0) . __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult..FoundOverloaded) && \"previous declaration set still overloaded\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 8866, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           "previous declaration set still overloaded");
8867
8868    // Diagnose no-prototype function declarations with calling conventions that
8869    // don't support variadic calls. Only do this in C and do it after merging
8870    // possibly prototyped redeclarations.
8871    const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8872    if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8873      CallingConv CC = FT->getExtInfo().getCC();
8874      if (!supportsVariadicCall(CC)) {
8875        // Windows system headers sometimes accidentally use stdcall without
8876        // (void) parameters, so we relax this to a warning.
8877        int DiagID =
8878            CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8879        Diag(NewFD->getLocation(), DiagID)
8880            << FunctionType::getNameForCallConv(CC);
8881      }
8882    }
8883  } else {
8884    // C++11 [replacement.functions]p3:
8885    //  The program's definitions shall not be specified as inline.
8886    //
8887    // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8888    //
8889    // Suppress the diagnostic if the function is __attribute__((used)), since
8890    // that forces an external definition to be emitted.
8891    if (D.getDeclSpec().isInlineSpecified() &&
8892        NewFD->isReplaceableGlobalAllocationFunction() &&
8893        !NewFD->hasAttr<UsedAttr>())
8894      Diag(D.getDeclSpec().getInlineSpecLoc(),
8895           diag::ext_operator_new_delete_declared_inline)
8896        << NewFD->getDeclName();
8897
8898    // If the declarator is a template-id, translate the parser's template
8899    // argument list into our AST format.
8900    if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
8901      TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8902      TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8903      TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8904      ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8905                                         TemplateId->NumArgs);
8906      translateTemplateArguments(TemplateArgsPtr,
8907                                 TemplateArgs);
8908
8909      HasExplicitTemplateArgs = true;
8910
8911      if (NewFD->isInvalidDecl()) {
8912        HasExplicitTemplateArgs = false;
8913      } else if (FunctionTemplate) {
8914        // Function template with explicit template arguments.
8915        Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8916          << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8917
8918        HasExplicitTemplateArgs = false;
8919      } else {
8920        ' for this decl") ? static_cast (0) . __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 8922, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert((isFunctionTemplateSpecialization ||
8921' for this decl") ? static_cast (0) . __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 8922, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">                D.getDeclSpec().isFriendSpecified()) &&
8922' for this decl") ? static_cast (0) . __assert_fail ("(isFunctionTemplateSpecialization || D.getDeclSpec().isFriendSpecified()) && \"should have a 'template<>' for this decl\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 8922, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">               "should have a 'template<>' for this decl");
8923        // "friend void foo<>(int);" is an implicit specialization decl.
8924        isFunctionTemplateSpecialization = true;
8925      }
8926    } else if (isFriend && isFunctionTemplateSpecialization) {
8927      // This combination is only possible in a recovery case;  the user
8928      // wrote something like:
8929      //   template <> friend void foo(int);
8930      // which we're recovering from as if the user had written:
8931      //   friend void foo<>(int);
8932      // Go ahead and fake up a template id.
8933      HasExplicitTemplateArgs = true;
8934      TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8935      TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8936    }
8937
8938    // We do not add HD attributes to specializations here because
8939    // they may have different constexpr-ness compared to their
8940    // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8941    // may end up with different effective targets. Instead, a
8942    // specialization inherits its target attributes from its template
8943    // in the CheckFunctionTemplateSpecialization() call below.
8944    if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8945      maybeAddCUDAHostDeviceAttrs(NewFDPrevious);
8946
8947    // If it's a friend (and only if it's a friend), it's possible
8948    // that either the specialized function type or the specialized
8949    // template is dependent, and therefore matching will fail.  In
8950    // this case, don't check the specialization yet.
8951    bool InstantiationDependent = false;
8952    if (isFunctionTemplateSpecialization && isFriend &&
8953        (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8954         TemplateSpecializationType::anyDependentTemplateArguments(
8955            TemplateArgs,
8956            InstantiationDependent))) {
8957       (0) . __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 8958, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(HasExplicitTemplateArgs &&
8958 (0) . __assert_fail ("HasExplicitTemplateArgs && \"friend function specialization without template args\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 8958, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">             "friend function specialization without template args");
8959      if (CheckDependentFunctionTemplateSpecialization(NewFDTemplateArgs,
8960                                                       Previous))
8961        NewFD->setInvalidDecl();
8962    } else if (isFunctionTemplateSpecialization) {
8963      if (CurContext->isDependentContext() && CurContext->isRecord()
8964          && !isFriend) {
8965        isDependentClassScopeExplicitSpecialization = true;
8966      } else if (!NewFD->isInvalidDecl() &&
8967                 CheckFunctionTemplateSpecialization(
8968                     NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
8969                     Previous))
8970        NewFD->setInvalidDecl();
8971
8972      // C++ [dcl.stc]p1:
8973      //   A storage-class-specifier shall not be specified in an explicit
8974      //   specialization (14.7.3)
8975      FunctionTemplateSpecializationInfo *Info =
8976          NewFD->getTemplateSpecializationInfo();
8977      if (Info && SC != SC_None) {
8978        if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8979          Diag(NewFD->getLocation(),
8980               diag::err_explicit_specialization_inconsistent_storage_class)
8981            << SC
8982            << FixItHint::CreateRemoval(
8983                                      D.getDeclSpec().getStorageClassSpecLoc());
8984
8985        else
8986          Diag(NewFD->getLocation(),
8987               diag::ext_explicit_specialization_storage_class)
8988            << FixItHint::CreateRemoval(
8989                                      D.getDeclSpec().getStorageClassSpecLoc());
8990      }
8991    } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
8992      if (CheckMemberSpecialization(NewFDPrevious))
8993          NewFD->setInvalidDecl();
8994    }
8995
8996    // Perform semantic checking on the function declaration.
8997    if (!isDependentClassScopeExplicitSpecialization) {
8998      if (!NewFD->isInvalidDecl() && NewFD->isMain())
8999        CheckMain(NewFDD.getDeclSpec());
9000
9001      if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9002        CheckMSVCRTEntryPoint(NewFD);
9003
9004      if (!NewFD->isInvalidDecl())
9005        D.setRedeclaration(CheckFunctionDeclaration(SNewFDPrevious,
9006                                                    isMemberSpecialization));
9007      else if (!Previous.empty())
9008        // Recover gracefully from an invalid redeclaration.
9009        D.setRedeclaration(true);
9010    }
9011
9012     (0) . __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult..FoundOverloaded) && \"previous declaration set still overloaded\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 9014, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9013 (0) . __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult..FoundOverloaded) && \"previous declaration set still overloaded\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 9014, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">            Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9014 (0) . __assert_fail ("(NewFD->isInvalidDecl() || !D.isRedeclaration() || Previous.getResultKind() != LookupResult..FoundOverloaded) && \"previous declaration set still overloaded\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 9014, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           "previous declaration set still overloaded");
9015
9016    NamedDecl *PrincipalDecl = (FunctionTemplate
9017                                ? cast<NamedDecl>(FunctionTemplate)
9018                                : NewFD);
9019
9020    if (isFriend && NewFD->getPreviousDecl()) {
9021      AccessSpecifier Access = AS_public;
9022      if (!NewFD->isInvalidDecl())
9023        Access = NewFD->getPreviousDecl()->getAccess();
9024
9025      NewFD->setAccess(Access);
9026      if (FunctionTemplateFunctionTemplate->setAccess(Access);
9027    }
9028
9029    if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9030        PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
9031      PrincipalDecl->setNonMemberOperator();
9032
9033    // If we have a function template, check the template parameter
9034    // list. This will check and merge default template arguments.
9035    if (FunctionTemplate) {
9036      FunctionTemplateDecl *PrevTemplate =
9037                                     FunctionTemplate->getPreviousDecl();
9038      CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9039                       PrevTemplate ? PrevTemplate->getTemplateParameters()
9040                                    : nullptr,
9041                            D.getDeclSpec().isFriendSpecified()
9042                              ? (D.isFunctionDefinition()
9043                                   ? TPC_FriendFunctionTemplateDefinition
9044                                   : TPC_FriendFunctionTemplate)
9045                              : (D.getCXXScopeSpec().isSet() &&
9046                                 DC && DC->isRecord() &&
9047                                 DC->isDependentContext())
9048                                  ? TPC_ClassTemplateMember
9049                                  : TPC_FunctionTemplate);
9050    }
9051
9052    if (NewFD->isInvalidDecl()) {
9053      // Ignore all the rest of this.
9054    } else if (!D.isRedeclaration()) {
9055      struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9056                                       AddToScope };
9057      // Fake up an access specifier if it's supposed to be a class member.
9058      if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9059        NewFD->setAccess(AS_public);
9060
9061      // Qualified decls generally require a previous declaration.
9062      if (D.getCXXScopeSpec().isSet()) {
9063        // ...with the major exception of templated-scope or
9064        // dependent-scope friend declarations.
9065
9066        // TODO: we currently also suppress this check in dependent
9067        // contexts because (1) the parameter depth will be off when
9068        // matching friend templates and (2) we might actually be
9069        // selecting a friend based on a dependent factor.  But there
9070        // are situations where these conditions don't apply and we
9071        // can actually do this check immediately.
9072        //
9073        // Unless the scope is dependent, it's always an error if qualified
9074        // redeclaration lookup found nothing at all. Diagnose that now;
9075        // nothing will diagnose that error later.
9076        if (isFriend &&
9077            (D.getCXXScopeSpec().getScopeRep()->isDependent() ||
9078             (!Previous.empty() && (TemplateParamLists.size() ||
9079                                    CurContext->isDependentContext())))) {
9080          // ignore these
9081        } else {
9082          // The user tried to provide an out-of-line definition for a
9083          // function that is a member of a class or namespace, but there
9084          // was no such member function declared (C++ [class.mfct]p2,
9085          // C++ [namespace.memdef]p2). For example:
9086          //
9087          // class X {
9088          //   void f() const;
9089          // };
9090          //
9091          // void X::f() { } // ill-formed
9092          //
9093          // Complain about this problem, and attempt to suggest close
9094          // matches (e.g., those that differ only in cv-qualifiers and
9095          // whether the parameter types are references).
9096
9097          if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9098                  *thisPreviousNewFDExtraArgsfalsenullptr)) {
9099            AddToScope = ExtraArgs.AddToScope;
9100            return Result;
9101          }
9102        }
9103
9104        // Unqualified local friend declarations are required to resolve
9105        // to something.
9106      } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
9107        if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
9108                *thisPreviousNewFDExtraArgstrueS)) {
9109          AddToScope = ExtraArgs.AddToScope;
9110          return Result;
9111        }
9112      }
9113    } else if (!D.isFunctionDefinition() &&
9114               isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
9115               !isFriend && !isFunctionTemplateSpecialization &&
9116               !isMemberSpecialization) {
9117      // An out-of-line member function declaration must also be a
9118      // definition (C++ [class.mfct]p2).
9119      // Note that this is not the case for explicit specializations of
9120      // function templates or member functions of class templates, per
9121      // C++ [temp.expl.spec]p2. We also allow these declarations as an
9122      // extension for compatibility with old SWIG code which likes to
9123      // generate them.
9124      Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
9125        << D.getCXXScopeSpec().getRange();
9126    }
9127  }
9128
9129  ProcessPragmaWeak(SNewFD);
9130  checkAttributesAfterMerging(*this, *NewFD);
9131
9132  AddKnownFunctionAttributes(NewFD);
9133
9134  if (NewFD->hasAttr<OverloadableAttr>() &&
9135      !NewFD->getType()->getAs<FunctionProtoType>()) {
9136    Diag(NewFD->getLocation(),
9137         diag::err_attribute_overloadable_no_prototype)
9138      << NewFD;
9139
9140    // Turn this into a variadic function with no parameters.
9141    const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
9142    FunctionProtoType::ExtProtoInfo EPI(
9143        Context.getDefaultCallingConvention(truefalse));
9144    EPI.Variadic = true;
9145    EPI.ExtInfo = FT->getExtInfo();
9146
9147    QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
9148    NewFD->setType(R);
9149  }
9150
9151  // If there's a #pragma GCC visibility in scope, and this isn't a class
9152  // member, set the visibility of this function.
9153  if (!DC->isRecord() && NewFD->isExternallyVisible())
9154    AddPushedVisibilityAttribute(NewFD);
9155
9156  // If there's a #pragma clang arc_cf_code_audited in scope, consider
9157  // marking the function.
9158  AddCFAuditedAttribute(NewFD);
9159
9160  // If this is a function definition, check if we have to apply optnone due to
9161  // a pragma.
9162  if(D.isFunctionDefinition())
9163    AddRangeBasedOptnone(NewFD);
9164
9165  // If this is the first declaration of an extern C variable, update
9166  // the map of such variables.
9167  if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
9168      isIncompleteDeclExternC(*thisNewFD))
9169    RegisterLocallyScopedExternCDecl(NewFDS);
9170
9171  // Set this FunctionDecl's range up to the right paren.
9172  NewFD->setRangeEnd(D.getSourceRange().getEnd());
9173
9174  if (D.isRedeclaration() && !Previous.empty()) {
9175    NamedDecl *Prev = Previous.getRepresentativeDecl();
9176    checkDLLAttributeRedeclaration(*thisPrevNewFD,
9177                                   isMemberSpecialization ||
9178                                       isFunctionTemplateSpecialization,
9179                                   D.isFunctionDefinition());
9180  }
9181
9182  if (getLangOpts().CUDA) {
9183    IdentifierInfo *II = NewFD->getIdentifier();
9184    if (II && II->isStr(getCudaConfigureFuncName()) &&
9185        !NewFD->isInvalidDecl() &&
9186        NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
9187      if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
9188        Diag(NewFD->getLocation(), diag::err_config_scalar_return)
9189            << getCudaConfigureFuncName();
9190      Context.setcudaConfigureCallDecl(NewFD);
9191    }
9192
9193    // Variadic functions, other than a *declaration* of printf, are not allowed
9194    // in device-side CUDA code, unless someone passed
9195    // -fcuda-allow-variadic-functions.
9196    if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
9197        (NewFD->hasAttr<CUDADeviceAttr>() ||
9198         NewFD->hasAttr<CUDAGlobalAttr>()) &&
9199        !(II && II->isStr("printf") && NewFD->isExternC() &&
9200          !D.isFunctionDefinition())) {
9201      Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
9202    }
9203  }
9204
9205  MarkUnusedFileScopedDecl(NewFD);
9206
9207  if (getLangOpts().CPlusPlus) {
9208    if (FunctionTemplate) {
9209      if (NewFD->isInvalidDecl())
9210        FunctionTemplate->setInvalidDecl();
9211      return FunctionTemplate;
9212    }
9213
9214    if (isMemberSpecialization && !NewFD->isInvalidDecl())
9215      CompleteMemberSpecialization(NewFDPrevious);
9216  }
9217
9218  if (NewFD->hasAttr<OpenCLKernelAttr>()) {
9219    // OpenCL v1.2 s6.8 static is invalid for kernel functions.
9220    if ((getLangOpts().OpenCLVersion >= 120)
9221        && (SC == SC_Static)) {
9222      Diag(D.getIdentifierLoc(), diag::err_static_kernel);
9223      D.setInvalidType();
9224    }
9225
9226    // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
9227    if (!NewFD->getReturnType()->isVoidType()) {
9228      SourceRange RTRange = NewFD->getReturnTypeSourceRange();
9229      Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
9230          << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
9231                                : FixItHint());
9232      D.setInvalidType();
9233    }
9234
9235    llvm::SmallPtrSet<const Type *, 16> ValidTypes;
9236    for (auto Param : NewFD->parameters())
9237      checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
9238  }
9239  for (const ParmVarDecl *Param : NewFD->parameters()) {
9240    QualType PT = Param->getType();
9241
9242    // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
9243    // types.
9244    if (getLangOpts().OpenCLVersion >= 200) {
9245      if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
9246        QualType ElemTy = PipeTy->getElementType();
9247          if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
9248            Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
9249            D.setInvalidType();
9250          }
9251      }
9252    }
9253  }
9254
9255  // Here we have an function template explicit specialization at class scope.
9256  // The actual specialization will be postponed to template instatiation
9257  // time via the ClassScopeFunctionSpecializationDecl node.
9258  if (isDependentClassScopeExplicitSpecialization) {
9259    ClassScopeFunctionSpecializationDecl *NewSpec =
9260                         ClassScopeFunctionSpecializationDecl::Create(
9261                                ContextCurContextNewFD->getLocation(),
9262                                cast<CXXMethodDecl>(NewFD),
9263                                HasExplicitTemplateArgsTemplateArgs);
9264    CurContext->addDecl(NewSpec);
9265    AddToScope = false;
9266  }
9267
9268  // Diagnose availability attributes. Availability cannot be used on functions
9269  // that are run during load/unload.
9270  if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
9271    if (NewFD->hasAttr<ConstructorAttr>()) {
9272      Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9273          << 1;
9274      NewFD->dropAttr<AvailabilityAttr>();
9275    }
9276    if (NewFD->hasAttr<DestructorAttr>()) {
9277      Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
9278          << 2;
9279      NewFD->dropAttr<AvailabilityAttr>();
9280    }
9281  }
9282
9283  return NewFD;
9284}
9285
9286/// Return a CodeSegAttr from a containing class.  The Microsoft docs say
9287/// when __declspec(code_seg) "is applied to a class, all member functions of
9288/// the class and nested classes -- this includes compiler-generated special
9289/// member functions -- are put in the specified segment."
9290/// The actual behavior is a little more complicated. The Microsoft compiler
9291/// won't check outer classes if there is an active value from #pragma code_seg.
9292/// The CodeSeg is always applied from the direct parent but only from outer
9293/// classes when the #pragma code_seg stack is empty. See:
9294/// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
9295/// available since MS has removed the page.
9296static Attr *getImplicitCodeSegAttrFromClass(Sema &Sconst FunctionDecl *FD) {
9297  const auto *Method = dyn_cast<CXXMethodDecl>(FD);
9298  if (!Method)
9299    return nullptr;
9300  const CXXRecordDecl *Parent = Method->getParent();
9301  if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9302    Attr *NewAttr = SAttr->clone(S.getASTContext());
9303    NewAttr->setImplicit(true);
9304    return NewAttr;
9305  }
9306
9307  // The Microsoft compiler won't check outer classes for the CodeSeg
9308  // when the #pragma code_seg stack is active.
9309  if (S.CodeSegStack.CurrentValue)
9310   return nullptr;
9311
9312  while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
9313    if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
9314      Attr *NewAttr = SAttr->clone(S.getASTContext());
9315      NewAttr->setImplicit(true);
9316      return NewAttr;
9317    }
9318  }
9319  return nullptr;
9320}
9321
9322/// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
9323/// containing class. Otherwise it will return implicit SectionAttr if the
9324/// function is a definition and there is an active value on CodeSegStack
9325/// (from the current #pragma code-seg value).
9326///
9327/// \param FD Function being declared.
9328/// \param IsDefinition Whether it is a definition or just a declarartion.
9329/// \returns A CodeSegAttr or SectionAttr to apply to the function or
9330///          nullptr if no attribute should be added.
9331Attr *Sema::getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD,
9332                                                       bool IsDefinition) {
9333  if (Attr *A = getImplicitCodeSegAttrFromClass(*thisFD))
9334    return A;
9335  if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
9336      CodeSegStack.CurrentValue) {
9337    return SectionAttr::CreateImplicit(getASTContext(),
9338                                       SectionAttr::Declspec_allocate,
9339                                       CodeSegStack.CurrentValue->getString(),
9340                                       CodeSegStack.CurrentPragmaLocation);
9341  }
9342  return nullptr;
9343}
9344
9345/// Determines if we can perform a correct type check for \p D as a
9346/// redeclaration of \p PrevDecl. If not, we can generally still perform a
9347/// best-effort check.
9348///
9349/// \param NewD The new declaration.
9350/// \param OldD The old declaration.
9351/// \param NewT The portion of the type of the new declaration to check.
9352/// \param OldT The portion of the type of the old declaration to check.
9353bool Sema::canFullyTypeCheckRedeclaration(ValueDecl *NewDValueDecl *OldD,
9354                                          QualType NewTQualType OldT) {
9355  if (!NewD->getLexicalDeclContext()->isDependentContext())
9356    return true;
9357
9358  // For dependently-typed local extern declarations and friends, we can't
9359  // perform a correct type check in general until instantiation:
9360  //
9361  //   int f();
9362  //   template<typename T> void g() { T f(); }
9363  //
9364  // (valid if g() is only instantiated with T = int).
9365  if (NewT->isDependentType() &&
9366      (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
9367    return false;
9368
9369  // Similarly, if the previous declaration was a dependent local extern
9370  // declaration, we don't really know its type yet.
9371  if (OldT->isDependentType() && OldD->isLocalExternDecl())
9372    return false;
9373
9374  return true;
9375}
9376
9377/// Checks if the new declaration declared in dependent context must be
9378/// put in the same redeclaration chain as the specified declaration.
9379///
9380/// \param D Declaration that is checked.
9381/// \param PrevDecl Previous declaration found with proper lookup method for the
9382///                 same declaration name.
9383/// \returns True if D must be added to the redeclaration chain which PrevDecl
9384///          belongs to.
9385///
9386bool Sema::shouldLinkDependentDeclWithPrevious(Decl *DDecl *PrevDecl) {
9387  if (!D->getLexicalDeclContext()->isDependentContext())
9388    return true;
9389
9390  // Don't chain dependent friend function definitions until instantiation, to
9391  // permit cases like
9392  //
9393  //   void func();
9394  //   template<typename T> class C1 { friend void func() {} };
9395  //   template<typename T> class C2 { friend void func() {} };
9396  //
9397  // ... which is valid if only one of C1 and C2 is ever instantiated.
9398  //
9399  // FIXME: This need only apply to function definitions. For now, we proxy
9400  // this by checking for a file-scope function. We do not want this to apply
9401  // to friend declarations nominating member functions, because that gets in
9402  // the way of access checks.
9403  if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
9404    return false;
9405
9406  auto *VD = dyn_cast<ValueDecl>(D);
9407  auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
9408  return !VD || !PrevVD ||
9409         canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
9410                                        PrevVD->getType());
9411}
9412
9413/// Check the target attribute of the function for MultiVersion
9414/// validity.
9415///
9416/// Returns true if there was an error, false otherwise.
9417static bool CheckMultiVersionValue(Sema &Sconst FunctionDecl *FD) {
9418  const auto *TA = FD->getAttr<TargetAttr>();
9419   (0) . __assert_fail ("TA && \"MultiVersion Candidate requires a target attribute\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 9419, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(TA && "MultiVersion Candidate requires a target attribute");
9420  TargetAttr::ParsedTargetAttr ParseInfo = TA->parse();
9421  const TargetInfo &TargetInfo = S.Context.getTargetInfo();
9422  enum ErrType { Feature = 0Architecture = 1 };
9423
9424  if (!ParseInfo.Architecture.empty() &&
9425      !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
9426    S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9427        << Architecture << ParseInfo.Architecture;
9428    return true;
9429  }
9430
9431  for (const auto &Feat : ParseInfo.Features) {
9432    auto BareFeat = StringRef{Feat}.substr(1);
9433    if (Feat[0] == '-') {
9434      S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9435          << Feature << ("no-" + BareFeat).str();
9436      return true;
9437    }
9438
9439    if (!TargetInfo.validateCpuSupports(BareFeat) ||
9440        !TargetInfo.isValidFeatureName(BareFeat)) {
9441      S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
9442          << Feature << BareFeat;
9443      return true;
9444    }
9445  }
9446  return false;
9447}
9448
9449static bool HasNonMultiVersionAttributes(const FunctionDecl *FD,
9450                                         MultiVersionKind MVType) {
9451  for (const Attr *A : FD->attrs()) {
9452    switch (A->getKind()) {
9453    case attr::CPUDispatch:
9454    case attr::CPUSpecific:
9455      if (MVType != MultiVersionKind::CPUDispatch &&
9456          MVType != MultiVersionKind::CPUSpecific)
9457        return true;
9458      break;
9459    case attr::Target:
9460      if (MVType != MultiVersionKind::Target)
9461        return true;
9462      break;
9463    default:
9464      return true;
9465    }
9466  }
9467  return false;
9468}
9469
9470static bool CheckMultiVersionAdditionalRules(Sema &Sconst FunctionDecl *OldFD,
9471                                             const FunctionDecl *NewFD,
9472                                             bool CausesMV,
9473                                             MultiVersionKind MVType) {
9474  enum DoesntSupport {
9475    FuncTemplates = 0,
9476    VirtFuncs = 1,
9477    DeducedReturn = 2,
9478    Constructors = 3,
9479    Destructors = 4,
9480    DeletedFuncs = 5,
9481    DefaultedFuncs = 6,
9482    ConstexprFuncs = 7,
9483  };
9484  enum Different {
9485    CallingConv = 0,
9486    ReturnType = 1,
9487    ConstexprSpec = 2,
9488    InlineSpec = 3,
9489    StorageClass = 4,
9490    Linkage = 5
9491  };
9492
9493  bool IsCPUSpecificCPUDispatchMVType =
9494      MVType == MultiVersionKind::CPUDispatch ||
9495      MVType == MultiVersionKind::CPUSpecific;
9496
9497  if (OldFD && !OldFD->getType()->getAs<FunctionProtoType>()) {
9498    S.Diag(OldFD->getLocation(), diag::err_multiversion_noproto);
9499    S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9500    return true;
9501  }
9502
9503  if (!NewFD->getType()->getAs<FunctionProtoType>())
9504    return S.Diag(NewFD->getLocation(), diag::err_multiversion_noproto);
9505
9506  if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9507    S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9508    if (OldFD)
9509      S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9510    return true;
9511  }
9512
9513  // For now, disallow all other attributes.  These should be opt-in, but
9514  // an analysis of all of them is a future FIXME.
9515  if (CausesMV && OldFD && HasNonMultiVersionAttributes(OldFDMVType)) {
9516    S.Diag(OldFD->getLocation(), diag::err_multiversion_no_other_attrs)
9517        << IsCPUSpecificCPUDispatchMVType;
9518    S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9519    return true;
9520  }
9521
9522  if (HasNonMultiVersionAttributes(NewFD, MVType))
9523    return S.Diag(NewFD->getLocation(), diag::err_multiversion_no_other_attrs)
9524           << IsCPUSpecificCPUDispatchMVType;
9525
9526  if (NewFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
9527    return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9528           << IsCPUSpecificCPUDispatchMVType << FuncTemplates;
9529
9530  if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
9531    if (NewCXXFD->isVirtual())
9532      return S.Diag(NewCXXFD->getLocation(),
9533                    diag::err_multiversion_doesnt_support)
9534             << IsCPUSpecificCPUDispatchMVType << VirtFuncs;
9535
9536    if (const auto *NewCXXCtor = dyn_cast<CXXConstructorDecl>(NewFD))
9537      return S.Diag(NewCXXCtor->getLocation(),
9538                    diag::err_multiversion_doesnt_support)
9539             << IsCPUSpecificCPUDispatchMVType << Constructors;
9540
9541    if (const auto *NewCXXDtor = dyn_cast<CXXDestructorDecl>(NewFD))
9542      return S.Diag(NewCXXDtor->getLocation(),
9543                    diag::err_multiversion_doesnt_support)
9544             << IsCPUSpecificCPUDispatchMVType << Destructors;
9545  }
9546
9547  if (NewFD->isDeleted())
9548    return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9549           << IsCPUSpecificCPUDispatchMVType << DeletedFuncs;
9550
9551  if (NewFD->isDefaulted())
9552    return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9553           << IsCPUSpecificCPUDispatchMVType << DefaultedFuncs;
9554
9555  if (NewFD->isConstexpr() && (MVType == MultiVersionKind::CPUDispatch ||
9556                               MVType == MultiVersionKind::CPUSpecific))
9557    return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9558           << IsCPUSpecificCPUDispatchMVType << ConstexprFuncs;
9559
9560  QualType NewQType = S.getASTContext().getCanonicalType(NewFD->getType());
9561  const auto *NewType = cast<FunctionType>(NewQType);
9562  QualType NewReturnType = NewType->getReturnType();
9563
9564  if (NewReturnType->isUndeducedType())
9565    return S.Diag(NewFD->getLocation(), diag::err_multiversion_doesnt_support)
9566           << IsCPUSpecificCPUDispatchMVType << DeducedReturn;
9567
9568  // Only allow transition to MultiVersion if it hasn't been used.
9569  if (OldFD && CausesMV && OldFD->isUsed(false))
9570    return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
9571
9572  // Ensure the return type is identical.
9573  if (OldFD) {
9574    QualType OldQType = S.getASTContext().getCanonicalType(OldFD->getType());
9575    const auto *OldType = cast<FunctionType>(OldQType);
9576    FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
9577    FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
9578
9579    if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
9580      return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9581             << CallingConv;
9582
9583    QualType OldReturnType = OldType->getReturnType();
9584
9585    if (OldReturnType != NewReturnType)
9586      return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9587             << ReturnType;
9588
9589    if (OldFD->isConstexpr() != NewFD->isConstexpr())
9590      return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9591             << ConstexprSpec;
9592
9593    if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
9594      return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9595             << InlineSpec;
9596
9597    if (OldFD->getStorageClass() != NewFD->getStorageClass())
9598      return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9599             << StorageClass;
9600
9601    if (OldFD->isExternC() != NewFD->isExternC())
9602      return S.Diag(NewFD->getLocation(), diag::err_multiversion_diff)
9603             << Linkage;
9604
9605    if (S.CheckEquivalentExceptionSpec(
9606            OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
9607            NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
9608      return true;
9609  }
9610  return false;
9611}
9612
9613/// Check the validity of a multiversion function declaration that is the
9614/// first of its kind. Also sets the multiversion'ness' of the function itself.
9615///
9616/// This sets NewFD->isInvalidDecl() to true if there was an error.
9617///
9618/// Returns true if there was an error, false otherwise.
9619static bool CheckMultiVersionFirstFunction(Sema &SFunctionDecl *FD,
9620                                           MultiVersionKind MVType,
9621                                           const TargetAttr *TA,
9622                                           const CPUDispatchAttr *CPUDisp,
9623                                           const CPUSpecificAttr *CPUSpec) {
9624   (0) . __assert_fail ("MVType != MultiVersionKind..None && \"Function lacks multiversion attribute\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 9625, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(MVType != MultiVersionKind::None &&
9625 (0) . __assert_fail ("MVType != MultiVersionKind..None && \"Function lacks multiversion attribute\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 9625, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "Function lacks multiversion attribute");
9626
9627  // Target only causes MV if it is default, otherwise this is a normal
9628  // function.
9629  if (MVType == MultiVersionKind::Target && !TA->isDefaultVersion())
9630    return false;
9631
9632  if (MVType == MultiVersionKind::Target && CheckMultiVersionValue(SFD)) {
9633    FD->setInvalidDecl();
9634    return true;
9635  }
9636
9637  if (CheckMultiVersionAdditionalRules(SnullptrFDtrueMVType)) {
9638    FD->setInvalidDecl();
9639    return true;
9640  }
9641
9642  FD->setIsMultiVersion();
9643  return false;
9644}
9645
9646static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD) {
9647  for (const Decl *D = FD->getPreviousDecl(); DD = D->getPreviousDecl()) {
9648    if (D->getAsFunction()->getMultiVersionKind() != MultiVersionKind::None)
9649      return true;
9650  }
9651
9652  return false;
9653}
9654
9655static bool CheckTargetCausesMultiVersioning(
9656    Sema &SFunctionDecl *OldFDFunctionDecl *NewFDconst TargetAttr *NewTA,
9657    bool &RedeclarationNamedDecl *&OldDeclbool &MergeTypeWithPrevious,
9658    LookupResult &Previous) {
9659  const auto *OldTA = OldFD->getAttr<TargetAttr>();
9660  TargetAttr::ParsedTargetAttr NewParsed = NewTA->parse();
9661  // Sort order doesn't matter, it just needs to be consistent.
9662  llvm::sort(NewParsed.Features);
9663
9664  // If the old decl is NOT MultiVersioned yet, and we don't cause that
9665  // to change, this is a simple redeclaration.
9666  if (!NewTA->isDefaultVersion() &&
9667      (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
9668    return false;
9669
9670  // Otherwise, this decl causes MultiVersioning.
9671  if (!S.getASTContext().getTargetInfo().supportsMultiVersioning()) {
9672    S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
9673    S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9674    NewFD->setInvalidDecl();
9675    return true;
9676  }
9677
9678  if (CheckMultiVersionAdditionalRules(SOldFDNewFDtrue,
9679                                       MultiVersionKind::Target)) {
9680    NewFD->setInvalidDecl();
9681    return true;
9682  }
9683
9684  if (CheckMultiVersionValue(SNewFD)) {
9685    NewFD->setInvalidDecl();
9686    return true;
9687  }
9688
9689  // If this is 'default', permit the forward declaration.
9690  if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
9691    Redeclaration = true;
9692    OldDecl = OldFD;
9693    OldFD->setIsMultiVersion();
9694    NewFD->setIsMultiVersion();
9695    return false;
9696  }
9697
9698  if (CheckMultiVersionValue(SOldFD)) {
9699    S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9700    NewFD->setInvalidDecl();
9701    return true;
9702  }
9703
9704  TargetAttr::ParsedTargetAttr OldParsed =
9705      OldTA->parse(std::less<std::string>());
9706
9707  if (OldParsed == NewParsed) {
9708    S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9709    S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9710    NewFD->setInvalidDecl();
9711    return true;
9712  }
9713
9714  for (const auto *FD : OldFD->redecls()) {
9715    const auto *CurTA = FD->getAttr<TargetAttr>();
9716    // We allow forward declarations before ANY multiversioning attributes, but
9717    // nothing after the fact.
9718    if (PreviousDeclsHaveMultiVersionAttribute(FD) &&
9719        (!CurTA || CurTA->isInherited())) {
9720      S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
9721          << 0;
9722      S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
9723      NewFD->setInvalidDecl();
9724      return true;
9725    }
9726  }
9727
9728  OldFD->setIsMultiVersion();
9729  NewFD->setIsMultiVersion();
9730  Redeclaration = false;
9731  MergeTypeWithPrevious = false;
9732  OldDecl = nullptr;
9733  Previous.clear();
9734  return false;
9735}
9736
9737/// Check the validity of a new function declaration being added to an existing
9738/// multiversioned declaration collection.
9739static bool CheckMultiVersionAdditionalDecl(
9740    Sema &SFunctionDecl *OldFDFunctionDecl *NewFD,
9741    MultiVersionKind NewMVTypeconst TargetAttr *NewTA,
9742    const CPUDispatchAttr *NewCPUDispconst CPUSpecificAttr *NewCPUSpec,
9743    bool &RedeclarationNamedDecl *&OldDeclbool &MergeTypeWithPrevious,
9744    LookupResult &Previous) {
9745
9746  MultiVersionKind OldMVType = OldFD->getMultiVersionKind();
9747  // Disallow mixing of multiversioning types.
9748  if ((OldMVType == MultiVersionKind::Target &&
9749       NewMVType != MultiVersionKind::Target) ||
9750      (NewMVType == MultiVersionKind::Target &&
9751       OldMVType != MultiVersionKind::Target)) {
9752    S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9753    S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
9754    NewFD->setInvalidDecl();
9755    return true;
9756  }
9757
9758  TargetAttr::ParsedTargetAttr NewParsed;
9759  if (NewTA) {
9760    NewParsed = NewTA->parse();
9761    llvm::sort(NewParsed.Features);
9762  }
9763
9764  bool UseMemberUsingDeclRules =
9765      S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
9766
9767  // Next, check ALL non-overloads to see if this is a redeclaration of a
9768  // previous member of the MultiVersion set.
9769  for (NamedDecl *ND : Previous) {
9770    FunctionDecl *CurFD = ND->getAsFunction();
9771    if (!CurFD)
9772      continue;
9773    if (S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
9774      continue;
9775
9776    if (NewMVType == MultiVersionKind::Target) {
9777      const auto *CurTA = CurFD->getAttr<TargetAttr>();
9778      if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
9779        NewFD->setIsMultiVersion();
9780        Redeclaration = true;
9781        OldDecl = ND;
9782        return false;
9783      }
9784
9785      TargetAttr::ParsedTargetAttr CurParsed =
9786          CurTA->parse(std::less<std::string>());
9787      if (CurParsed == NewParsed) {
9788        S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
9789        S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9790        NewFD->setInvalidDecl();
9791        return true;
9792      }
9793    } else {
9794      const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
9795      const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
9796      // Handle CPUDispatch/CPUSpecific versions.
9797      // Only 1 CPUDispatch function is allowed, this will make it go through
9798      // the redeclaration errors.
9799      if (NewMVType == MultiVersionKind::CPUDispatch &&
9800          CurFD->hasAttr<CPUDispatchAttr>()) {
9801        if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
9802            std::equal(
9803                CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
9804                NewCPUDisp->cpus_begin(),
9805                [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9806                  return Cur->getName() == New->getName();
9807                })) {
9808          NewFD->setIsMultiVersion();
9809          Redeclaration = true;
9810          OldDecl = ND;
9811          return false;
9812        }
9813
9814        // If the declarations don't match, this is an error condition.
9815        S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
9816        S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9817        NewFD->setInvalidDecl();
9818        return true;
9819      }
9820      if (NewMVType == MultiVersionKind::CPUSpecific && CurCPUSpec) {
9821
9822        if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
9823            std::equal(
9824                CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
9825                NewCPUSpec->cpus_begin(),
9826                [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
9827                  return Cur->getName() == New->getName();
9828                })) {
9829          NewFD->setIsMultiVersion();
9830          Redeclaration = true;
9831          OldDecl = ND;
9832          return false;
9833        }
9834
9835        // Only 1 version of CPUSpecific is allowed for each CPU.
9836        for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
9837          for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
9838            if (CurII == NewII) {
9839              S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
9840                  << NewII;
9841              S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
9842              NewFD->setInvalidDecl();
9843              return true;
9844            }
9845          }
9846        }
9847      }
9848      // If the two decls aren't the same MVType, there is no possible error
9849      // condition.
9850    }
9851  }
9852
9853  // Else, this is simply a non-redecl case.  Checking the 'value' is only
9854  // necessary in the Target case, since The CPUSpecific/Dispatch cases are
9855  // handled in the attribute adding step.
9856  if (NewMVType == MultiVersionKind::Target &&
9857      CheckMultiVersionValue(SNewFD)) {
9858    NewFD->setInvalidDecl();
9859    return true;
9860  }
9861
9862  if (CheckMultiVersionAdditionalRules(SOldFDNewFD,
9863                                       !OldFD->isMultiVersion(), NewMVType)) {
9864    NewFD->setInvalidDecl();
9865    return true;
9866  }
9867
9868  // Permit forward declarations in the case where these two are compatible.
9869  if (!OldFD->isMultiVersion()) {
9870    OldFD->setIsMultiVersion();
9871    NewFD->setIsMultiVersion();
9872    Redeclaration = true;
9873    OldDecl = OldFD;
9874    return false;
9875  }
9876
9877  NewFD->setIsMultiVersion();
9878  Redeclaration = false;
9879  MergeTypeWithPrevious = false;
9880  OldDecl = nullptr;
9881  Previous.clear();
9882  return false;
9883}
9884
9885
9886/// Check the validity of a mulitversion function declaration.
9887/// Also sets the multiversion'ness' of the function itself.
9888///
9889/// This sets NewFD->isInvalidDecl() to true if there was an error.
9890///
9891/// Returns true if there was an error, false otherwise.
9892static bool CheckMultiVersionFunction(Sema &SFunctionDecl *NewFD,
9893                                      bool &RedeclarationNamedDecl *&OldDecl,
9894                                      bool &MergeTypeWithPrevious,
9895                                      LookupResult &Previous) {
9896  const auto *NewTA = NewFD->getAttr<TargetAttr>();
9897  const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
9898  const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
9899
9900  // Mixing Multiversioning types is prohibited.
9901  if ((NewTA && NewCPUDisp) || (NewTA && NewCPUSpec) ||
9902      (NewCPUDisp && NewCPUSpec)) {
9903    S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
9904    NewFD->setInvalidDecl();
9905    return true;
9906  }
9907
9908  MultiVersionKind  MVType = NewFD->getMultiVersionKind();
9909
9910  // Main isn't allowed to become a multiversion function, however it IS
9911  // permitted to have 'main' be marked with the 'target' optimization hint.
9912  if (NewFD->isMain()) {
9913    if ((MVType == MultiVersionKind::Target && NewTA->isDefaultVersion()) ||
9914        MVType == MultiVersionKind::CPUDispatch ||
9915        MVType == MultiVersionKind::CPUSpecific) {
9916      S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
9917      NewFD->setInvalidDecl();
9918      return true;
9919    }
9920    return false;
9921  }
9922
9923  if (!OldDecl || !OldDecl->getAsFunction() ||
9924      OldDecl->getDeclContext()->getRedeclContext() !=
9925          NewFD->getDeclContext()->getRedeclContext()) {
9926    // If there's no previous declaration, AND this isn't attempting to cause
9927    // multiversioning, this isn't an error condition.
9928    if (MVType == MultiVersionKind::None)
9929      return false;
9930    return CheckMultiVersionFirstFunction(S, NewFD, MVType, NewTA, NewCPUDisp,
9931                                          NewCPUSpec);
9932  }
9933
9934  FunctionDecl *OldFD = OldDecl->getAsFunction();
9935
9936  if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::None)
9937    return false;
9938
9939  if (OldFD->isMultiVersion() && MVType == MultiVersionKind::None) {
9940    S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
9941        << (OldFD->getMultiVersionKind() != MultiVersionKind::Target);
9942    NewFD->setInvalidDecl();
9943    return true;
9944  }
9945
9946  // Handle the target potentially causes multiversioning case.
9947  if (!OldFD->isMultiVersion() && MVType == MultiVersionKind::Target)
9948    return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
9949                                            Redeclaration, OldDecl,
9950                                            MergeTypeWithPrevious, Previous);
9951
9952  // At this point, we have a multiversion function decl (in OldFD) AND an
9953  // appropriate attribute in the current function decl.  Resolve that these are
9954  // still compatible with previous declarations.
9955  return CheckMultiVersionAdditionalDecl(
9956      S, OldFD, NewFD, MVType, NewTA, NewCPUDisp, NewCPUSpec, Redeclaration,
9957      OldDecl, MergeTypeWithPrevious, Previous);
9958}
9959
9960/// Perform semantic checking of a new function declaration.
9961///
9962/// Performs semantic analysis of the new function declaration
9963/// NewFD. This routine performs all semantic checking that does not
9964/// require the actual declarator involved in the declaration, and is
9965/// used both for the declaration of functions as they are parsed
9966/// (called via ActOnDeclarator) and for the declaration of functions
9967/// that have been instantiated via C++ template instantiation (called
9968/// via InstantiateDecl).
9969///
9970/// \param IsMemberSpecialization whether this new function declaration is
9971/// a member specialization (that replaces any definition provided by the
9972/// previous declaration).
9973///
9974/// This sets NewFD->isInvalidDecl() to true if there was an error.
9975///
9976/// \returns true if the function declaration is a redeclaration.
9977bool Sema::CheckFunctionDeclaration(Scope *SFunctionDecl *NewFD,
9978                                    LookupResult &Previous,
9979                                    bool IsMemberSpecialization) {
9980   (0) . __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 9981, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
9981 (0) . __assert_fail ("!NewFD->getReturnType()->isVariablyModifiedType() && \"Variably modified return types are not handled here\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 9981, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "Variably modified return types are not handled here");
9982
9983  // Determine whether the type of this function should be merged with
9984  // a previous visible declaration. This never happens for functions in C++,
9985  // and always happens in C if the previous declaration was visible.
9986  bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
9987                               !Previous.isShadowed();
9988
9989  bool Redeclaration = false;
9990  NamedDecl *OldDecl = nullptr;
9991  bool MayNeedOverloadableChecks = false;
9992
9993  // Merge or overload the declaration with an existing declaration of
9994  // the same name, if appropriate.
9995  if (!Previous.empty()) {
9996    // Determine whether NewFD is an overload of PrevDecl or
9997    // a declaration that requires merging. If it's an overload,
9998    // there's no more work to do here; we'll just add the new
9999    // function to the scope.
10000    if (!AllowOverloadingOfFunction(PreviousContextNewFD)) {
10001      NamedDecl *Candidate = Previous.getRepresentativeDecl();
10002      if (shouldLinkPossiblyHiddenDecl(CandidateNewFD)) {
10003        Redeclaration = true;
10004        OldDecl = Candidate;
10005      }
10006    } else {
10007      MayNeedOverloadableChecks = true;
10008      switch (CheckOverload(SNewFDPreviousOldDecl,
10009                            /*NewIsUsingDecl*/ false)) {
10010      case Ovl_Match:
10011        Redeclaration = true;
10012        break;
10013
10014      case Ovl_NonFunction:
10015        Redeclaration = true;
10016        break;
10017
10018      case Ovl_Overload:
10019        Redeclaration = false;
10020        break;
10021      }
10022    }
10023  }
10024
10025  // Check for a previous extern "C" declaration with this name.
10026  if (!Redeclaration &&
10027      checkForConflictWithNonVisibleExternC(*thisNewFDPrevious)) {
10028    if (!Previous.empty()) {
10029      // This is an extern "C" declaration with the same name as a previous
10030      // declaration, and thus redeclares that entity...
10031      Redeclaration = true;
10032      OldDecl = Previous.getFoundDecl();
10033      MergeTypeWithPrevious = false;
10034
10035      // ... except in the presence of __attribute__((overloadable)).
10036      if (OldDecl->hasAttr<OverloadableAttr>() ||
10037          NewFD->hasAttr<OverloadableAttr>()) {
10038        if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
10039          MayNeedOverloadableChecks = true;
10040          Redeclaration = false;
10041          OldDecl = nullptr;
10042        }
10043      }
10044    }
10045  }
10046
10047  if (CheckMultiVersionFunction(*thisNewFDRedeclarationOldDecl,
10048                                MergeTypeWithPreviousPrevious))
10049    return Redeclaration;
10050
10051  // C++11 [dcl.constexpr]p8:
10052  //   A constexpr specifier for a non-static member function that is not
10053  //   a constructor declares that member function to be const.
10054  //
10055  // This needs to be delayed until we know whether this is an out-of-line
10056  // definition of a static member function.
10057  //
10058  // This rule is not present in C++1y, so we produce a backwards
10059  // compatibility warning whenever it happens in C++11.
10060  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
10061  if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
10062      !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
10063      !MD->getMethodQualifiers().hasConst()) {
10064    CXXMethodDecl *OldMD = nullptr;
10065    if (OldDecl)
10066      OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
10067    if (!OldMD || !OldMD->isStatic()) {
10068      const FunctionProtoType *FPT =
10069        MD->getType()->castAs<FunctionProtoType>();
10070      FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10071      EPI.TypeQuals.addConst();
10072      MD->setType(Context.getFunctionType(FPT->getReturnType(),
10073                                          FPT->getParamTypes(), EPI));
10074
10075      // Warn that we did this, if we're not performing template instantiation.
10076      // In that case, we'll have warned already when the template was defined.
10077      if (!inTemplateInstantiation()) {
10078        SourceLocation AddConstLoc;
10079        if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
10080                .IgnoreParens().getAs<FunctionTypeLoc>())
10081          AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
10082
10083        Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
10084          << FixItHint::CreateInsertion(AddConstLoc, " const");
10085      }
10086    }
10087  }
10088
10089  if (Redeclaration) {
10090    // NewFD and OldDecl represent declarations that need to be
10091    // merged.
10092    if (MergeFunctionDecl(NewFDOldDeclSMergeTypeWithPrevious)) {
10093      NewFD->setInvalidDecl();
10094      return Redeclaration;
10095    }
10096
10097    Previous.clear();
10098    Previous.addDecl(OldDecl);
10099
10100    if (FunctionTemplateDecl *OldTemplateDecl =
10101            dyn_cast<FunctionTemplateDecl>(OldDecl)) {
10102      auto *OldFD = OldTemplateDecl->getTemplatedDecl();
10103      FunctionTemplateDecl *NewTemplateDecl
10104        = NewFD->getDescribedFunctionTemplate();
10105       (0) . __assert_fail ("NewTemplateDecl && \"Template/non-template mismatch\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 10105, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(NewTemplateDecl && "Template/non-template mismatch");
10106
10107      // The call to MergeFunctionDecl above may have created some state in
10108      // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
10109      // can add it as a redeclaration.
10110      NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
10111
10112      NewFD->setPreviousDeclaration(OldFD);
10113      adjustDeclContextForDeclaratorDecl(NewFDOldFD);
10114      if (NewFD->isCXXClassMember()) {
10115        NewFD->setAccess(OldTemplateDecl->getAccess());
10116        NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
10117      }
10118
10119      // If this is an explicit specialization of a member that is a function
10120      // template, mark it as a member specialization.
10121      if (IsMemberSpecialization &&
10122          NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
10123        NewTemplateDecl->setMemberSpecialization();
10124        isMemberSpecialization()", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 10124, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(OldTemplateDecl->isMemberSpecialization());
10125        // Explicit specializations of a member template do not inherit deleted
10126        // status from the parent member template that they are specializing.
10127        if (OldFD->isDeleted()) {
10128          // FIXME: This assert will not hold in the presence of modules.
10129          getCanonicalDecl() == OldFD", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 10129, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(OldFD->getCanonicalDecl() == OldFD);
10130          // FIXME: We need an update record for this AST mutation.
10131          OldFD->setDeletedAsWritten(false);
10132        }
10133      }
10134
10135    } else {
10136      if (shouldLinkDependentDeclWithPrevious(NewFDOldDecl)) {
10137        auto *OldFD = cast<FunctionDecl>(OldDecl);
10138        // This needs to happen first so that 'inline' propagates.
10139        NewFD->setPreviousDeclaration(OldFD);
10140        adjustDeclContextForDeclaratorDecl(NewFD, OldFD);
10141        if (NewFD->isCXXClassMember())
10142          NewFD->setAccess(OldFD->getAccess());
10143      }
10144    }
10145  } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
10146             !NewFD->getAttr<OverloadableAttr>()) {
10147     (0) . __assert_fail ("(Previous.empty() || llvm..any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr(); })) && \"Non-redecls shouldn't happen without overloadable present\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 10152, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert((Previous.empty() ||
10148 (0) . __assert_fail ("(Previous.empty() || llvm..any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr(); })) && \"Non-redecls shouldn't happen without overloadable present\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 10152, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">            llvm::any_of(Previous,
10149 (0) . __assert_fail ("(Previous.empty() || llvm..any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr(); })) && \"Non-redecls shouldn't happen without overloadable present\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 10152, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">                         [](const NamedDecl *ND) {
10150 (0) . __assert_fail ("(Previous.empty() || llvm..any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr(); })) && \"Non-redecls shouldn't happen without overloadable present\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 10152, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">                           return ND->hasAttr<OverloadableAttr>();
10151 (0) . __assert_fail ("(Previous.empty() || llvm..any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr(); })) && \"Non-redecls shouldn't happen without overloadable present\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 10152, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">                         })) &&
10152 (0) . __assert_fail ("(Previous.empty() || llvm..any_of(Previous, [](const NamedDecl *ND) { return ND->hasAttr(); })) && \"Non-redecls shouldn't happen without overloadable present\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 10152, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           "Non-redecls shouldn't happen without overloadable present");
10153
10154    auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
10155      const auto *FD = dyn_cast<FunctionDecl>(ND);
10156      return FD && !FD->hasAttr<OverloadableAttr>();
10157    });
10158
10159    if (OtherUnmarkedIter != Previous.end()) {
10160      Diag(NewFD->getLocation(),
10161           diag::err_attribute_overloadable_multiple_unmarked_overloads);
10162      Diag((*OtherUnmarkedIter)->getLocation(),
10163           diag::note_attribute_overloadable_prev_overload)
10164          << false;
10165
10166      NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
10167    }
10168  }
10169
10170  // Semantic checking for this function declaration (in isolation).
10171
10172  if (getLangOpts().CPlusPlus) {
10173    // C++-specific checks.
10174    if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
10175      CheckConstructor(Constructor);
10176    } else if (CXXDestructorDecl *Destructor =
10177                dyn_cast<CXXDestructorDecl>(NewFD)) {
10178      CXXRecordDecl *Record = Destructor->getParent();
10179      QualType ClassType = Context.getTypeDeclType(Record);
10180
10181      // FIXME: Shouldn't we be able to perform this check even when the class
10182      // type is dependent? Both gcc and edg can handle that.
10183      if (!ClassType->isDependentType()) {
10184        DeclarationName Name
10185          = Context.DeclarationNames.getCXXDestructorName(
10186                                        Context.getCanonicalType(ClassType));
10187        if (NewFD->getDeclName() != Name) {
10188          Diag(NewFD->getLocation(), diag::err_destructor_name);
10189          NewFD->setInvalidDecl();
10190          return Redeclaration;
10191        }
10192      }
10193    } else if (CXXConversionDecl *Conversion
10194               = dyn_cast<CXXConversionDecl>(NewFD)) {
10195      ActOnConversionDeclarator(Conversion);
10196    } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
10197      if (auto *TD = Guide->getDescribedFunctionTemplate())
10198        CheckDeductionGuideTemplate(TD);
10199
10200      // A deduction guide is not on the list of entities that can be
10201      // explicitly specialized.
10202      if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
10203        Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
10204            << /*explicit specialization*/ 1;
10205    }
10206
10207    // Find any virtual functions that this function overrides.
10208    if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
10209      if (!Method->isFunctionTemplateSpecialization() &&
10210          !Method->getDescribedFunctionTemplate() &&
10211          Method->isCanonicalDecl()) {
10212        if (AddOverriddenMethods(Method->getParent(), Method)) {
10213          // If the function was marked as "static", we have a problem.
10214          if (NewFD->getStorageClass() == SC_Static) {
10215            ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
10216          }
10217        }
10218      }
10219
10220      if (Method->isStatic())
10221        checkThisInStaticMemberFunctionType(Method);
10222    }
10223
10224    // Extra checking for C++ overloaded operators (C++ [over.oper]).
10225    if (NewFD->isOverloadedOperator() &&
10226        CheckOverloadedOperatorDeclaration(NewFD)) {
10227      NewFD->setInvalidDecl();
10228      return Redeclaration;
10229    }
10230
10231    // Extra checking for C++0x literal operators (C++0x [over.literal]).
10232    if (NewFD->getLiteralIdentifier() &&
10233        CheckLiteralOperatorDeclaration(NewFD)) {
10234      NewFD->setInvalidDecl();
10235      return Redeclaration;
10236    }
10237
10238    // In C++, check default arguments now that we have merged decls. Unless
10239    // the lexical context is the class, because in this case this is done
10240    // during delayed parsing anyway.
10241    if (!CurContext->isRecord())
10242      CheckCXXDefaultArguments(NewFD);
10243
10244    // If this function declares a builtin function, check the type of this
10245    // declaration against the expected type for the builtin.
10246    if (unsigned BuiltinID = NewFD->getBuiltinID()) {
10247      ASTContext::GetBuiltinTypeError Error;
10248      LookupPredefedObjCSuperType(*thisSNewFD->getIdentifier());
10249      QualType T = Context.GetBuiltinType(BuiltinIDError);
10250      // If the type of the builtin differs only in its exception
10251      // specification, that's OK.
10252      // FIXME: If the types do differ in this way, it would be better to
10253      // retain the 'noexcept' form of the type.
10254      if (!T.isNull() &&
10255          !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
10256                                                            NewFD->getType()))
10257        // The type of this function differs from the type of the builtin,
10258        // so forget about the builtin entirely.
10259        Context.BuiltinInfo.forgetBuiltin(BuiltinIDContext.Idents);
10260    }
10261
10262    // If this function is declared as being extern "C", then check to see if
10263    // the function returns a UDT (class, struct, or union type) that is not C
10264    // compatible, and if it does, warn the user.
10265    // But, issue any diagnostic on the first declaration only.
10266    if (Previous.empty() && NewFD->isExternC()) {
10267      QualType R = NewFD->getReturnType();
10268      if (R->isIncompleteType() && !R->isVoidType())
10269        Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
10270            << NewFD << R;
10271      else if (!R.isPODType(Context) && !R->isVoidType() &&
10272               !R->isObjCObjectPointerType())
10273        Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
10274    }
10275
10276    // C++1z [dcl.fct]p6:
10277    //   [...] whether the function has a non-throwing exception-specification
10278    //   [is] part of the function type
10279    //
10280    // This results in an ABI break between C++14 and C++17 for functions whose
10281    // declared type includes an exception-specification in a parameter or
10282    // return type. (Exception specifications on the function itself are OK in
10283    // most cases, and exception specifications are not permitted in most other
10284    // contexts where they could make it into a mangling.)
10285    if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
10286      auto HasNoexcept = [&](QualType T) -> bool {
10287        // Strip off declarator chunks that could be between us and a function
10288        // type. We don't need to look far, exception specifications are very
10289        // restricted prior to C++17.
10290        if (auto *RT = T->getAs<ReferenceType>())
10291          T = RT->getPointeeType();
10292        else if (T->isAnyPointerType())
10293          T = T->getPointeeType();
10294        else if (auto *MPT = T->getAs<MemberPointerType>())
10295          T = MPT->getPointeeType();
10296        if (auto *FPT = T->getAs<FunctionProtoType>())
10297          if (FPT->isNothrow())
10298            return true;
10299        return false;
10300      };
10301
10302      auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
10303      bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
10304      for (QualType T : FPT->param_types())
10305        AnyNoexcept |= HasNoexcept(T);
10306      if (AnyNoexcept)
10307        Diag(NewFD->getLocation(),
10308             diag::warn_cxx17_compat_exception_spec_in_signature)
10309            << NewFD;
10310    }
10311
10312    if (!Redeclaration && LangOpts.CUDA)
10313      checkCUDATargetOverload(NewFDPrevious);
10314  }
10315  return Redeclaration;
10316}
10317
10318void Sema::CheckMain(FunctionDeclFDconst DeclSpecDS) {
10319  // C++11 [basic.start.main]p3:
10320  //   A program that [...] declares main to be inline, static or
10321  //   constexpr is ill-formed.
10322  // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
10323  //   appear in a declaration of main.
10324  // static main is not an error under C99, but we should warn about it.
10325  // We accept _Noreturn main as an extension.
10326  if (FD->getStorageClass() == SC_Static)
10327    Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
10328         ? diag::err_static_main : diag::warn_static_main)
10329      << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
10330  if (FD->isInlineSpecified())
10331    Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
10332      << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
10333  if (DS.isNoreturnSpecified()) {
10334    SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
10335    SourceRange NoreturnRange(NoreturnLocgetLocForEndOfToken(NoreturnLoc));
10336    Diag(NoreturnLoc, diag::ext_noreturn_main);
10337    Diag(NoreturnLoc, diag::note_main_remove_noreturn)
10338      << FixItHint::CreateRemoval(NoreturnRange);
10339  }
10340  if (FD->isConstexpr()) {
10341    Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
10342      << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
10343    FD->setConstexpr(false);
10344  }
10345
10346  if (getLangOpts().OpenCL) {
10347    Diag(FD->getLocation(), diag::err_opencl_no_main)
10348        << FD->hasAttr<OpenCLKernelAttr>();
10349    FD->setInvalidDecl();
10350    return;
10351  }
10352
10353  QualType T = FD->getType();
10354   (0) . __assert_fail ("T->isFunctionType() && \"function decl is not of function type\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 10354, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(T->isFunctionType() && "function decl is not of function type");
10355  const FunctionTypeFT = T->castAs<FunctionType>();
10356
10357  // Set default calling convention for main()
10358  if (FT->getCallConv() != CC_C) {
10359    FT = Context.adjustFunctionType(FTFT->getExtInfo().withCallingConv(CC_C));
10360    FD->setType(QualType(FT0));
10361    T = Context.getCanonicalType(FD->getType());
10362  }
10363
10364  if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
10365    // In C with GNU extensions we allow main() to have non-integer return
10366    // type, but we should warn about the extension, and we disable the
10367    // implicit-return-zero rule.
10368
10369    // GCC in C mode accepts qualified 'int'.
10370    if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
10371      FD->setHasImplicitReturnZero(true);
10372    else {
10373      Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
10374      SourceRange RTRange = FD->getReturnTypeSourceRange();
10375      if (RTRange.isValid())
10376        Diag(RTRange.getBegin(), diag::note_main_change_return_type)
10377            << FixItHint::CreateReplacement(RTRange, "int");
10378    }
10379  } else {
10380    // In C and C++, main magically returns 0 if you fall off the end;
10381    // set the flag which tells us that.
10382    // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
10383
10384    // All the standards say that main() should return 'int'.
10385    if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
10386      FD->setHasImplicitReturnZero(true);
10387    else {
10388      // Otherwise, this is just a flat-out error.
10389      SourceRange RTRange = FD->getReturnTypeSourceRange();
10390      Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
10391          << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
10392                                : FixItHint());
10393      FD->setInvalidDecl(true);
10394    }
10395  }
10396
10397  // Treat protoless main() as nullary.
10398  if (isa<FunctionNoProtoType>(FT)) return;
10399
10400  const FunctionProtoTypeFTP = cast<const FunctionProtoType>(FT);
10401  unsigned nparams = FTP->getNumParams();
10402  getNumParams() == nparams", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 10402, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(FD->getNumParams() == nparams);
10403
10404  bool HasExtraParameters = (nparams > 3);
10405
10406  if (FTP->isVariadic()) {
10407    Diag(FD->getLocation(), diag::ext_variadic_main);
10408    // FIXME: if we had information about the location of the ellipsis, we
10409    // could add a FixIt hint to remove it as a parameter.
10410  }
10411
10412  // Darwin passes an undocumented fourth argument of type char**.  If
10413  // other platforms start sprouting these, the logic below will start
10414  // getting shifty.
10415  if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
10416    HasExtraParameters = false;
10417
10418  if (HasExtraParameters) {
10419    Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
10420    FD->setInvalidDecl(true);
10421    nparams = 3;
10422  }
10423
10424  // FIXME: a lot of the following diagnostics would be improved
10425  // if we had some location information about types.
10426
10427  QualType CharPP =
10428    Context.getPointerType(Context.getPointerType(Context.CharTy));
10429  QualType Expected[] = { Context.IntTyCharPPCharPPCharPP };
10430
10431  for (unsigned i = 0i < nparams; ++i) {
10432    QualType AT = FTP->getParamType(i);
10433
10434    bool mismatch = true;
10435
10436    if (Context.hasSameUnqualifiedType(ATExpected[i]))
10437      mismatch = false;
10438    else if (Expected[i] == CharPP) {
10439      // As an extension, the following forms are okay:
10440      //   char const **
10441      //   char const * const *
10442      //   char * const *
10443
10444      QualifierCollector qs;
10445      const PointerTypePT;
10446      if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
10447          (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
10448          Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
10449                              Context.CharTy)) {
10450        qs.removeConst();
10451        mismatch = !qs.empty();
10452      }
10453    }
10454
10455    if (mismatch) {
10456      Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
10457      // TODO: suggest replacing given type with expected type
10458      FD->setInvalidDecl(true);
10459    }
10460  }
10461
10462  if (nparams == 1 && !FD->isInvalidDecl()) {
10463    Diag(FD->getLocation(), diag::warn_main_one_arg);
10464  }
10465
10466  if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10467    Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10468    FD->setInvalidDecl();
10469  }
10470}
10471
10472void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
10473  QualType T = FD->getType();
10474   (0) . __assert_fail ("T->isFunctionType() && \"function decl is not of function type\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 10474, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(T->isFunctionType() && "function decl is not of function type");
10475  const FunctionType *FT = T->castAs<FunctionType>();
10476
10477  // Set an implicit return of 'zero' if the function can return some integral,
10478  // enumeration, pointer or nullptr type.
10479  if (FT->getReturnType()->isIntegralOrEnumerationType() ||
10480      FT->getReturnType()->isAnyPointerType() ||
10481      FT->getReturnType()->isNullPtrType())
10482    // DllMain is exempt because a return value of zero means it failed.
10483    if (FD->getName() != "DllMain")
10484      FD->setHasImplicitReturnZero(true);
10485
10486  if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
10487    Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
10488    FD->setInvalidDecl();
10489  }
10490}
10491
10492bool Sema::CheckForConstantInitializer(Expr *InitQualType DclT) {
10493  // FIXME: Need strict checking.  In C89, we need to check for
10494  // any assignment, increment, decrement, function-calls, or
10495  // commas outside of a sizeof.  In C99, it's the same list,
10496  // except that the aforementioned are allowed in unevaluated
10497  // expressions.  Everything else falls under the
10498  // "may accept other forms of constant expressions" exception.
10499  // (We never end up here for C++, so the constant expression
10500  // rules there don't matter.)
10501  const Expr *Culprit;
10502  if (Init->isConstantInitializer(Contextfalse, &Culprit))
10503    return false;
10504  Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
10505    << Culprit->getSourceRange();
10506  return true;
10507}
10508
10509namespace {
10510  // Visits an initialization expression to see if OrigDecl is evaluated in
10511  // its own initialization and throws a warning if it does.
10512  class SelfReferenceChecker
10513      : public EvaluatedExprVisitor<SelfReferenceChecker> {
10514    Sema &S;
10515    Decl *OrigDecl;
10516    bool isRecordType;
10517    bool isPODType;
10518    bool isReferenceType;
10519
10520    bool isInitList;
10521    llvm::SmallVector<unsigned4InitFieldIndex;
10522
10523  public:
10524    typedef EvaluatedExprVisitor<SelfReferenceCheckerInherited;
10525
10526    SelfReferenceChecker(Sema &SDecl *OrigDecl) : Inherited(S.Context),
10527                                                    S(S), OrigDecl(OrigDecl) {
10528      isPODType = false;
10529      isRecordType = false;
10530      isReferenceType = false;
10531      isInitList = false;
10532      if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
10533        isPODType = VD->getType().isPODType(S.Context);
10534        isRecordType = VD->getType()->isRecordType();
10535        isReferenceType = VD->getType()->isReferenceType();
10536      }
10537    }
10538
10539    // For most expressions, just call the visitor.  For initializer lists,
10540    // track the index of the field being initialized since fields are
10541    // initialized in order allowing use of previously initialized fields.
10542    void CheckExpr(Expr *E) {
10543      InitListExpr *InitList = dyn_cast<InitListExpr>(E);
10544      if (!InitList) {
10545        Visit(E);
10546        return;
10547      }
10548
10549      // Track and increment the index here.
10550      isInitList = true;
10551      InitFieldIndex.push_back(0);
10552      for (auto Child : InitList->children()) {
10553        CheckExpr(cast<Expr>(Child));
10554        ++InitFieldIndex.back();
10555      }
10556      InitFieldIndex.pop_back();
10557    }
10558
10559    // Returns true if MemberExpr is checked and no further checking is needed.
10560    // Returns false if additional checking is required.
10561    bool CheckInitListMemberExpr(MemberExpr *Ebool CheckReference) {
10562      llvm::SmallVector<FieldDecl*, 4Fields;
10563      Expr *Base = E;
10564      bool ReferenceField = false;
10565
10566      // Get the field members used.
10567      while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10568        FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
10569        if (!FD)
10570          return false;
10571        Fields.push_back(FD);
10572        if (FD->getType()->isReferenceType())
10573          ReferenceField = true;
10574        Base = ME->getBase()->IgnoreParenImpCasts();
10575      }
10576
10577      // Keep checking only if the base Decl is the same.
10578      DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
10579      if (!DRE || DRE->getDecl() != OrigDecl)
10580        return false;
10581
10582      // A reference field can be bound to an unininitialized field.
10583      if (CheckReference && !ReferenceField)
10584        return true;
10585
10586      // Convert FieldDecls to their index number.
10587      llvm::SmallVector<unsigned4UsedFieldIndex;
10588      for (const FieldDecl *I : llvm::reverse(Fields))
10589        UsedFieldIndex.push_back(I->getFieldIndex());
10590
10591      // See if a warning is needed by checking the first difference in index
10592      // numbers.  If field being used has index less than the field being
10593      // initialized, then the use is safe.
10594      for (auto UsedIter = UsedFieldIndex.begin(),
10595                UsedEnd = UsedFieldIndex.end(),
10596                OrigIter = InitFieldIndex.begin(),
10597                OrigEnd = InitFieldIndex.end();
10598           UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
10599        if (*UsedIter < *OrigIter)
10600          return true;
10601        if (*UsedIter > *OrigIter)
10602          break;
10603      }
10604
10605      // TODO: Add a different warning which will print the field names.
10606      HandleDeclRefExpr(DRE);
10607      return true;
10608    }
10609
10610    // For most expressions, the cast is directly above the DeclRefExpr.
10611    // For conditional operators, the cast can be outside the conditional
10612    // operator if both expressions are DeclRefExpr's.
10613    void HandleValue(Expr *E) {
10614      E = E->IgnoreParens();
10615      if (DeclRefExprDRE = dyn_cast<DeclRefExpr>(E)) {
10616        HandleDeclRefExpr(DRE);
10617        return;
10618      }
10619
10620      if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
10621        Visit(CO->getCond());
10622        HandleValue(CO->getTrueExpr());
10623        HandleValue(CO->getFalseExpr());
10624        return;
10625      }
10626
10627      if (BinaryConditionalOperator *BCO =
10628              dyn_cast<BinaryConditionalOperator>(E)) {
10629        Visit(BCO->getCond());
10630        HandleValue(BCO->getFalseExpr());
10631        return;
10632      }
10633
10634      if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
10635        HandleValue(OVE->getSourceExpr());
10636        return;
10637      }
10638
10639      if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
10640        if (BO->getOpcode() == BO_Comma) {
10641          Visit(BO->getLHS());
10642          HandleValue(BO->getRHS());
10643          return;
10644        }
10645      }
10646
10647      if (isa<MemberExpr>(E)) {
10648        if (isInitList) {
10649          if (CheckInitListMemberExpr(cast<MemberExpr>(E),
10650                                      false /*CheckReference*/))
10651            return;
10652        }
10653
10654        Expr *Base = E->IgnoreParenImpCasts();
10655        while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10656          // Check for static member variables and don't warn on them.
10657          if (!isa<FieldDecl>(ME->getMemberDecl()))
10658            return;
10659          Base = ME->getBase()->IgnoreParenImpCasts();
10660        }
10661        if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
10662          HandleDeclRefExpr(DRE);
10663        return;
10664      }
10665
10666      Visit(E);
10667    }
10668
10669    // Reference types not handled in HandleValue are handled here since all
10670    // uses of references are bad, not just r-value uses.
10671    void VisitDeclRefExpr(DeclRefExpr *E) {
10672      if (isReferenceType)
10673        HandleDeclRefExpr(E);
10674    }
10675
10676    void VisitImplicitCastExpr(ImplicitCastExpr *E) {
10677      if (E->getCastKind() == CK_LValueToRValue) {
10678        HandleValue(E->getSubExpr());
10679        return;
10680      }
10681
10682      Inherited::VisitImplicitCastExpr(E);
10683    }
10684
10685    void VisitMemberExpr(MemberExpr *E) {
10686      if (isInitList) {
10687        if (CheckInitListMemberExpr(Etrue /*CheckReference*/))
10688          return;
10689      }
10690
10691      // Don't warn on arrays since they can be treated as pointers.
10692      if (E->getType()->canDecayToPointerType()) return;
10693
10694      // Warn when a non-static method call is followed by non-static member
10695      // field accesses, which is followed by a DeclRefExpr.
10696      CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
10697      bool Warn = (MD && !MD->isStatic());
10698      Expr *Base = E->getBase()->IgnoreParenImpCasts();
10699      while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
10700        if (!isa<FieldDecl>(ME->getMemberDecl()))
10701          Warn = false;
10702        Base = ME->getBase()->IgnoreParenImpCasts();
10703      }
10704
10705      if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
10706        if (Warn)
10707          HandleDeclRefExpr(DRE);
10708        return;
10709      }
10710
10711      // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
10712      // Visit that expression.
10713      Visit(Base);
10714    }
10715
10716    void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
10717      Expr *Callee = E->getCallee();
10718
10719      if (isa<UnresolvedLookupExpr>(Callee))
10720        return Inherited::VisitCXXOperatorCallExpr(E);
10721
10722      Visit(Callee);
10723      for (auto Arg: E->arguments())
10724        HandleValue(Arg->IgnoreParenImpCasts());
10725    }
10726
10727    void VisitUnaryOperator(UnaryOperator *E) {
10728      // For POD record types, addresses of its own members are well-defined.
10729      if (E->getOpcode() == UO_AddrOf && isRecordType &&
10730          isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
10731        if (!isPODType)
10732          HandleValue(E->getSubExpr());
10733        return;
10734      }
10735
10736      if (E->isIncrementDecrementOp()) {
10737        HandleValue(E->getSubExpr());
10738        return;
10739      }
10740
10741      Inherited::VisitUnaryOperator(E);
10742    }
10743
10744    void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
10745
10746    void VisitCXXConstructExpr(CXXConstructExpr *E) {
10747      if (E->getConstructor()->isCopyConstructor()) {
10748        Expr *ArgExpr = E->getArg(0);
10749        if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
10750          if (ILE->getNumInits() == 1)
10751            ArgExpr = ILE->getInit(0);
10752        if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
10753          if (ICE->getCastKind() == CK_NoOp)
10754            ArgExpr = ICE->getSubExpr();
10755        HandleValue(ArgExpr);
10756        return;
10757      }
10758      Inherited::VisitCXXConstructExpr(E);
10759    }
10760
10761    void VisitCallExpr(CallExpr *E) {
10762      // Treat std::move as a use.
10763      if (E->isCallToStdMove()) {
10764        HandleValue(E->getArg(0));
10765        return;
10766      }
10767
10768      Inherited::VisitCallExpr(E);
10769    }
10770
10771    void VisitBinaryOperator(BinaryOperator *E) {
10772      if (E->isCompoundAssignmentOp()) {
10773        HandleValue(E->getLHS());
10774        Visit(E->getRHS());
10775        return;
10776      }
10777
10778      Inherited::VisitBinaryOperator(E);
10779    }
10780
10781    // A custom visitor for BinaryConditionalOperator is needed because the
10782    // regular visitor would check the condition and true expression separately
10783    // but both point to the same place giving duplicate diagnostics.
10784    void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
10785      Visit(E->getCond());
10786      Visit(E->getFalseExpr());
10787    }
10788
10789    void HandleDeclRefExpr(DeclRefExpr *DRE) {
10790      DeclReferenceDecl = DRE->getDecl();
10791      if (OrigDecl != ReferenceDeclreturn;
10792      unsigned diag;
10793      if (isReferenceType) {
10794        diag = diag::warn_uninit_self_reference_in_reference_init;
10795      } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
10796        diag = diag::warn_static_self_reference_in_init;
10797      } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
10798                 isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
10799                 DRE->getDecl()->getType()->isRecordType()) {
10800        diag = diag::warn_uninit_self_reference_in_init;
10801      } else {
10802        // Local variables will be handled by the CFG analysis.
10803        return;
10804      }
10805
10806      S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
10807                            S.PDiag(diag)
10808                                << DRE->getDecl() << OrigDecl->getLocation()
10809                                << DRE->getSourceRange());
10810    }
10811  };
10812
10813  /// CheckSelfReference - Warns if OrigDecl is used in expression E.
10814  static void CheckSelfReference(Sema &SDeclOrigDeclExpr *E,
10815                                 bool DirectInit) {
10816    // Parameters arguments are occassionially constructed with itself,
10817    // for instance, in recursive functions.  Skip them.
10818    if (isa<ParmVarDecl>(OrigDecl))
10819      return;
10820
10821    E = E->IgnoreParens();
10822
10823    // Skip checking T a = a where T is not a record or reference type.
10824    // Doing so is a way to silence uninitialized warnings.
10825    if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
10826      if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
10827        if (ICE->getCastKind() == CK_LValueToRValue)
10828          if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
10829            if (DRE->getDecl() == OrigDecl)
10830              return;
10831
10832    SelfReferenceChecker(SOrigDecl).CheckExpr(E);
10833  }
10834// end anonymous namespace
10835
10836namespace {
10837  // Simple wrapper to add the name of a variable or (if no variable is
10838  // available) a DeclarationName into a diagnostic.
10839  struct VarDeclOrName {
10840    VarDecl *VDecl;
10841    DeclarationName Name;
10842
10843    friend const Sema::SemaDiagnosticBuilder &
10844    operator<<(const Sema::SemaDiagnosticBuilder &DiagVarDeclOrName VN) {
10845      return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
10846    }
10847  };
10848// end anonymous namespace
10849
10850QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
10851                                            DeclarationName NameQualType Type,
10852                                            TypeSourceInfo *TSI,
10853                                            SourceRange Rangebool DirectInit,
10854                                            Expr *&Init) {
10855  bool IsInitCapture = !VDecl;
10856   (0) . __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 10857, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert((!VDecl || !VDecl->isInitCapture()) &&
10857 (0) . __assert_fail ("(!VDecl || !VDecl->isInitCapture()) && \"init captures are expected to be deduced prior to initialization\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 10857, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "init captures are expected to be deduced prior to initialization");
10858
10859  VarDeclOrName VN{VDeclName};
10860
10861  DeducedType *Deduced = Type->getContainedDeducedType();
10862   (0) . __assert_fail ("Deduced && \"deduceVarTypeFromInitializer for non-deduced type\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 10862, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
10863
10864  // C++11 [dcl.spec.auto]p3
10865  if (!Init) {
10866     (0) . __assert_fail ("VDecl && \"no init for init capture deduction?\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 10866, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(VDecl && "no init for init capture deduction?");
10867
10868    // Except for class argument deduction, and then for an initializing
10869    // declaration only, i.e. no static at class scope or extern.
10870    if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
10871        VDecl->hasExternalStorage() ||
10872        VDecl->isStaticDataMember()) {
10873      Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
10874        << VDecl->getDeclName() << Type;
10875      return QualType();
10876    }
10877  }
10878
10879  ArrayRef<Expr*> DeduceInits;
10880  if (Init)
10881    DeduceInits = Init;
10882
10883  if (DirectInit) {
10884    if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
10885      DeduceInits = PL->exprs();
10886  }
10887
10888  if (isa<DeducedTemplateSpecializationType>(Deduced)) {
10889     (0) . __assert_fail ("VDecl && \"non-auto type for init capture deduction?\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 10889, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(VDecl && "non-auto type for init capture deduction?");
10890    InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10891    InitializationKind Kind = InitializationKind::CreateForInit(
10892        VDecl->getLocation(), DirectInitInit);
10893    // FIXME: Initialization should not be taking a mutable list of inits.
10894    SmallVector<Expr*, 8InitsCopy(DeduceInits.begin(), DeduceInits.end());
10895    return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
10896                                                       InitsCopy);
10897  }
10898
10899  if (DirectInit) {
10900    if (auto *IL = dyn_cast<InitListExpr>(Init))
10901      DeduceInits = IL->inits();
10902  }
10903
10904  // Deduction only works if we have exactly one source expression.
10905  if (DeduceInits.empty()) {
10906    // It isn't possible to write this directly, but it is possible to
10907    // end up in this situation with "auto x(some_pack...);"
10908    Diag(Init->getBeginLoc(), IsInitCapture
10909                                  ? diag::err_init_capture_no_expression
10910                                  : diag::err_auto_var_init_no_expression)
10911        << VN << Type << Range;
10912    return QualType();
10913  }
10914
10915  if (DeduceInits.size() > 1) {
10916    Diag(DeduceInits[1]->getBeginLoc(),
10917         IsInitCapture ? diag::err_init_capture_multiple_expressions
10918                       : diag::err_auto_var_init_multiple_expressions)
10919        << VN << Type << Range;
10920    return QualType();
10921  }
10922
10923  Expr *DeduceInit = DeduceInits[0];
10924  if (DirectInit && isa<InitListExpr>(DeduceInit)) {
10925    Diag(Init->getBeginLoc(), IsInitCapture
10926                                  ? diag::err_init_capture_paren_braces
10927                                  : diag::err_auto_var_init_paren_braces)
10928        << isa<InitListExpr>(Init) << VN << Type << Range;
10929    return QualType();
10930  }
10931
10932  // Expressions default to 'id' when we're in a debugger.
10933  bool DefaultedAnyToId = false;
10934  if (getLangOpts().DebuggerCastResultToId &&
10935      Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
10936    ExprResult Result = forceUnknownAnyToType(InitContext.getObjCIdType());
10937    if (Result.isInvalid()) {
10938      return QualType();
10939    }
10940    Init = Result.get();
10941    DefaultedAnyToId = true;
10942  }
10943
10944  // C++ [dcl.decomp]p1:
10945  //   If the assignment-expression [...] has array type A and no ref-qualifier
10946  //   is present, e has type cv A
10947  if (VDecl && isa<DecompositionDecl>(VDecl) &&
10948      Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
10949      DeduceInit->getType()->isConstantArrayType())
10950    return Context.getQualifiedType(DeduceInit->getType(),
10951                                    Type.getQualifiers());
10952
10953  QualType DeducedType;
10954  if (DeduceAutoType(TSIDeduceInitDeducedType) == DAR_Failed) {
10955    if (!IsInitCapture)
10956      DiagnoseAutoDeductionFailure(VDeclDeduceInit);
10957    else if (isa<InitListExpr>(Init))
10958      Diag(Range.getBegin(),
10959           diag::err_init_capture_deduction_failure_from_init_list)
10960          << VN
10961          << (DeduceInit->getType().isNull() ? TSI->getType()
10962                                             : DeduceInit->getType())
10963          << DeduceInit->getSourceRange();
10964    else
10965      Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
10966          << VN << TSI->getType()
10967          << (DeduceInit->getType().isNull() ? TSI->getType()
10968                                             : DeduceInit->getType())
10969          << DeduceInit->getSourceRange();
10970  } else
10971    Init = DeduceInit;
10972
10973  // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
10974  // 'id' instead of a specific object type prevents most of our usual
10975  // checks.
10976  // We only want to warn outside of template instantiations, though:
10977  // inside a template, the 'id' could have come from a parameter.
10978  if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
10979      !DeducedType.isNull() && DeducedType->isObjCIdType()) {
10980    SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
10981    Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
10982  }
10983
10984  return DeducedType;
10985}
10986
10987bool Sema::DeduceVariableDeclarationType(VarDecl *VDeclbool DirectInit,
10988                                         Expr *&Init) {
10989  QualType DeducedType = deduceVarTypeFromInitializer(
10990      VDeclVDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
10991      VDecl->getSourceRange(), DirectInitInit);
10992  if (DeducedType.isNull()) {
10993    VDecl->setInvalidDecl();
10994    return true;
10995  }
10996
10997  VDecl->setType(DeducedType);
10998  isLinkageValid()", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 10998, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(VDecl->isLinkageValid());
10999
11000  // In ARC, infer lifetime.
11001  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
11002    VDecl->setInvalidDecl();
11003
11004  // If this is a redeclaration, check that the type we just deduced matches
11005  // the previously declared type.
11006  if (VarDecl *Old = VDecl->getPreviousDecl()) {
11007    // We never need to merge the type, because we cannot form an incomplete
11008    // array of auto, nor deduce such a type.
11009    MergeVarDeclTypes(VDeclOld/*MergeTypeWithPrevious*/ false);
11010  }
11011
11012  // Check the deduced type is valid for a variable declaration.
11013  CheckVariableDeclarationType(VDecl);
11014  return VDecl->isInvalidDecl();
11015}
11016
11017/// AddInitializerToDecl - Adds the initializer Init to the
11018/// declaration dcl. If DirectInit is true, this is C++ direct
11019/// initialization rather than copy initialization.
11020void Sema::AddInitializerToDecl(Decl *RealDeclExpr *Initbool DirectInit) {
11021  // If there is no declaration, there was an error parsing it.  Just ignore
11022  // the initializer.
11023  if (!RealDecl || RealDecl->isInvalidDecl()) {
11024    CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
11025    return;
11026  }
11027
11028  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
11029    // Pure-specifiers are handled in ActOnPureSpecifier.
11030    Diag(Method->getLocation(), diag::err_member_function_initialization)
11031      << Method->getDeclName() << Init->getSourceRange();
11032    Method->setInvalidDecl();
11033    return;
11034  }
11035
11036  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
11037  if (!VDecl) {
11038     (0) . __assert_fail ("!isa(RealDecl) && \"field init shouldn't get here\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 11038, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
11039    Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
11040    RealDecl->setInvalidDecl();
11041    return;
11042  }
11043
11044  // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
11045  if (VDecl->getType()->isUndeducedType()) {
11046    // Attempt typo correction early so that the type of the init expression can
11047    // be deduced based on the chosen correction if the original init contains a
11048    // TypoExpr.
11049    ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
11050    if (!Res.isUsable()) {
11051      RealDecl->setInvalidDecl();
11052      return;
11053    }
11054    Init = Res.get();
11055
11056    if (DeduceVariableDeclarationType(VDeclDirectInitInit))
11057      return;
11058  }
11059
11060  // dllimport cannot be used on variable definitions.
11061  if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
11062    Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
11063    VDecl->setInvalidDecl();
11064    return;
11065  }
11066
11067  if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
11068    // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
11069    Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
11070    VDecl->setInvalidDecl();
11071    return;
11072  }
11073
11074  if (!VDecl->getType()->isDependentType()) {
11075    // A definition must end up with a complete type, which means it must be
11076    // complete with the restriction that an array type might be completed by
11077    // the initializer; note that later code assumes this restriction.
11078    QualType BaseDeclType = VDecl->getType();
11079    if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
11080      BaseDeclType = Array->getElementType();
11081    if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
11082                            diag::err_typecheck_decl_incomplete_type)) {
11083      RealDecl->setInvalidDecl();
11084      return;
11085    }
11086
11087    // The variable can not have an abstract class type.
11088    if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
11089                               diag::err_abstract_type_in_decl,
11090                               AbstractVariableType))
11091      VDecl->setInvalidDecl();
11092  }
11093
11094  // If adding the initializer will turn this declaration into a definition,
11095  // and we already have a definition for this variable, diagnose or otherwise
11096  // handle the situation.
11097  VarDecl *Def;
11098  if ((Def = VDecl->getDefinition()) && Def != VDecl &&
11099      (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
11100      !VDecl->isThisDeclarationADemotedDefinition() &&
11101      checkVarDeclRedefinition(DefVDecl))
11102    return;
11103
11104  if (getLangOpts().CPlusPlus) {
11105    // C++ [class.static.data]p4
11106    //   If a static data member is of const integral or const
11107    //   enumeration type, its declaration in the class definition can
11108    //   specify a constant-initializer which shall be an integral
11109    //   constant expression (5.19). In that case, the member can appear
11110    //   in integral constant expressions. The member shall still be
11111    //   defined in a namespace scope if it is used in the program and the
11112    //   namespace scope definition shall not contain an initializer.
11113    //
11114    // We already performed a redefinition check above, but for static
11115    // data members we also need to check whether there was an in-class
11116    // declaration with an initializer.
11117    if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
11118      Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
11119          << VDecl->getDeclName();
11120      Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
11121           diag::note_previous_initializer)
11122          << 0;
11123      return;
11124    }
11125
11126    if (VDecl->hasLocalStorage())
11127      setFunctionHasBranchProtectedScope();
11128
11129    if (DiagnoseUnexpandedParameterPack(InitUPPC_Initializer)) {
11130      VDecl->setInvalidDecl();
11131      return;
11132    }
11133  }
11134
11135  // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
11136  // a kernel function cannot be initialized."
11137  if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
11138    Diag(VDecl->getLocation(), diag::err_local_cant_init);
11139    VDecl->setInvalidDecl();
11140    return;
11141  }
11142
11143  // Get the decls type and save a reference for later, since
11144  // CheckInitializerTypes may change it.
11145  QualType DclT = VDecl->getType(), SavT = DclT;
11146
11147  // Expressions default to 'id' when we're in a debugger
11148  // and we are assigning it to a variable of Objective-C pointer type.
11149  if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
11150      Init->getType() == Context.UnknownAnyTy) {
11151    ExprResult Result = forceUnknownAnyToType(InitContext.getObjCIdType());
11152    if (Result.isInvalid()) {
11153      VDecl->setInvalidDecl();
11154      return;
11155    }
11156    Init = Result.get();
11157  }
11158
11159  // Perform the initialization.
11160  ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
11161  if (!VDecl->isInvalidDecl()) {
11162    InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
11163    InitializationKind Kind = InitializationKind::CreateForInit(
11164        VDecl->getLocation(), DirectInitInit);
11165
11166    MultiExprArg Args = Init;
11167    if (CXXDirectInit)
11168      Args = MultiExprArg(CXXDirectInit->getExprs(),
11169                          CXXDirectInit->getNumExprs());
11170
11171    // Try to correct any TypoExprs in the initialization arguments.
11172    for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
11173      ExprResult Res = CorrectDelayedTyposInExpr(
11174          Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
11175            InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
11176            return Init.Failed() ? ExprError() : E;
11177          });
11178      if (Res.isInvalid()) {
11179        VDecl->setInvalidDecl();
11180      } else if (Res.get() != Args[Idx]) {
11181        Args[Idx] = Res.get();
11182      }
11183    }
11184    if (VDecl->isInvalidDecl())
11185      return;
11186
11187    InitializationSequence InitSeq(*this, Entity, Kind, Args,
11188                                   /*TopLevelOfInitList=*/false,
11189                                   /*TreatUnavailableAsInvalid=*/false);
11190    ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
11191    if (Result.isInvalid()) {
11192      VDecl->setInvalidDecl();
11193      return;
11194    }
11195
11196    Init = Result.getAs<Expr>();
11197  }
11198
11199  // Check for self-references within variable initializers.
11200  // Variables declared within a function/method body (except for references)
11201  // are handled by a dataflow analysis.
11202  if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
11203      VDecl->getType()->isReferenceType()) {
11204    CheckSelfReference(*thisRealDeclInitDirectInit);
11205  }
11206
11207  // If the type changed, it means we had an incomplete type that was
11208  // completed by the initializer. For example:
11209  //   int ary[] = { 1, 3, 5 };
11210  // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
11211  if (!VDecl->isInvalidDecl() && (DclT != SavT))
11212    VDecl->setType(DclT);
11213
11214  if (!VDecl->isInvalidDecl()) {
11215    checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
11216
11217    if (VDecl->hasAttr<BlocksAttr>())
11218      checkRetainCycles(VDeclInit);
11219
11220    // It is safe to assign a weak reference into a strong variable.
11221    // Although this code can still have problems:
11222    //   id x = self.weakProp;
11223    //   id y = self.weakProp;
11224    // we do not warn to warn spuriously when 'x' and 'y' are on separate
11225    // paths through the function. This should be revisited if
11226    // -Wrepeated-use-of-weak is made flow-sensitive.
11227    if (FunctionScopeInfo *FSI = getCurFunction())
11228      if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
11229           VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
11230          !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
11231                           Init->getBeginLoc()))
11232        FSI->markSafeWeakUse(Init);
11233  }
11234
11235  // The initialization is usually a full-expression.
11236  //
11237  // FIXME: If this is a braced initialization of an aggregate, it is not
11238  // an expression, and each individual field initializer is a separate
11239  // full-expression. For instance, in:
11240  //
11241  //   struct Temp { ~Temp(); };
11242  //   struct S { S(Temp); };
11243  //   struct T { S a, b; } t = { Temp(), Temp() }
11244  //
11245  // we should destroy the first Temp before constructing the second.
11246  ExprResult Result =
11247      ActOnFinishFullExpr(InitVDecl->getLocation(),
11248                          /*DiscardedValue*/ falseVDecl->isConstexpr());
11249  if (Result.isInvalid()) {
11250    VDecl->setInvalidDecl();
11251    return;
11252  }
11253  Init = Result.get();
11254
11255  // Attach the initializer to the decl.
11256  VDecl->setInit(Init);
11257
11258  if (VDecl->isLocalVarDecl()) {
11259    // Don't check the initializer if the declaration is malformed.
11260    if (VDecl->isInvalidDecl()) {
11261      // do nothing
11262
11263    // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
11264    // This is true even in OpenCL C++.
11265    } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
11266      CheckForConstantInitializer(InitDclT);
11267
11268    // Otherwise, C++ does not restrict the initializer.
11269    } else if (getLangOpts().CPlusPlus) {
11270      // do nothing
11271
11272    // C99 6.7.8p4: All the expressions in an initializer for an object that has
11273    // static storage duration shall be constant expressions or string literals.
11274    } else if (VDecl->getStorageClass() == SC_Static) {
11275      CheckForConstantInitializer(InitDclT);
11276
11277    // C89 is stricter than C99 for aggregate initializers.
11278    // C89 6.5.7p3: All the expressions [...] in an initializer list
11279    // for an object that has aggregate or union type shall be
11280    // constant expressions.
11281    } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
11282               isa<InitListExpr>(Init)) {
11283      const Expr *Culprit;
11284      if (!Init->isConstantInitializer(Contextfalse, &Culprit)) {
11285        Diag(Culprit->getExprLoc(),
11286             diag::ext_aggregate_init_not_constant)
11287          << Culprit->getSourceRange();
11288      }
11289    }
11290
11291    if (auto *E = dyn_cast<ExprWithCleanups>(Init))
11292      if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
11293        if (VDecl->hasLocalStorage())
11294          BE->getBlockDecl()->setCanAvoidCopyToHeap();
11295  } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
11296             VDecl->getLexicalDeclContext()->isRecord()) {
11297    // This is an in-class initialization for a static data member, e.g.,
11298    //
11299    // struct S {
11300    //   static const int value = 17;
11301    // };
11302
11303    // C++ [class.mem]p4:
11304    //   A member-declarator can contain a constant-initializer only
11305    //   if it declares a static member (9.4) of const integral or
11306    //   const enumeration type, see 9.4.2.
11307    //
11308    // C++11 [class.static.data]p3:
11309    //   If a non-volatile non-inline const static data member is of integral
11310    //   or enumeration type, its declaration in the class definition can
11311    //   specify a brace-or-equal-initializer in which every initializer-clause
11312    //   that is an assignment-expression is a constant expression. A static
11313    //   data member of literal type can be declared in the class definition
11314    //   with the constexpr specifier; if so, its declaration shall specify a
11315    //   brace-or-equal-initializer in which every initializer-clause that is
11316    //   an assignment-expression is a constant expression.
11317
11318    // Do nothing on dependent types.
11319    if (DclT->isDependentType()) {
11320
11321    // Allow any 'static constexpr' members, whether or not they are of literal
11322    // type. We separately check that every constexpr variable is of literal
11323    // type.
11324    } else if (VDecl->isConstexpr()) {
11325
11326    // Require constness.
11327    } else if (!DclT.isConstQualified()) {
11328      Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
11329        << Init->getSourceRange();
11330      VDecl->setInvalidDecl();
11331
11332    // We allow integer constant expressions in all cases.
11333    } else if (DclT->isIntegralOrEnumerationType()) {
11334      // Check whether the expression is a constant expression.
11335      SourceLocation Loc;
11336      if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
11337        // In C++11, a non-constexpr const static data member with an
11338        // in-class initializer cannot be volatile.
11339        Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
11340      else if (Init->isValueDependent())
11341        ; // Nothing to check.
11342      else if (Init->isIntegerConstantExpr(Context, &Loc))
11343        ; // Ok, it's an ICE!
11344      else if (Init->getType()->isScopedEnumeralType() &&
11345               Init->isCXX11ConstantExpr(Context))
11346        ; // Ok, it is a scoped-enum constant expression.
11347      else if (Init->isEvaluatable(Context)) {
11348        // If we can constant fold the initializer through heroics, accept it,
11349        // but report this as a use of an extension for -pedantic.
11350        Diag(Loc, diag::ext_in_class_initializer_non_constant)
11351          << Init->getSourceRange();
11352      } else {
11353        // Otherwise, this is some crazy unknown case.  Report the issue at the
11354        // location provided by the isIntegerConstantExpr failed check.
11355        Diag(Loc, diag::err_in_class_initializer_non_constant)
11356          << Init->getSourceRange();
11357        VDecl->setInvalidDecl();
11358      }
11359
11360    // We allow foldable floating-point constants as an extension.
11361    } else if (DclT->isFloatingType()) { // also permits complex, which is ok
11362      // In C++98, this is a GNU extension. In C++11, it is not, but we support
11363      // it anyway and provide a fixit to add the 'constexpr'.
11364      if (getLangOpts().CPlusPlus11) {
11365        Diag(VDecl->getLocation(),
11366             diag::ext_in_class_initializer_float_type_cxx11)
11367            << DclT << Init->getSourceRange();
11368        Diag(VDecl->getBeginLoc(),
11369             diag::note_in_class_initializer_float_type_cxx11)
11370            << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11371      } else {
11372        Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
11373          << DclT << Init->getSourceRange();
11374
11375        if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
11376          Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
11377            << Init->getSourceRange();
11378          VDecl->setInvalidDecl();
11379        }
11380      }
11381
11382    // Suggest adding 'constexpr' in C++11 for literal types.
11383    } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
11384      Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
11385          << DclT << Init->getSourceRange()
11386          << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
11387      VDecl->setConstexpr(true);
11388
11389    } else {
11390      Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
11391        << DclT << Init->getSourceRange();
11392      VDecl->setInvalidDecl();
11393    }
11394  } else if (VDecl->isFileVarDecl()) {
11395    // In C, extern is typically used to avoid tentative definitions when
11396    // declaring variables in headers, but adding an intializer makes it a
11397    // definition. This is somewhat confusing, so GCC and Clang both warn on it.
11398    // In C++, extern is often used to give implictly static const variables
11399    // external linkage, so don't warn in that case. If selectany is present,
11400    // this might be header code intended for C and C++ inclusion, so apply the
11401    // C++ rules.
11402    if (VDecl->getStorageClass() == SC_Extern &&
11403        ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
11404         !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
11405        !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
11406        !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
11407      Diag(VDecl->getLocation(), diag::warn_extern_init);
11408
11409    // In Microsoft C++ mode, a const variable defined in namespace scope has
11410    // external linkage by default if the variable is declared with
11411    // __declspec(dllexport).
11412    if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11413        getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
11414        VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
11415      VDecl->setStorageClass(SC_Extern);
11416
11417    // C99 6.7.8p4. All file scoped initializers need to be constant.
11418    if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
11419      CheckForConstantInitializer(InitDclT);
11420  }
11421
11422  // We will represent direct-initialization similarly to copy-initialization:
11423  //    int x(1);  -as-> int x = 1;
11424  //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
11425  //
11426  // Clients that want to distinguish between the two forms, can check for
11427  // direct initializer using VarDecl::getInitStyle().
11428  // A major benefit is that clients that don't particularly care about which
11429  // exactly form was it (like the CodeGen) can handle both cases without
11430  // special case code.
11431
11432  // C++ 8.5p11:
11433  // The form of initialization (using parentheses or '=') is generally
11434  // insignificant, but does matter when the entity being initialized has a
11435  // class type.
11436  if (CXXDirectInit) {
11437     (0) . __assert_fail ("DirectInit && \"Call-style initializer must be direct init.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 11437, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(DirectInit && "Call-style initializer must be direct init.");
11438    VDecl->setInitStyle(VarDecl::CallInit);
11439  } else if (DirectInit) {
11440    // This must be list-initialization. No other way is direct-initialization.
11441    VDecl->setInitStyle(VarDecl::ListInit);
11442  }
11443
11444  CheckCompleteVariableDeclaration(VDecl);
11445}
11446
11447/// ActOnInitializerError - Given that there was an error parsing an
11448/// initializer for the given declaration, try to return to some form
11449/// of sanity.
11450void Sema::ActOnInitializerError(Decl *D) {
11451  // Our main concern here is re-establishing invariants like "a
11452  // variable's type is either dependent or complete".
11453  if (!D || D->isInvalidDecl()) return;
11454
11455  VarDecl *VD = dyn_cast<VarDecl>(D);
11456  if (!VDreturn;
11457
11458  // Bindings are not usable if we can't make sense of the initializer.
11459  if (auto *DD = dyn_cast<DecompositionDecl>(D))
11460    for (auto *BD : DD->bindings())
11461      BD->setInvalidDecl();
11462
11463  // Auto types are meaningless if we can't make sense of the initializer.
11464  if (ParsingInitForAutoVars.count(D)) {
11465    D->setInvalidDecl();
11466    return;
11467  }
11468
11469  QualType Ty = VD->getType();
11470  if (Ty->isDependentType()) return;
11471
11472  // Require a complete type.
11473  if (RequireCompleteType(VD->getLocation(),
11474                          Context.getBaseElementType(Ty),
11475                          diag::err_typecheck_decl_incomplete_type)) {
11476    VD->setInvalidDecl();
11477    return;
11478  }
11479
11480  // Require a non-abstract type.
11481  if (RequireNonAbstractType(VD->getLocation(), Ty,
11482                             diag::err_abstract_type_in_decl,
11483                             AbstractVariableType)) {
11484    VD->setInvalidDecl();
11485    return;
11486  }
11487
11488  // Don't bother complaining about constructors or destructors,
11489  // though.
11490}
11491
11492void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
11493  // If there is no declaration, there was an error parsing it. Just ignore it.
11494  if (!RealDecl)
11495    return;
11496
11497  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
11498    QualType Type = Var->getType();
11499
11500    // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
11501    if (isa<DecompositionDecl>(RealDecl)) {
11502      Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
11503      Var->setInvalidDecl();
11504      return;
11505    }
11506
11507    Expr *TmpInit = nullptr;
11508    if (Type->isUndeducedType() &&
11509        DeduceVariableDeclarationType(VarfalseTmpInit))
11510      return;
11511
11512    // C++11 [class.static.data]p3: A static data member can be declared with
11513    // the constexpr specifier; if so, its declaration shall specify
11514    // a brace-or-equal-initializer.
11515    // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
11516    // the definition of a variable [...] or the declaration of a static data
11517    // member.
11518    if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
11519        !Var->isThisDeclarationADemotedDefinition()) {
11520      if (Var->isStaticDataMember()) {
11521        // C++1z removes the relevant rule; the in-class declaration is always
11522        // a definition there.
11523        if (!getLangOpts().CPlusPlus17) {
11524          Diag(Var->getLocation(),
11525               diag::err_constexpr_static_mem_var_requires_init)
11526            << Var->getDeclName();
11527          Var->setInvalidDecl();
11528          return;
11529        }
11530      } else {
11531        Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
11532        Var->setInvalidDecl();
11533        return;
11534      }
11535    }
11536
11537    // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
11538    // be initialized.
11539    if (!Var->isInvalidDecl() &&
11540        Var->getType().getAddressSpace() == LangAS::opencl_constant &&
11541        Var->getStorageClass() != SC_Extern && !Var->getInit()) {
11542      Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
11543      Var->setInvalidDecl();
11544      return;
11545    }
11546
11547    switch (Var->isThisDeclarationADefinition()) {
11548    case VarDecl::Definition:
11549      if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
11550        break;
11551
11552      // We have an out-of-line definition of a static data member
11553      // that has an in-class initializer, so we type-check this like
11554      // a declaration.
11555      //
11556      LLVM_FALLTHROUGH;
11557
11558    case VarDecl::DeclarationOnly:
11559      // It's only a declaration.
11560
11561      // Block scope. C99 6.7p7: If an identifier for an object is
11562      // declared with no linkage (C99 6.2.2p6), the type for the
11563      // object shall be complete.
11564      if (!Type->isDependentType() && Var->isLocalVarDecl() &&
11565          !Var->hasLinkage() && !Var->isInvalidDecl() &&
11566          RequireCompleteType(Var->getLocation(), Type,
11567                              diag::err_typecheck_decl_incomplete_type))
11568        Var->setInvalidDecl();
11569
11570      // Make sure that the type is not abstract.
11571      if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11572          RequireNonAbstractType(Var->getLocation(), Type,
11573                                 diag::err_abstract_type_in_decl,
11574                                 AbstractVariableType))
11575        Var->setInvalidDecl();
11576      if (!Type->isDependentType() && !Var->isInvalidDecl() &&
11577          Var->getStorageClass() == SC_PrivateExtern) {
11578        Diag(Var->getLocation(), diag::warn_private_extern);
11579        Diag(Var->getLocation(), diag::note_private_extern);
11580      }
11581
11582      return;
11583
11584    case VarDecl::TentativeDefinition:
11585      // File scope. C99 6.9.2p2: A declaration of an identifier for an
11586      // object that has file scope without an initializer, and without a
11587      // storage-class specifier or with the storage-class specifier "static",
11588      // constitutes a tentative definition. Note: A tentative definition with
11589      // external linkage is valid (C99 6.2.2p5).
11590      if (!Var->isInvalidDecl()) {
11591        if (const IncompleteArrayType *ArrayT
11592                                    = Context.getAsIncompleteArrayType(Type)) {
11593          if (RequireCompleteType(Var->getLocation(),
11594                                  ArrayT->getElementType(),
11595                                  diag::err_illegal_decl_array_incomplete_type))
11596            Var->setInvalidDecl();
11597        } else if (Var->getStorageClass() == SC_Static) {
11598          // C99 6.9.2p3: If the declaration of an identifier for an object is
11599          // a tentative definition and has internal linkage (C99 6.2.2p3), the
11600          // declared type shall not be an incomplete type.
11601          // NOTE: code such as the following
11602          //     static struct s;
11603          //     struct s { int a; };
11604          // is accepted by gcc. Hence here we issue a warning instead of
11605          // an error and we do not invalidate the static declaration.
11606          // NOTE: to avoid multiple warnings, only check the first declaration.
11607          if (Var->isFirstDecl())
11608            RequireCompleteType(Var->getLocation(), Type,
11609                                diag::ext_typecheck_decl_incomplete_type);
11610        }
11611      }
11612
11613      // Record the tentative definition; we're done.
11614      if (!Var->isInvalidDecl())
11615        TentativeDefinitions.push_back(Var);
11616      return;
11617    }
11618
11619    // Provide a specific diagnostic for uninitialized variable
11620    // definitions with incomplete array type.
11621    if (Type->isIncompleteArrayType()) {
11622      Diag(Var->getLocation(),
11623           diag::err_typecheck_incomplete_array_needs_initializer);
11624      Var->setInvalidDecl();
11625      return;
11626    }
11627
11628    // Provide a specific diagnostic for uninitialized variable
11629    // definitions with reference type.
11630    if (Type->isReferenceType()) {
11631      Diag(Var->getLocation(), diag::err_reference_var_requires_init)
11632        << Var->getDeclName()
11633        << SourceRange(Var->getLocation(), Var->getLocation());
11634      Var->setInvalidDecl();
11635      return;
11636    }
11637
11638    // Do not attempt to type-check the default initializer for a
11639    // variable with dependent type.
11640    if (Type->isDependentType())
11641      return;
11642
11643    if (Var->isInvalidDecl())
11644      return;
11645
11646    if (!Var->hasAttr<AliasAttr>()) {
11647      if (RequireCompleteType(Var->getLocation(),
11648                              Context.getBaseElementType(Type),
11649                              diag::err_typecheck_decl_incomplete_type)) {
11650        Var->setInvalidDecl();
11651        return;
11652      }
11653    } else {
11654      return;
11655    }
11656
11657    // The variable can not have an abstract class type.
11658    if (RequireNonAbstractType(Var->getLocation(), Type,
11659                               diag::err_abstract_type_in_decl,
11660                               AbstractVariableType)) {
11661      Var->setInvalidDecl();
11662      return;
11663    }
11664
11665    // Check for jumps past the implicit initializer.  C++0x
11666    // clarifies that this applies to a "variable with automatic
11667    // storage duration", not a "local variable".
11668    // C++11 [stmt.dcl]p3
11669    //   A program that jumps from a point where a variable with automatic
11670    //   storage duration is not in scope to a point where it is in scope is
11671    //   ill-formed unless the variable has scalar type, class type with a
11672    //   trivial default constructor and a trivial destructor, a cv-qualified
11673    //   version of one of these types, or an array of one of the preceding
11674    //   types and is declared without an initializer.
11675    if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
11676      if (const RecordType *Record
11677            = Context.getBaseElementType(Type)->getAs<RecordType>()) {
11678        CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
11679        // Mark the function (if we're in one) for further checking even if the
11680        // looser rules of C++11 do not require such checks, so that we can
11681        // diagnose incompatibilities with C++98.
11682        if (!CXXRecord->isPOD())
11683          setFunctionHasBranchProtectedScope();
11684      }
11685    }
11686
11687    // C++03 [dcl.init]p9:
11688    //   If no initializer is specified for an object, and the
11689    //   object is of (possibly cv-qualified) non-POD class type (or
11690    //   array thereof), the object shall be default-initialized; if
11691    //   the object is of const-qualified type, the underlying class
11692    //   type shall have a user-declared default
11693    //   constructor. Otherwise, if no initializer is specified for
11694    //   a non- static object, the object and its subobjects, if
11695    //   any, have an indeterminate initial value); if the object
11696    //   or any of its subobjects are of const-qualified type, the
11697    //   program is ill-formed.
11698    // C++0x [dcl.init]p11:
11699    //   If no initializer is specified for an object, the object is
11700    //   default-initialized; [...].
11701    InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
11702    InitializationKind Kind
11703      = InitializationKind::CreateDefault(Var->getLocation());
11704
11705    InitializationSequence InitSeq(*this, Entity, Kind, None);
11706    ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
11707    if (Init.isInvalid())
11708      Var->setInvalidDecl();
11709    else if (Init.get()) {
11710      Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
11711      // This is important for template substitution.
11712      Var->setInitStyle(VarDecl::CallInit);
11713    }
11714
11715    CheckCompleteVariableDeclaration(Var);
11716  }
11717}
11718
11719void Sema::ActOnCXXForRangeDecl(Decl *D) {
11720  // If there is no declaration, there was an error parsing it. Ignore it.
11721  if (!D)
11722    return;
11723
11724  VarDecl *VD = dyn_cast<VarDecl>(D);
11725  if (!VD) {
11726    Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
11727    D->setInvalidDecl();
11728    return;
11729  }
11730
11731  VD->setCXXForRangeDecl(true);
11732
11733  // for-range-declaration cannot be given a storage class specifier.
11734  int Error = -1;
11735  switch (VD->getStorageClass()) {
11736  case SC_None:
11737    break;
11738  case SC_Extern:
11739    Error = 0;
11740    break;
11741  case SC_Static:
11742    Error = 1;
11743    break;
11744  case SC_PrivateExtern:
11745    Error = 2;
11746    break;
11747  case SC_Auto:
11748    Error = 3;
11749    break;
11750  case SC_Register:
11751    Error = 4;
11752    break;
11753  }
11754  if (Error != -1) {
11755    Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
11756      << VD->getDeclName() << Error;
11757    D->setInvalidDecl();
11758  }
11759}
11760
11761StmtResult
11762Sema::ActOnCXXForRangeIdentifier(Scope *SSourceLocation IdentLoc,
11763                                 IdentifierInfo *Ident,
11764                                 ParsedAttributes &Attrs,
11765                                 SourceLocation AttrEnd) {
11766  // C++1y [stmt.iter]p1:
11767  //   A range-based for statement of the form
11768  //      for ( for-range-identifier : for-range-initializer ) statement
11769  //   is equivalent to
11770  //      for ( auto&& for-range-identifier : for-range-initializer ) statement
11771  DeclSpec DS(Attrs.getPool().getFactory());
11772
11773  const char *PrevSpec;
11774  unsigned DiagID;
11775  DS.SetTypeSpecType(DeclSpec::TST_autoIdentLocPrevSpecDiagID,
11776                     getPrintingPolicy());
11777
11778  Declarator D(DSDeclaratorContext::ForContext);
11779  D.SetIdentifier(IdentIdentLoc);
11780  D.takeAttributes(AttrsAttrEnd);
11781
11782  ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
11783  D.AddTypeInfo(DeclaratorChunk::getReference(0IdentLoc/*lvalue*/ false),
11784                IdentLoc);
11785  Decl *Var = ActOnDeclarator(SD);
11786  cast<VarDecl>(Var)->setCXXForRangeDecl(true);
11787  FinalizeDeclaration(Var);
11788  return ActOnDeclStmt(FinalizeDeclaratorGroup(SDSVar), IdentLoc,
11789                       AttrEnd.isValid() ? AttrEnd : IdentLoc);
11790}
11791
11792void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
11793  if (var->isInvalidDecl()) return;
11794
11795  if (getLangOpts().OpenCL) {
11796    // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
11797    // initialiser
11798    if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
11799        !var->hasInit()) {
11800      Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
11801          << 1 /*Init*/;
11802      var->setInvalidDecl();
11803      return;
11804    }
11805  }
11806
11807  // In Objective-C, don't allow jumps past the implicit initialization of a
11808  // local retaining variable.
11809  if (getLangOpts().ObjC &&
11810      var->hasLocalStorage()) {
11811    switch (var->getType().getObjCLifetime()) {
11812    case Qualifiers::OCL_None:
11813    case Qualifiers::OCL_ExplicitNone:
11814    case Qualifiers::OCL_Autoreleasing:
11815      break;
11816
11817    case Qualifiers::OCL_Weak:
11818    case Qualifiers::OCL_Strong:
11819      setFunctionHasBranchProtectedScope();
11820      break;
11821    }
11822  }
11823
11824  if (var->hasLocalStorage() &&
11825      var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
11826    setFunctionHasBranchProtectedScope();
11827
11828  // Warn about externally-visible variables being defined without a
11829  // prior declaration.  We only want to do this for global
11830  // declarations, but we also specifically need to avoid doing it for
11831  // class members because the linkage of an anonymous class can
11832  // change if it's later given a typedef name.
11833  if (var->isThisDeclarationADefinition() &&
11834      var->getDeclContext()->getRedeclContext()->isFileContext() &&
11835      var->isExternallyVisible() && var->hasLinkage() &&
11836      !var->isInline() && !var->getDescribedVarTemplate() &&
11837      !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
11838      !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
11839                                  var->getLocation())) {
11840    // Find a previous declaration that's not a definition.
11841    VarDecl *prev = var->getPreviousDecl();
11842    while (prev && prev->isThisDeclarationADefinition())
11843      prev = prev->getPreviousDecl();
11844
11845    if (!prev)
11846      Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
11847  }
11848
11849  // Cache the result of checking for constant initialization.
11850  Optional<boolCacheHasConstInit;
11851  const Expr *CacheCulprit;
11852  auto checkConstInit = [&]() mutable {
11853    if (!CacheHasConstInit)
11854      CacheHasConstInit = var->getInit()->isConstantInitializer(
11855            Context, var->getType()->isReferenceType(), &CacheCulprit);
11856    return *CacheHasConstInit;
11857  };
11858
11859  if (var->getTLSKind() == VarDecl::TLS_Static) {
11860    if (var->getType().isDestructedType()) {
11861      // GNU C++98 edits for __thread, [basic.start.term]p3:
11862      //   The type of an object with thread storage duration shall not
11863      //   have a non-trivial destructor.
11864      Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
11865      if (getLangOpts().CPlusPlus11)
11866        Diag(var->getLocation(), diag::note_use_thread_local);
11867    } else if (getLangOpts().CPlusPlus && var->hasInit()) {
11868      if (!checkConstInit()) {
11869        // GNU C++98 edits for __thread, [basic.start.init]p4:
11870        //   An object of thread storage duration shall not require dynamic
11871        //   initialization.
11872        // FIXME: Need strict checking here.
11873        Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
11874          << CacheCulprit->getSourceRange();
11875        if (getLangOpts().CPlusPlus11)
11876          Diag(var->getLocation(), diag::note_use_thread_local);
11877      }
11878    }
11879  }
11880
11881  // Apply section attributes and pragmas to global variables.
11882  bool GlobalStorage = var->hasGlobalStorage();
11883  if (GlobalStorage && var->isThisDeclarationADefinition() &&
11884      !inTemplateInstantiation()) {
11885    PragmaStack<StringLiteral *> *Stack = nullptr;
11886    int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
11887    if (var->getType().isConstQualified())
11888      Stack = &ConstSegStack;
11889    else if (!var->getInit()) {
11890      Stack = &BSSSegStack;
11891      SectionFlags |= ASTContext::PSF_Write;
11892    } else {
11893      Stack = &DataSegStack;
11894      SectionFlags |= ASTContext::PSF_Write;
11895    }
11896    if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
11897      var->addAttr(SectionAttr::CreateImplicit(
11898          Context, SectionAttr::Declspec_allocate,
11899          Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
11900    }
11901    if (const SectionAttr *SA = var->getAttr<SectionAttr>())
11902      if (UnifySection(SA->getName(), SectionFlags, var))
11903        var->dropAttr<SectionAttr>();
11904
11905    // Apply the init_seg attribute if this has an initializer.  If the
11906    // initializer turns out to not be dynamic, we'll end up ignoring this
11907    // attribute.
11908    if (CurInitSeg && var->getInit())
11909      var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
11910                                               CurInitSegLoc));
11911  }
11912
11913  // All the following checks are C++ only.
11914  if (!getLangOpts().CPlusPlus) {
11915      // If this variable must be emitted, add it as an initializer for the
11916      // current module.
11917     if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
11918       Context.addModuleInitializer(ModuleScopes.back().Module, var);
11919     return;
11920  }
11921
11922  if (auto *DD = dyn_cast<DecompositionDecl>(var))
11923    CheckCompleteDecompositionDeclaration(DD);
11924
11925  QualType type = var->getType();
11926  if (type->isDependentType()) return;
11927
11928  if (var->hasAttr<BlocksAttr>())
11929    getCurFunction()->addByrefBlockVar(var);
11930
11931  Expr *Init = var->getInit();
11932  bool IsGlobal = GlobalStorage && !var->isStaticLocal();
11933  QualType baseType = Context.getBaseElementType(type);
11934
11935  if (Init && !Init->isValueDependent()) {
11936    if (var->isConstexpr()) {
11937      SmallVector<PartialDiagnosticAt8Notes;
11938      if (!var->evaluateValue(Notes) || !var->isInitICE()) {
11939        SourceLocation DiagLoc = var->getLocation();
11940        // If the note doesn't add any useful information other than a source
11941        // location, fold it into the primary diagnostic.
11942        if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
11943              diag::note_invalid_subexpr_in_const_expr) {
11944          DiagLoc = Notes[0].first;
11945          Notes.clear();
11946        }
11947        Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
11948          << var << Init->getSourceRange();
11949        for (unsigned I = 0, N = Notes.size(); I != N; ++I)
11950          Diag(Notes[I].first, Notes[I].second);
11951      }
11952    } else if (var->isUsableInConstantExpressions(Context)) {
11953      // Check whether the initializer of a const variable of integral or
11954      // enumeration type is an ICE now, since we can't tell whether it was
11955      // initialized by a constant expression if we check later.
11956      var->checkInitIsICE();
11957    }
11958
11959    // Don't emit further diagnostics about constexpr globals since they
11960    // were just diagnosed.
11961    if (!var->isConstexpr() && GlobalStorage &&
11962            var->hasAttr<RequireConstantInitAttr>()) {
11963      // FIXME: Need strict checking in C++03 here.
11964      bool DiagErr = getLangOpts().CPlusPlus11
11965          ? !var->checkInitIsICE() : !checkConstInit();
11966      if (DiagErr) {
11967        auto attr = var->getAttr<RequireConstantInitAttr>();
11968        Diag(var->getLocation(), diag::err_require_constant_init_failed)
11969          << Init->getSourceRange();
11970        Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
11971          << attr->getRange();
11972        if (getLangOpts().CPlusPlus11) {
11973          APValue Value;
11974          SmallVector<PartialDiagnosticAt8Notes;
11975          Init->EvaluateAsInitializer(Value, getASTContext(), var, Notes);
11976          for (auto &it : Notes)
11977            Diag(it.first, it.second);
11978        } else {
11979          Diag(CacheCulprit->getExprLoc(),
11980               diag::note_invalid_subexpr_in_const_expr)
11981              << CacheCulprit->getSourceRange();
11982        }
11983      }
11984    }
11985    else if (!var->isConstexpr() && IsGlobal &&
11986             !getDiagnostics().isIgnored(diag::warn_global_constructor,
11987                                    var->getLocation())) {
11988      // Warn about globals which don't have a constant initializer.  Don't
11989      // warn about globals with a non-trivial destructor because we already
11990      // warned about them.
11991      CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
11992      if (!(RD && !RD->hasTrivialDestructor())) {
11993        if (!checkConstInit())
11994          Diag(var->getLocation(), diag::warn_global_constructor)
11995            << Init->getSourceRange();
11996      }
11997    }
11998  }
11999
12000  // Require the destructor.
12001  if (const RecordType *recordType = baseType->getAs<RecordType>())
12002    FinalizeVarWithDestructor(varrecordType);
12003
12004  // If this variable must be emitted, add it as an initializer for the current
12005  // module.
12006  if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
12007    Context.addModuleInitializer(ModuleScopes.back().Module, var);
12008}
12009
12010/// Determines if a variable's alignment is dependent.
12011static bool hasDependentAlignment(VarDecl *VD) {
12012  if (VD->getType()->isDependentType())
12013    return true;
12014  for (auto *I : VD->specific_attrs<AlignedAttr>())
12015    if (I->isAlignmentDependent())
12016      return true;
12017  return false;
12018}
12019
12020/// Check if VD needs to be dllexport/dllimport due to being in a
12021/// dllexport/import function.
12022void Sema::CheckStaticLocalForDllExport(VarDecl *VD) {
12023  isStaticLocal()", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 12023, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(VD->isStaticLocal());
12024
12025  auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12026
12027  // Find outermost function when VD is in lambda function.
12028  while (FD && !getDLLAttr(FD) &&
12029         !FD->hasAttr<DLLExportStaticLocalAttr>() &&
12030         !FD->hasAttr<DLLImportStaticLocalAttr>()) {
12031    FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
12032  }
12033
12034  if (!FD)
12035    return;
12036
12037  // Static locals inherit dll attributes from their function.
12038  if (Attr *A = getDLLAttr(FD)) {
12039    auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
12040    NewAttr->setInherited(true);
12041    VD->addAttr(NewAttr);
12042  } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
12043    auto *NewAttr = ::new (getASTContext()) DLLExportAttr(A->getRange(),
12044                                                          getASTContext(),
12045                                                          A->getSpellingListIndex());
12046    NewAttr->setInherited(true);
12047    VD->addAttr(NewAttr);
12048
12049    // Export this function to enforce exporting this static variable even
12050    // if it is not used in this compilation unit.
12051    if (!FD->hasAttr<DLLExportAttr>())
12052      FD->addAttr(NewAttr);
12053
12054  } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
12055    auto *NewAttr = ::new (getASTContext()) DLLImportAttr(A->getRange(),
12056                                                          getASTContext(),
12057                                                          A->getSpellingListIndex());
12058    NewAttr->setInherited(true);
12059    VD->addAttr(NewAttr);
12060  }
12061}
12062
12063/// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
12064/// any semantic actions necessary after any initializer has been attached.
12065void Sema::FinalizeDeclaration(Decl *ThisDecl) {
12066  // Note that we are no longer parsing the initializer for this declaration.
12067  ParsingInitForAutoVars.erase(ThisDecl);
12068
12069  VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
12070  if (!VD)
12071    return;
12072
12073  // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
12074  if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
12075      !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
12076    if (PragmaClangBSSSection.Valid)
12077      VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(Context,
12078                                                            PragmaClangBSSSection.SectionName,
12079                                                            PragmaClangBSSSection.PragmaLocation));
12080    if (PragmaClangDataSection.Valid)
12081      VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(Context,
12082                                                             PragmaClangDataSection.SectionName,
12083                                                             PragmaClangDataSection.PragmaLocation));
12084    if (PragmaClangRodataSection.Valid)
12085      VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(Context,
12086                                                               PragmaClangRodataSection.SectionName,
12087                                                               PragmaClangRodataSection.PragmaLocation));
12088  }
12089
12090  if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
12091    for (auto *BD : DD->bindings()) {
12092      FinalizeDeclaration(BD);
12093    }
12094  }
12095
12096  checkAttributesAfterMerging(*this, *VD);
12097
12098  // Perform TLS alignment check here after attributes attached to the variable
12099  // which may affect the alignment have been processed. Only perform the check
12100  // if the target has a maximum TLS alignment (zero means no constraints).
12101  if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
12102    // Protect the check so that it's not performed on dependent types and
12103    // dependent alignments (we can't determine the alignment in that case).
12104    if (VD->getTLSKind() && !hasDependentAlignment(VD) &&
12105        !VD->isInvalidDecl()) {
12106      CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
12107      if (Context.getDeclAlign(VD) > MaxAlignChars) {
12108        Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
12109          << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
12110          << (unsigned)MaxAlignChars.getQuantity();
12111      }
12112    }
12113  }
12114
12115  if (VD->isStaticLocal()) {
12116    CheckStaticLocalForDllExport(VD);
12117
12118    if (dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
12119      // CUDA 8.0 E.3.9.4: Within the body of a __device__ or __global__
12120      // function, only __shared__ variables or variables without any device
12121      // memory qualifiers may be declared with static storage class.
12122      // Note: It is unclear how a function-scope non-const static variable
12123      // without device memory qualifier is implemented, therefore only static
12124      // const variable without device memory qualifier is allowed.
12125      [&]() {
12126        if (!getLangOpts().CUDA)
12127          return;
12128        if (VD->hasAttr<CUDASharedAttr>())
12129          return;
12130        if (VD->getType().isConstQualified() &&
12131            !(VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
12132          return;
12133        if (CUDADiagIfDeviceCode(VD->getLocation(),
12134                                 diag::err_device_static_local_var)
12135            << CurrentCUDATarget())
12136          VD->setInvalidDecl();
12137      }();
12138    }
12139  }
12140
12141  // Perform check for initializers of device-side global variables.
12142  // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
12143  // 7.5). We must also apply the same checks to all __shared__
12144  // variables whether they are local or not. CUDA also allows
12145  // constant initializers for __constant__ and __device__ variables.
12146  if (getLangOpts().CUDA)
12147    checkAllowedCUDAInitializer(VD);
12148
12149  // Grab the dllimport or dllexport attribute off of the VarDecl.
12150  const InheritableAttr *DLLAttr = getDLLAttr(VD);
12151
12152  // Imported static data members cannot be defined out-of-line.
12153  if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
12154    if (VD->isStaticDataMember() && VD->isOutOfLine() &&
12155        VD->isThisDeclarationADefinition()) {
12156      // We allow definitions of dllimport class template static data members
12157      // with a warning.
12158      CXXRecordDecl *Context =
12159        cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
12160      bool IsClassTemplateMember =
12161          isa<ClassTemplatePartialSpecializationDecl>(Context) ||
12162          Context->getDescribedClassTemplate();
12163
12164      Diag(VD->getLocation(),
12165           IsClassTemplateMember
12166               ? diag::warn_attribute_dllimport_static_field_definition
12167               : diag::err_attribute_dllimport_static_field_definition);
12168      Diag(IA->getLocation(), diag::note_attribute);
12169      if (!IsClassTemplateMember)
12170        VD->setInvalidDecl();
12171    }
12172  }
12173
12174  // dllimport/dllexport variables cannot be thread local, their TLS index
12175  // isn't exported with the variable.
12176  if (DLLAttr && VD->getTLSKind()) {
12177    auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
12178    if (F && getDLLAttr(F)) {
12179      isStaticLocal()", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 12179, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(VD->isStaticLocal());
12180      // But if this is a static local in a dlimport/dllexport function, the
12181      // function will never be inlined, which means the var would never be
12182      // imported, so having it marked import/export is safe.
12183    } else {
12184      Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
12185                                                                    << DLLAttr;
12186      VD->setInvalidDecl();
12187    }
12188  }
12189
12190  if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
12191    if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
12192      Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
12193      VD->dropAttr<UsedAttr>();
12194    }
12195  }
12196
12197  const DeclContext *DC = VD->getDeclContext();
12198  // If there's a #pragma GCC visibility in scope, and this isn't a class
12199  // member, set the visibility of this variable.
12200  if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
12201    AddPushedVisibilityAttribute(VD);
12202
12203  // FIXME: Warn on unused var template partial specializations.
12204  if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
12205    MarkUnusedFileScopedDecl(VD);
12206
12207  // Now we have parsed the initializer and can update the table of magic
12208  // tag values.
12209  if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
12210      !VD->getType()->isIntegralOrEnumerationType())
12211    return;
12212
12213  for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
12214    const Expr *MagicValueExpr = VD->getInit();
12215    if (!MagicValueExpr) {
12216      continue;
12217    }
12218    llvm::APSInt MagicValueInt;
12219    if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
12220      Diag(I->getRange().getBegin(),
12221           diag::err_type_tag_for_datatype_not_ice)
12222        << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12223      continue;
12224    }
12225    if (MagicValueInt.getActiveBits() > 64) {
12226      Diag(I->getRange().getBegin(),
12227           diag::err_type_tag_for_datatype_too_large)
12228        << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
12229      continue;
12230    }
12231    uint64_t MagicValue = MagicValueInt.getZExtValue();
12232    RegisterTypeTagForDatatype(I->getArgumentKind(),
12233                               MagicValue,
12234                               I->getMatchingCType(),
12235                               I->getLayoutCompatible(),
12236                               I->getMustBeNull());
12237  }
12238}
12239
12240static bool hasDeducedAuto(DeclaratorDecl *DD) {
12241  auto *VD = dyn_cast<VarDecl>(DD);
12242  return VD && !VD->getType()->hasAutoForTrailingReturnType();
12243}
12244
12245Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *Sconst DeclSpec &DS,
12246                                                   ArrayRef<Decl *> Group) {
12247  SmallVector<Decl*, 8Decls;
12248
12249  if (DS.isTypeSpecOwned())
12250    Decls.push_back(DS.getRepAsDecl());
12251
12252  DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
12253  DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
12254  bool DiagnosedMultipleDecomps = false;
12255  DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
12256  bool DiagnosedNonDeducedAuto = false;
12257
12258  for (unsigned i = 0e = Group.size(); i != e; ++i) {
12259    if (Decl *D = Group[i]) {
12260      // For declarators, there are some additional syntactic-ish checks we need
12261      // to perform.
12262      if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
12263        if (!FirstDeclaratorInGroup)
12264          FirstDeclaratorInGroup = DD;
12265        if (!FirstDecompDeclaratorInGroup)
12266          FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
12267        if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
12268            !hasDeducedAuto(DD))
12269          FirstNonDeducedAutoInGroup = DD;
12270
12271        if (FirstDeclaratorInGroup != DD) {
12272          // A decomposition declaration cannot be combined with any other
12273          // declaration in the same group.
12274          if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
12275            Diag(FirstDecompDeclaratorInGroup->getLocation(),
12276                 diag::err_decomp_decl_not_alone)
12277                << FirstDeclaratorInGroup->getSourceRange()
12278                << DD->getSourceRange();
12279            DiagnosedMultipleDecomps = true;
12280          }
12281
12282          // A declarator that uses 'auto' in any way other than to declare a
12283          // variable with a deduced type cannot be combined with any other
12284          // declarator in the same group.
12285          if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
12286            Diag(FirstNonDeducedAutoInGroup->getLocation(),
12287                 diag::err_auto_non_deduced_not_alone)
12288                << FirstNonDeducedAutoInGroup->getType()
12289                       ->hasAutoForTrailingReturnType()
12290                << FirstDeclaratorInGroup->getSourceRange()
12291                << DD->getSourceRange();
12292            DiagnosedNonDeducedAuto = true;
12293          }
12294        }
12295      }
12296
12297      Decls.push_back(D);
12298    }
12299  }
12300
12301  if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
12302    if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
12303      handleTagNumbering(TagS);
12304      if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
12305          getLangOpts().CPlusPlus)
12306        Context.addDeclaratorForUnnamedTagDecl(TagFirstDeclaratorInGroup);
12307    }
12308  }
12309
12310  return BuildDeclaratorGroup(Decls);
12311}
12312
12313/// BuildDeclaratorGroup - convert a list of declarations into a declaration
12314/// group, performing any necessary semantic checking.
12315Sema::DeclGroupPtrTy
12316Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
12317  // C++14 [dcl.spec.auto]p7: (DR1347)
12318  //   If the type that replaces the placeholder type is not the same in each
12319  //   deduction, the program is ill-formed.
12320  if (Group.size() > 1) {
12321    QualType Deduced;
12322    VarDecl *DeducedDecl = nullptr;
12323    for (unsigned i = 0e = Group.size(); i != e; ++i) {
12324      VarDecl *D = dyn_cast<VarDecl>(Group[i]);
12325      if (!D || D->isInvalidDecl())
12326        break;
12327      DeducedType *DT = D->getType()->getContainedDeducedType();
12328      if (!DT || DT->getDeducedType().isNull())
12329        continue;
12330      if (Deduced.isNull()) {
12331        Deduced = DT->getDeducedType();
12332        DeducedDecl = D;
12333      } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
12334        auto *AT = dyn_cast<AutoType>(DT);
12335        Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
12336             diag::err_auto_different_deductions)
12337          << (AT ? (unsigned)AT->getKeyword() : 3)
12338          << Deduced << DeducedDecl->getDeclName()
12339          << DT->getDeducedType() << D->getDeclName()
12340          << DeducedDecl->getInit()->getSourceRange()
12341          << D->getInit()->getSourceRange();
12342        D->setInvalidDecl();
12343        break;
12344      }
12345    }
12346  }
12347
12348  ActOnDocumentableDecls(Group);
12349
12350  return DeclGroupPtrTy::make(
12351      DeclGroupRef::Create(Context, Group.data(), Group.size()));
12352}
12353
12354void Sema::ActOnDocumentableDecl(Decl *D) {
12355  ActOnDocumentableDecls(D);
12356}
12357
12358void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
12359  // Don't parse the comment if Doxygen diagnostics are ignored.
12360  if (Group.empty() || !Group[0])
12361    return;
12362
12363  if (Diags.isIgnored(diag::warn_doc_param_not_found,
12364                      Group[0]->getLocation()) &&
12365      Diags.isIgnored(diag::warn_unknown_comment_command_name,
12366                      Group[0]->getLocation()))
12367    return;
12368
12369  if (Group.size() >= 2) {
12370    // This is a decl group.  Normally it will contain only declarations
12371    // produced from declarator list.  But in case we have any definitions or
12372    // additional declaration references:
12373    //   'typedef struct S {} S;'
12374    //   'typedef struct S *S;'
12375    //   'struct S *pS;'
12376    // FinalizeDeclaratorGroup adds these as separate declarations.
12377    Decl *MaybeTagDecl = Group[0];
12378    if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
12379      Group = Group.slice(1);
12380    }
12381  }
12382
12383  // See if there are any new comments that are not attached to a decl.
12384  ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
12385  if (!Comments.empty() &&
12386      !Comments.back()->isAttached()) {
12387    // There is at least one comment that not attached to a decl.
12388    // Maybe it should be attached to one of these decls?
12389    //
12390    // Note that this way we pick up not only comments that precede the
12391    // declaration, but also comments that *follow* the declaration -- thanks to
12392    // the lookahead in the lexer: we've consumed the semicolon and looked
12393    // ahead through comments.
12394    for (unsigned i = 0, e = Group.size(); i != e; ++i)
12395      Context.getCommentForDecl(Group[i], &PP);
12396  }
12397}
12398
12399/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
12400/// to introduce parameters into function prototype scope.
12401Decl *Sema::ActOnParamDeclarator(Scope *SDeclarator &D) {
12402  const DeclSpec &DS = D.getDeclSpec();
12403
12404  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
12405
12406  // C++03 [dcl.stc]p2 also permits 'auto'.
12407  StorageClass SC = SC_None;
12408  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
12409    SC = SC_Register;
12410    // In C++11, the 'register' storage class specifier is deprecated.
12411    // In C++17, it is not allowed, but we tolerate it as an extension.
12412    if (getLangOpts().CPlusPlus11) {
12413      Diag(DS.getStorageClassSpecLoc(),
12414           getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
12415                                     : diag::warn_deprecated_register)
12416        << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
12417    }
12418  } else if (getLangOpts().CPlusPlus &&
12419             DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
12420    SC = SC_Auto;
12421  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
12422    Diag(DS.getStorageClassSpecLoc(),
12423         diag::err_invalid_storage_class_in_func_decl);
12424    D.getMutableDeclSpec().ClearStorageClassSpecs();
12425  }
12426
12427  if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
12428    Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
12429      << DeclSpec::getSpecifierName(TSCS);
12430  if (DS.isInlineSpecified())
12431    Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
12432        << getLangOpts().CPlusPlus17;
12433  if (DS.isConstexprSpecified())
12434    Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
12435      << 0;
12436
12437  DiagnoseFunctionSpecifiers(DS);
12438
12439  TypeSourceInfo *TInfo = GetTypeForDeclarator(DS);
12440  QualType parmDeclType = TInfo->getType();
12441
12442  if (getLangOpts().CPlusPlus) {
12443    // Check that there are no default arguments inside the type of this
12444    // parameter.
12445    CheckExtraCXXDefaultArguments(D);
12446
12447    // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
12448    if (D.getCXXScopeSpec().isSet()) {
12449      Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
12450        << D.getCXXScopeSpec().getRange();
12451      D.getCXXScopeSpec().clear();
12452    }
12453  }
12454
12455  // Ensure we have a valid name
12456  IdentifierInfo *II = nullptr;
12457  if (D.hasName()) {
12458    II = D.getIdentifier();
12459    if (!II) {
12460      Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
12461        << GetNameForDeclarator(D).getName();
12462      D.setInvalidType(true);
12463    }
12464  }
12465
12466  // Check for redeclaration of parameters, e.g. int foo(int x, int x);
12467  if (II) {
12468    LookupResult R(*thisIID.getIdentifierLoc(), LookupOrdinaryName,
12469                   ForVisibleRedeclaration);
12470    LookupName(RS);
12471    if (R.isSingleResult()) {
12472      NamedDecl *PrevDecl = R.getFoundDecl();
12473      if (PrevDecl->isTemplateParameter()) {
12474        // Maybe we will complain about the shadowed template parameter.
12475        DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12476        // Just pretend that we didn't see the previous declaration.
12477        PrevDecl = nullptr;
12478      } else if (S->isDeclScope(PrevDecl)) {
12479        Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
12480        Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
12481
12482        // Recover by removing the name
12483        II = nullptr;
12484        D.SetIdentifier(nullptrD.getIdentifierLoc());
12485        D.setInvalidType(true);
12486      }
12487    }
12488  }
12489
12490  // Temporarily put parameter variables in the translation unit, not
12491  // the enclosing context.  This prevents them from accidentally
12492  // looking like class members in C++.
12493  ParmVarDecl *New =
12494      CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
12495                     D.getIdentifierLoc(), IIparmDeclTypeTInfoSC);
12496
12497  if (D.isInvalidType())
12498    New->setInvalidDecl();
12499
12500  isFunctionPrototypeScope()", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 12500, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(S->isFunctionPrototypeScope());
12501  getFunctionPrototypeDepth() >= 1", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 12501, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(S->getFunctionPrototypeDepth() >= 1);
12502  New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
12503                    S->getNextFunctionPrototypeIndex());
12504
12505  // Add the parameter declaration into this scope.
12506  S->AddDecl(New);
12507  if (II)
12508    IdResolver.AddDecl(New);
12509
12510  ProcessDeclAttributes(SNewD);
12511
12512  if (D.getDeclSpec().isModulePrivateSpecified())
12513    Diag(New->getLocation(), diag::err_module_private_local)
12514      << 1 << New->getDeclName()
12515      << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12516      << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12517
12518  if (New->hasAttr<BlocksAttr>()) {
12519    Diag(New->getLocation(), diag::err_block_on_nonlocal);
12520  }
12521  return New;
12522}
12523
12524/// Synthesizes a variable for a parameter arising from a
12525/// typedef.
12526ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
12527                                              SourceLocation Loc,
12528                                              QualType T) {
12529  /* FIXME: setting StartLoc == Loc.
12530     Would it be worth to modify callers so as to provide proper source
12531     location for the unnamed parameters, embedding the parameter's type? */
12532  ParmVarDecl *Param = ParmVarDecl::Create(ContextDCLocLocnullptr,
12533                                TContext.getTrivialTypeSourceInfo(TLoc),
12534                                           SC_Nonenullptr);
12535  Param->setImplicit();
12536  return Param;
12537}
12538
12539void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
12540  // Don't diagnose unused-parameter errors in template instantiations; we
12541  // will already have done so in the template itself.
12542  if (inTemplateInstantiation())
12543    return;
12544
12545  for (const ParmVarDecl *Parameter : Parameters) {
12546    if (!Parameter->isReferenced() && Parameter->getDeclName() &&
12547        !Parameter->hasAttr<UnusedAttr>()) {
12548      Diag(Parameter->getLocation(), diag::warn_unused_parameter)
12549        << Parameter->getDeclName();
12550    }
12551  }
12552}
12553
12554void Sema::DiagnoseSizeOfParametersAndReturnValue(
12555    ArrayRef<ParmVarDecl *> ParametersQualType ReturnTyNamedDecl *D) {
12556  if (LangOpts.NumLargeByValueCopy == 0// No check.
12557    return;
12558
12559  // Warn if the return value is pass-by-value and larger than the specified
12560  // threshold.
12561  if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
12562    unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
12563    if (Size > LangOpts.NumLargeByValueCopy)
12564      Diag(D->getLocation(), diag::warn_return_value_size)
12565          << D->getDeclName() << Size;
12566  }
12567
12568  // Warn if any parameter is pass-by-value and larger than the specified
12569  // threshold.
12570  for (const ParmVarDecl *Parameter : Parameters) {
12571    QualType T = Parameter->getType();
12572    if (T->isDependentType() || !T.isPODType(Context))
12573      continue;
12574    unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
12575    if (Size > LangOpts.NumLargeByValueCopy)
12576      Diag(Parameter->getLocation(), diag::warn_parameter_size)
12577          << Parameter->getDeclName() << Size;
12578  }
12579}
12580
12581ParmVarDecl *Sema::CheckParameter(DeclContext *DCSourceLocation StartLoc,
12582                                  SourceLocation NameLocIdentifierInfo *Name,
12583                                  QualType TTypeSourceInfo *TSInfo,
12584                                  StorageClass SC) {
12585  // In ARC, infer a lifetime qualifier for appropriate parameter types.
12586  if (getLangOpts().ObjCAutoRefCount &&
12587      T.getObjCLifetime() == Qualifiers::OCL_None &&
12588      T->isObjCLifetimeType()) {
12589
12590    Qualifiers::ObjCLifetime lifetime;
12591
12592    // Special cases for arrays:
12593    //   - if it's const, use __unsafe_unretained
12594    //   - otherwise, it's an error
12595    if (T->isArrayType()) {
12596      if (!T.isConstQualified()) {
12597        if (DelayedDiagnostics.shouldDelayDiagnostics())
12598          DelayedDiagnostics.add(
12599              sema::DelayedDiagnostic::makeForbiddenType(
12600              NameLoc, diag::err_arc_array_param_no_ownership, T, false));
12601        else
12602          Diag(NameLoc, diag::err_arc_array_param_no_ownership)
12603              << TSInfo->getTypeLoc().getSourceRange();
12604      }
12605      lifetime = Qualifiers::OCL_ExplicitNone;
12606    } else {
12607      lifetime = T->getObjCARCImplicitLifetime();
12608    }
12609    T = Context.getLifetimeQualifiedType(Tlifetime);
12610  }
12611
12612  ParmVarDecl *New = ParmVarDecl::Create(ContextDCStartLocNameLocName,
12613                                         Context.getAdjustedParameterType(T),
12614                                         TSInfoSCnullptr);
12615
12616  // Parameters can not be abstract class types.
12617  // For record types, this is done by the AbstractClassUsageDiagnoser once
12618  // the class has been completely parsed.
12619  if (!CurContext->isRecord() &&
12620      RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
12621                             AbstractParamType))
12622    New->setInvalidDecl();
12623
12624  // Parameter declarators cannot be interface types. All ObjC objects are
12625  // passed by reference.
12626  if (T->isObjCObjectType()) {
12627    SourceLocation TypeEndLoc =
12628        getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
12629    Diag(NameLoc,
12630         diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
12631      << FixItHint::CreateInsertion(TypeEndLoc, "*");
12632    T = Context.getObjCObjectPointerType(T);
12633    New->setType(T);
12634  }
12635
12636  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
12637  // duration shall not be qualified by an address-space qualifier."
12638  // Since all parameters have automatic store duration, they can not have
12639  // an address space.
12640  if (T.getAddressSpace() != LangAS::Default &&
12641      // OpenCL allows function arguments declared to be an array of a type
12642      // to be qualified with an address space.
12643      !(getLangOpts().OpenCL &&
12644        (T->isArrayType() || T.getAddressSpace() == LangAS::opencl_private))) {
12645    Diag(NameLoc, diag::err_arg_with_address_space);
12646    New->setInvalidDecl();
12647  }
12648
12649  return New;
12650}
12651
12652void Sema::ActOnFinishKNRParamDeclarations(Scope *SDeclarator &D,
12653                                           SourceLocation LocAfterDecls) {
12654  DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
12655
12656  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
12657  // for a K&R function.
12658  if (!FTI.hasPrototype) {
12659    for (int i = FTI.NumParamsi != 0/* decrement in loop */) {
12660      --i;
12661      if (FTI.Params[i].Param == nullptr) {
12662        SmallString<256Code;
12663        llvm::raw_svector_ostream(Code)
12664            << "  int " << FTI.Params[i].Ident->getName() << ";\n";
12665        Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
12666            << FTI.Params[i].Ident
12667            << FixItHint::CreateInsertion(LocAfterDecls, Code);
12668
12669        // Implicitly declare the argument as type 'int' for lack of a better
12670        // type.
12671        AttributeFactory attrs;
12672        DeclSpec DS(attrs);
12673        const charPrevSpec// unused
12674        unsigned DiagID// unused
12675        DS.SetTypeSpecType(DeclSpec::TST_intFTI.Params[i].IdentLocPrevSpec,
12676                           DiagIDContext.getPrintingPolicy());
12677        // Use the identifier location for the type source range.
12678        DS.SetRangeStart(FTI.Params[i].IdentLoc);
12679        DS.SetRangeEnd(FTI.Params[i].IdentLoc);
12680        Declarator ParamD(DSDeclaratorContext::KNRTypeListContext);
12681        ParamD.SetIdentifier(FTI.Params[i].IdentFTI.Params[i].IdentLoc);
12682        FTI.Params[i].Param = ActOnParamDeclarator(SParamD);
12683      }
12684    }
12685  }
12686}
12687
12688Decl *
12689Sema::ActOnStartOfFunctionDef(Scope *FnBodyScopeDeclarator &D,
12690                              MultiTemplateParamsArg TemplateParameterLists,
12691                              SkipBodyInfo *SkipBody) {
12692   (0) . __assert_fail ("getCurFunctionDecl() == nullptr && \"Function parsing confused\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 12692, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
12693   (0) . __assert_fail ("D.isFunctionDeclarator() && \"Not a function declarator!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 12693, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(D.isFunctionDeclarator() && "Not a function declarator!");
12694  Scope *ParentScope = FnBodyScope->getParent();
12695
12696  D.setFunctionDefinitionKind(FDK_Definition);
12697  Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
12698  return ActOnStartOfFunctionDef(FnBodyScopeDPSkipBody);
12699}
12700
12701void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
12702  Consumer.HandleInlineFunctionDefinition(D);
12703}
12704
12705static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
12706                             const FunctionDecl*& PossibleZeroParamPrototype) {
12707  // Don't warn about invalid declarations.
12708  if (FD->isInvalidDecl())
12709    return false;
12710
12711  // Or declarations that aren't global.
12712  if (!FD->isGlobal())
12713    return false;
12714
12715  // Don't warn about C++ member functions.
12716  if (isa<CXXMethodDecl>(FD))
12717    return false;
12718
12719  // Don't warn about 'main'.
12720  if (FD->isMain())
12721    return false;
12722
12723  // Don't warn about inline functions.
12724  if (FD->isInlined())
12725    return false;
12726
12727  // Don't warn about function templates.
12728  if (FD->getDescribedFunctionTemplate())
12729    return false;
12730
12731  // Don't warn about function template specializations.
12732  if (FD->isFunctionTemplateSpecialization())
12733    return false;
12734
12735  // Don't warn for OpenCL kernels.
12736  if (FD->hasAttr<OpenCLKernelAttr>())
12737    return false;
12738
12739  // Don't warn on explicitly deleted functions.
12740  if (FD->isDeleted())
12741    return false;
12742
12743  bool MissingPrototype = true;
12744  for (const FunctionDecl *Prev = FD->getPreviousDecl();
12745       PrevPrev = Prev->getPreviousDecl()) {
12746    // Ignore any declarations that occur in function or method
12747    // scope, because they aren't visible from the header.
12748    if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
12749      continue;
12750
12751    MissingPrototype = !Prev->getType()->isFunctionProtoType();
12752    if (FD->getNumParams() == 0)
12753      PossibleZeroParamPrototype = Prev;
12754    break;
12755  }
12756
12757  return MissingPrototype;
12758}
12759
12760void
12761Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
12762                                   const FunctionDecl *EffectiveDefinition,
12763                                   SkipBodyInfo *SkipBody) {
12764  const FunctionDecl *Definition = EffectiveDefinition;
12765  if (!Definition && !FD->isDefined(Definition) && !FD->isCXXClassMember()) {
12766    // If this is a friend function defined in a class template, it does not
12767    // have a body until it is used, nevertheless it is a definition, see
12768    // [temp.inst]p2:
12769    //
12770    // ... for the purpose of determining whether an instantiated redeclaration
12771    // is valid according to [basic.def.odr] and [class.mem], a declaration that
12772    // corresponds to a definition in the template is considered to be a
12773    // definition.
12774    //
12775    // The following code must produce redefinition error:
12776    //
12777    //     template<typename T> struct C20 { friend void func_20() {} };
12778    //     C20<int> c20i;
12779    //     void func_20() {}
12780    //
12781    for (auto I : FD->redecls()) {
12782      if (I != FD && !I->isInvalidDecl() &&
12783          I->getFriendObjectKind() != Decl::FOK_None) {
12784        if (FunctionDecl *Original = I->getInstantiatedFromMemberFunction()) {
12785          if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
12786            // A merged copy of the same function, instantiated as a member of
12787            // the same class, is OK.
12788            if (declaresSameEntity(OrigFD, Original) &&
12789                declaresSameEntity(cast<Decl>(I->getLexicalDeclContext()),
12790                                   cast<Decl>(FD->getLexicalDeclContext())))
12791              continue;
12792          }
12793
12794          if (Original->isThisDeclarationADefinition()) {
12795            Definition = I;
12796            break;
12797          }
12798        }
12799      }
12800    }
12801  }
12802
12803  if (!Definition)
12804    // Similar to friend functions a friend function template may be a
12805    // definition and do not have a body if it is instantiated in a class
12806    // template.
12807    if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate()) {
12808      for (auto I : FTD->redecls()) {
12809        auto D = cast<FunctionTemplateDecl>(I);
12810        if (D != FTD) {
12811           (0) . __assert_fail ("!D->isThisDeclarationADefinition() && \"More than one definition in redeclaration chain\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 12812, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!D->isThisDeclarationADefinition() &&
12812 (0) . __assert_fail ("!D->isThisDeclarationADefinition() && \"More than one definition in redeclaration chain\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 12812, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">                 "More than one definition in redeclaration chain");
12813          if (D->getFriendObjectKind() != Decl::FOK_None)
12814            if (FunctionTemplateDecl *FT =
12815                                       D->getInstantiatedFromMemberTemplate()) {
12816              if (FT->isThisDeclarationADefinition()) {
12817                Definition = D->getTemplatedDecl();
12818                break;
12819              }
12820            }
12821        }
12822      }
12823    }
12824
12825  if (!Definition)
12826    return;
12827
12828  if (canRedefineFunction(DefinitiongetLangOpts()))
12829    return;
12830
12831  // Don't emit an error when this is redefinition of a typo-corrected
12832  // definition.
12833  if (TypoCorrectedFunctionDefinitions.count(Definition))
12834    return;
12835
12836  // If we don't have a visible definition of the function, and it's inline or
12837  // a template, skip the new definition.
12838  if (SkipBody && !hasVisibleDefinition(Definition) &&
12839      (Definition->getFormalLinkage() == InternalLinkage ||
12840       Definition->isInlined() ||
12841       Definition->getDescribedFunctionTemplate() ||
12842       Definition->getNumTemplateParameterLists())) {
12843    SkipBody->ShouldSkip = true;
12844    SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
12845    if (auto *TD = Definition->getDescribedFunctionTemplate())
12846      makeMergedDefinitionVisible(TD);
12847    makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
12848    return;
12849  }
12850
12851  if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
12852      Definition->getStorageClass() == SC_Extern)
12853    Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
12854        << FD->getDeclName() << getLangOpts().CPlusPlus;
12855  else
12856    Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
12857
12858  Diag(Definition->getLocation(), diag::note_previous_definition);
12859  FD->setInvalidDecl();
12860}
12861
12862static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
12863                                   Sema &S) {
12864  CXXRecordDecl *const LambdaClass = CallOperator->getParent();
12865
12866  LambdaScopeInfo *LSI = S.PushLambdaScope();
12867  LSI->CallOperator = CallOperator;
12868  LSI->Lambda = LambdaClass;
12869  LSI->ReturnType = CallOperator->getReturnType();
12870  const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
12871
12872  if (LCD == LCD_None)
12873    LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
12874  else if (LCD == LCD_ByCopy)
12875    LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
12876  else if (LCD == LCD_ByRef)
12877    LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
12878  DeclarationNameInfo DNI = CallOperator->getNameInfo();
12879
12880  LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
12881  LSI->Mutable = !CallOperator->isConst();
12882
12883  // Add the captures to the LSI so they can be noted as already
12884  // captured within tryCaptureVar.
12885  auto I = LambdaClass->field_begin();
12886  for (const auto &C : LambdaClass->captures()) {
12887    if (C.capturesVariable()) {
12888      VarDecl *VD = C.getCapturedVar();
12889      if (VD->isInitCapture())
12890        S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
12891      QualType CaptureType = VD->getType();
12892      const bool ByRef = C.getCaptureKind() == LCK_ByRef;
12893      LSI->addCapture(VD, /*IsBlock*/false, ByRef,
12894          /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
12895          /*EllipsisLoc*/C.isPackExpansion()
12896                         ? C.getEllipsisLoc() : SourceLocation(),
12897          CaptureType, /*Expr*/ nullptr);
12898
12899    } else if (C.capturesThis()) {
12900      LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
12901                              /*Expr*/ nullptr,
12902                              C.getCaptureKind() == LCK_StarThis);
12903    } else {
12904      LSI->addVLATypeCapture(C.getLocation(), I->getType());
12905    }
12906    ++I;
12907  }
12908}
12909
12910Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScopeDecl *D,
12911                                    SkipBodyInfo *SkipBody) {
12912  if (!D) {
12913    // Parsing the function declaration failed in some way. Push on a fake scope
12914    // anyway so we can try to parse the function body.
12915    PushFunctionScope();
12916    PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12917    return D;
12918  }
12919
12920  FunctionDecl *FD = nullptr;
12921
12922  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
12923    FD = FunTmpl->getTemplatedDecl();
12924  else
12925    FD = cast<FunctionDecl>(D);
12926
12927  // Do not push if it is a lambda because one is already pushed when building
12928  // the lambda in ActOnStartOfLambdaDefinition().
12929  if (!isLambdaCallOperator(FD))
12930    PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
12931
12932  // Check for defining attributes before the check for redefinition.
12933  if (const auto *Attr = FD->getAttr<AliasAttr>()) {
12934    Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
12935    FD->dropAttr<AliasAttr>();
12936    FD->setInvalidDecl();
12937  }
12938  if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
12939    Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
12940    FD->dropAttr<IFuncAttr>();
12941    FD->setInvalidDecl();
12942  }
12943
12944  // See if this is a redefinition. If 'will have body' is already set, then
12945  // these checks were already performed when it was set.
12946  if (!FD->willHaveBody() && !FD->isLateTemplateParsed()) {
12947    CheckForFunctionRedefinition(FDnullptrSkipBody);
12948
12949    // If we're skipping the body, we're done. Don't enter the scope.
12950    if (SkipBody && SkipBody->ShouldSkip)
12951      return D;
12952  }
12953
12954  // Mark this function as "will have a body eventually".  This lets users to
12955  // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
12956  // this function.
12957  FD->setWillHaveBody();
12958
12959  // If we are instantiating a generic lambda call operator, push
12960  // a LambdaScopeInfo onto the function stack.  But use the information
12961  // that's already been calculated (ActOnLambdaExpr) to prime the current
12962  // LambdaScopeInfo.
12963  // When the template operator is being specialized, the LambdaScopeInfo,
12964  // has to be properly restored so that tryCaptureVariable doesn't try
12965  // and capture any new variables. In addition when calculating potential
12966  // captures during transformation of nested lambdas, it is necessary to
12967  // have the LSI properly restored.
12968  if (isGenericLambdaCallOperatorSpecialization(FD)) {
12969     (0) . __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 12971, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(inTemplateInstantiation() &&
12970 (0) . __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 12971, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           "There should be an active template instantiation on the stack "
12971 (0) . __assert_fail ("inTemplateInstantiation() && \"There should be an active template instantiation on the stack \" \"when instantiating a generic lambda!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 12971, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           "when instantiating a generic lambda!");
12972    RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
12973  } else {
12974    // Enter a new function scope
12975    PushFunctionScope();
12976  }
12977
12978  // Builtin functions cannot be defined.
12979  if (unsigned BuiltinID = FD->getBuiltinID()) {
12980    if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
12981        !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
12982      Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
12983      FD->setInvalidDecl();
12984    }
12985  }
12986
12987  // The return type of a function definition must be complete
12988  // (C99 6.9.1p3, C++ [dcl.fct]p6).
12989  QualType ResultType = FD->getReturnType();
12990  if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
12991      !FD->isInvalidDecl() &&
12992      RequireCompleteType(FD->getLocation(), ResultType,
12993                          diag::err_func_def_incomplete_result))
12994    FD->setInvalidDecl();
12995
12996  if (FnBodyScope)
12997    PushDeclContext(FnBodyScopeFD);
12998
12999  // Check the validity of our function parameters
13000  CheckParmsForFunctionDef(FD->parameters(),
13001                           /*CheckParameterNames=*/true);
13002
13003  // Add non-parameter declarations already in the function to the current
13004  // scope.
13005  if (FnBodyScope) {
13006    for (Decl *NPD : FD->decls()) {
13007      auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
13008      if (!NonParmDecl)
13009        continue;
13010       (0) . __assert_fail ("!isa(NonParmDecl) && \"parameters should not be in newly created FD yet\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 13011, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!isa<ParmVarDecl>(NonParmDecl) &&
13011 (0) . __assert_fail ("!isa(NonParmDecl) && \"parameters should not be in newly created FD yet\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 13011, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">             "parameters should not be in newly created FD yet");
13012
13013      // If the decl has a name, make it accessible in the current scope.
13014      if (NonParmDecl->getDeclName())
13015        PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
13016
13017      // Similarly, dive into enums and fish their constants out, making them
13018      // accessible in this scope.
13019      if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
13020        for (auto *EI : ED->enumerators())
13021          PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
13022      }
13023    }
13024  }
13025
13026  // Introduce our parameters into the function scope
13027  for (auto Param : FD->parameters()) {
13028    Param->setOwningFunction(FD);
13029
13030    // If this has an identifier, add it to the scope stack.
13031    if (Param->getIdentifier() && FnBodyScope) {
13032      CheckShadow(FnBodyScope, Param);
13033
13034      PushOnScopeChains(Param, FnBodyScope);
13035    }
13036  }
13037
13038  // Ensure that the function's exception specification is instantiated.
13039  if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
13040    ResolveExceptionSpec(D->getLocation(), FPT);
13041
13042  // dllimport cannot be applied to non-inline function definitions.
13043  if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
13044      !FD->isTemplateInstantiation()) {
13045    hasAttr()", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 13045, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!FD->hasAttr<DLLExportAttr>());
13046    Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
13047    FD->setInvalidDecl();
13048    return D;
13049  }
13050  // We want to attach documentation to original Decl (which might be
13051  // a function template).
13052  ActOnDocumentableDecl(D);
13053  if (getCurLexicalContext()->isObjCContainer() &&
13054      getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
13055      getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
13056    Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
13057
13058  return D;
13059}
13060
13061/// Given the set of return statements within a function body,
13062/// compute the variables that are subject to the named return value
13063/// optimization.
13064///
13065/// Each of the variables that is subject to the named return value
13066/// optimization will be marked as NRVO variables in the AST, and any
13067/// return statement that has a marked NRVO variable as its NRVO candidate can
13068/// use the named return value optimization.
13069///
13070/// This function applies a very simplistic algorithm for NRVO: if every return
13071/// statement in the scope of a variable has the same NRVO candidate, that
13072/// candidate is an NRVO variable.
13073void Sema::computeNRVO(Stmt *BodyFunctionScopeInfo *Scope) {
13074  ReturnStmt **Returns = Scope->Returns.data();
13075
13076  for (unsigned I = 0E = Scope->Returns.size(); I != E; ++I) {
13077    if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
13078      if (!NRVOCandidate->isNRVOVariable())
13079        Returns[I]->setNRVOCandidate(nullptr);
13080    }
13081  }
13082}
13083
13084bool Sema::canDelayFunctionBody(const Declarator &D) {
13085  // We can't delay parsing the body of a constexpr function template (yet).
13086  if (D.getDeclSpec().isConstexprSpecified())
13087    return false;
13088
13089  // We can't delay parsing the body of a function template with a deduced
13090  // return type (yet).
13091  if (D.getDeclSpec().hasAutoTypeSpec()) {
13092    // If the placeholder introduces a non-deduced trailing return type,
13093    // we can still delay parsing it.
13094    if (D.getNumTypeObjects()) {
13095      const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
13096      if (Outer.Kind == DeclaratorChunk::Function &&
13097          Outer.Fun.hasTrailingReturnType()) {
13098        QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
13099        return Ty.isNull() || !Ty->isUndeducedType();
13100      }
13101    }
13102    return false;
13103  }
13104
13105  return true;
13106}
13107
13108bool Sema::canSkipFunctionBody(Decl *D) {
13109  // We cannot skip the body of a function (or function template) which is
13110  // constexpr, since we may need to evaluate its body in order to parse the
13111  // rest of the file.
13112  // We cannot skip the body of a function with an undeduced return type,
13113  // because any callers of that function need to know the type.
13114  if (const FunctionDecl *FD = D->getAsFunction()) {
13115    if (FD->isConstexpr())
13116      return false;
13117    // We can't simply call Type::isUndeducedType here, because inside template
13118    // auto can be deduced to a dependent type, which is not considered
13119    // "undeduced".
13120    if (FD->getReturnType()->getContainedDeducedType())
13121      return false;
13122  }
13123  return Consumer.shouldSkipFunctionBody(D);
13124}
13125
13126Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
13127  if (!Decl)
13128    return nullptr;
13129  if (FunctionDecl *FD = Decl->getAsFunction())
13130    FD->setHasSkippedBody();
13131  else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
13132    MD->setHasSkippedBody();
13133  return Decl;
13134}
13135
13136Decl *Sema::ActOnFinishFunctionBody(Decl *DStmt *BodyArg) {
13137  return ActOnFinishFunctionBody(DBodyArgfalse);
13138}
13139
13140/// RAII object that pops an ExpressionEvaluationContext when exiting a function
13141/// body.
13142class ExitFunctionBodyRAII {
13143public:
13144  ExitFunctionBodyRAII(Sema &Sbool IsLambda) : S(S), IsLambda(IsLambda) {}
13145  ~ExitFunctionBodyRAII() {
13146    if (!IsLambda)
13147      S.PopExpressionEvaluationContext();
13148  }
13149
13150private:
13151  Sema &S;
13152  bool IsLambda = false;
13153};
13154
13155Decl *Sema::ActOnFinishFunctionBody(Decl *dclStmt *Body,
13156                                    bool IsInstantiation) {
13157  FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
13158
13159  sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
13160  sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
13161
13162  if (getLangOpts().Coroutines && getCurFunction()->isCoroutine())
13163    CheckCompletedCoroutineBody(FDBody);
13164
13165  // Do not call PopExpressionEvaluationContext() if it is a lambda because one
13166  // is already popped when finishing the lambda in BuildLambdaExpr(). This is
13167  // meant to pop the context added in ActOnStartOfFunctionDef().
13168  ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
13169
13170  if (FD) {
13171    FD->setBody(Body);
13172    FD->setWillHaveBody(false);
13173
13174    if (getLangOpts().CPlusPlus14) {
13175      if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
13176          FD->getReturnType()->isUndeducedType()) {
13177        // If the function has a deduced result type but contains no 'return'
13178        // statements, the result type as written must be exactly 'auto', and
13179        // the deduced result type is 'void'.
13180        if (!FD->getReturnType()->getAs<AutoType>()) {
13181          Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
13182              << FD->getReturnType();
13183          FD->setInvalidDecl();
13184        } else {
13185          // Substitute 'void' for the 'auto' in the type.
13186          TypeLoc ResultType = getReturnTypeLoc(FD);
13187          Context.adjustDeducedFunctionResultType(
13188              FDSubstAutoType(ResultType.getType(), Context.VoidTy));
13189        }
13190      }
13191    } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
13192      // In C++11, we don't use 'auto' deduction rules for lambda call
13193      // operators because we don't support return type deduction.
13194      auto *LSI = getCurLambda();
13195      if (LSI->HasImplicitReturnType) {
13196        deduceClosureReturnType(*LSI);
13197
13198        // C++11 [expr.prim.lambda]p4:
13199        //   [...] if there are no return statements in the compound-statement
13200        //   [the deduced type is] the type void
13201        QualType RetType =
13202            LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
13203
13204        // Update the return type to the deduced type.
13205        const FunctionProtoType *Proto =
13206            FD->getType()->getAs<FunctionProtoType>();
13207        FD->setType(Context.getFunctionType(RetTypeProto->getParamTypes(),
13208                                            Proto->getExtProtoInfo()));
13209      }
13210    }
13211
13212    // If the function implicitly returns zero (like 'main') or is naked,
13213    // don't complain about missing return statements.
13214    if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
13215      WP.disableCheckFallThrough();
13216
13217    // MSVC permits the use of pure specifier (=0) on function definition,
13218    // defined at class scope, warn about this non-standard construct.
13219    if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
13220      Diag(FD->getLocation(), diag::ext_pure_function_definition);
13221
13222    if (!FD->isInvalidDecl()) {
13223      // Don't diagnose unused parameters of defaulted or deleted functions.
13224      if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody())
13225        DiagnoseUnusedParameters(FD->parameters());
13226      DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
13227                                             FD->getReturnType(), FD);
13228
13229      // If this is a structor, we need a vtable.
13230      if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
13231        MarkVTableUsed(FD->getLocation(), Constructor->getParent());
13232      else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
13233        MarkVTableUsed(FD->getLocation(), Destructor->getParent());
13234
13235      // Try to apply the named return value optimization. We have to check
13236      // if we can do this here because lambdas keep return statements around
13237      // to deduce an implicit return type.
13238      if (FD->getReturnType()->isRecordType() &&
13239          (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
13240        computeNRVO(BodygetCurFunction());
13241    }
13242
13243    // GNU warning -Wmissing-prototypes:
13244    //   Warn if a global function is defined without a previous
13245    //   prototype declaration. This warning is issued even if the
13246    //   definition itself provides a prototype. The aim is to detect
13247    //   global functions that fail to be declared in header files.
13248    const FunctionDecl *PossibleZeroParamPrototype = nullptr;
13249    if (ShouldWarnAboutMissingPrototype(FDPossibleZeroParamPrototype)) {
13250      Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
13251
13252      if (PossibleZeroParamPrototype) {
13253        // We found a declaration that is not a prototype,
13254        // but that could be a zero-parameter prototype
13255        if (TypeSourceInfo *TI =
13256                PossibleZeroParamPrototype->getTypeSourceInfo()) {
13257          TypeLoc TL = TI->getTypeLoc();
13258          if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
13259            Diag(PossibleZeroParamPrototype->getLocation(),
13260                 diag::note_declaration_not_a_prototype)
13261                << PossibleZeroParamPrototype
13262                << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
13263        }
13264      }
13265
13266      // GNU warning -Wstrict-prototypes
13267      //   Warn if K&R function is defined without a previous declaration.
13268      //   This warning is issued only if the definition itself does not provide
13269      //   a prototype. Only K&R definitions do not provide a prototype.
13270      //   An empty list in a function declarator that is part of a definition
13271      //   of that function specifies that the function has no parameters
13272      //   (C99 6.7.5.3p14)
13273      if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
13274          !LangOpts.CPlusPlus) {
13275        TypeSourceInfo *TI = FD->getTypeSourceInfo();
13276        TypeLoc TL = TI->getTypeLoc();
13277        FunctionTypeLoc FTL = TL.getAsAdjusted<FunctionTypeLoc>();
13278        Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
13279      }
13280    }
13281
13282    // Warn on CPUDispatch with an actual body.
13283    if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
13284      if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
13285        if (!CmpndBody->body_empty())
13286          Diag(CmpndBody->body_front()->getBeginLoc(),
13287               diag::warn_dispatch_body_ignored);
13288
13289    if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
13290      const CXXMethodDecl *KeyFunction;
13291      if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
13292          MD->isVirtual() &&
13293          (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
13294          MD == KeyFunction->getCanonicalDecl()) {
13295        // Update the key-function state if necessary for this ABI.
13296        if (FD->isInlined() &&
13297            !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
13298          Context.setNonKeyFunction(MD);
13299
13300          // If the newly-chosen key function is already defined, then we
13301          // need to mark the vtable as used retroactively.
13302          KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
13303          const FunctionDecl *Definition;
13304          if (KeyFunction && KeyFunction->isDefined(Definition))
13305            MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
13306        } else {
13307          // We just defined they key function; mark the vtable as used.
13308          MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
13309        }
13310      }
13311    }
13312
13313     (0) . __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 13314, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
13314 (0) . __assert_fail ("(FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) && \"Function parsing confused\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 13314, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           "Function parsing confused");
13315  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
13316     (0) . __assert_fail ("MD == getCurMethodDecl() && \"Method parsing confused\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 13316, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(MD == getCurMethodDecl() && "Method parsing confused");
13317    MD->setBody(Body);
13318    if (!MD->isInvalidDecl()) {
13319      if (!MD->hasSkippedBody())
13320        DiagnoseUnusedParameters(MD->parameters());
13321      DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
13322                                             MD->getReturnType(), MD);
13323
13324      if (Body)
13325        computeNRVO(BodygetCurFunction());
13326    }
13327    if (getCurFunction()->ObjCShouldCallSuper) {
13328      Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
13329          << MD->getSelector().getAsString();
13330      getCurFunction()->ObjCShouldCallSuper = false;
13331    }
13332    if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
13333      const ObjCMethodDecl *InitMethod = nullptr;
13334      bool isDesignated =
13335          MD->isDesignatedInitializerForTheInterface(&InitMethod);
13336      assert(isDesignated && InitMethod);
13337      (void)isDesignated;
13338
13339      auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
13340        auto IFace = MD->getClassInterface();
13341        if (!IFace)
13342          return false;
13343        auto SuperD = IFace->getSuperClass();
13344        if (!SuperD)
13345          return false;
13346        return SuperD->getIdentifier() ==
13347            NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
13348      };
13349      // Don't issue this warning for unavailable inits or direct subclasses
13350      // of NSObject.
13351      if (!MD->isUnavailable() && !superIsNSObject(MD)) {
13352        Diag(MD->getLocation(),
13353             diag::warn_objc_designated_init_missing_super_call);
13354        Diag(InitMethod->getLocation(),
13355             diag::note_objc_designated_init_marked_here);
13356      }
13357      getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
13358    }
13359    if (getCurFunction()->ObjCWarnForNoInitDelegation) {
13360      // Don't issue this warning for unavaialable inits.
13361      if (!MD->isUnavailable())
13362        Diag(MD->getLocation(),
13363             diag::warn_objc_secondary_init_missing_init_call);
13364      getCurFunction()->ObjCWarnForNoInitDelegation = false;
13365    }
13366  } else {
13367    // Parsing the function declaration failed in some way. Pop the fake scope
13368    // we pushed on.
13369    PopFunctionScopeInfo(ActivePolicydcl);
13370    return nullptr;
13371  }
13372
13373  if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
13374    DiagnoseUnguardedAvailabilityViolations(dcl);
13375
13376   (0) . __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 13378, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!getCurFunction()->ObjCShouldCallSuper &&
13377 (0) . __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 13378, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "This should only be set for ObjC methods, which should have been "
13378 (0) . __assert_fail ("!getCurFunction()->ObjCShouldCallSuper && \"This should only be set for ObjC methods, which should have been \" \"handled in the block above.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 13378, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "handled in the block above.");
13379
13380  // Verify and clean out per-function state.
13381  if (Body && (!FD || !FD->isDefaulted())) {
13382    // C++ constructors that have function-try-blocks can't have return
13383    // statements in the handlers of that block. (C++ [except.handle]p14)
13384    // Verify this.
13385    if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
13386      DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
13387
13388    // Verify that gotos and switch cases don't jump into scopes illegally.
13389    if (getCurFunction()->NeedsScopeChecking() &&
13390        !PP.isCodeCompletionEnabled())
13391      DiagnoseInvalidJumps(Body);
13392
13393    if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
13394      if (!Destructor->getParent()->isDependentType())
13395        CheckDestructor(Destructor);
13396
13397      MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
13398                                             Destructor->getParent());
13399    }
13400
13401    // If any errors have occurred, clear out any temporaries that may have
13402    // been leftover. This ensures that these temporaries won't be picked up for
13403    // deletion in some later function.
13404    if (getDiagnostics().hasErrorOccurred() ||
13405        getDiagnostics().getSuppressAllDiagnostics()) {
13406      DiscardCleanupsInEvaluationContext();
13407    }
13408    if (!getDiagnostics().hasUncompilableErrorOccurred() &&
13409        !isa<FunctionTemplateDecl>(dcl)) {
13410      // Since the body is valid, issue any analysis-based warnings that are
13411      // enabled.
13412      ActivePolicy = &WP;
13413    }
13414
13415    if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
13416        (!CheckConstexprFunctionDecl(FD) ||
13417         !CheckConstexprFunctionBody(FDBody)))
13418      FD->setInvalidDecl();
13419
13420    if (FD && FD->hasAttr<NakedAttr>()) {
13421      for (const Stmt *S : Body->children()) {
13422        // Allow local register variables without initializer as they don't
13423        // require prologue.
13424        bool RegisterVariables = false;
13425        if (auto *DS = dyn_cast<DeclStmt>(S)) {
13426          for (const auto *Decl : DS->decls()) {
13427            if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
13428              RegisterVariables =
13429                  Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
13430              if (!RegisterVariables)
13431                break;
13432            }
13433          }
13434        }
13435        if (RegisterVariables)
13436          continue;
13437        if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
13438          Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
13439          Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
13440          FD->setInvalidDecl();
13441          break;
13442        }
13443      }
13444    }
13445
13446     (0) . __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 13448, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(ExprCleanupObjects.size() ==
13447 (0) . __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 13448, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">               ExprEvalContexts.back().NumCleanupObjects &&
13448 (0) . __assert_fail ("ExprCleanupObjects.size() == ExprEvalContexts.back().NumCleanupObjects && \"Leftover temporaries in function\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 13448, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           "Leftover temporaries in function");
13449     (0) . __assert_fail ("!Cleanup.exprNeedsCleanups() && \"Unaccounted cleanups in function\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 13449, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
13450     (0) . __assert_fail ("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 13451, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(MaybeODRUseExprs.empty() &&
13451 (0) . __assert_fail ("MaybeODRUseExprs.empty() && \"Leftover expressions for odr-use checking\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 13451, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           "Leftover expressions for odr-use checking");
13452  }
13453
13454  if (!IsInstantiation)
13455    PopDeclContext();
13456
13457  PopFunctionScopeInfo(ActivePolicydcl);
13458  // If any errors have occurred, clear out any temporaries that may have
13459  // been leftover. This ensures that these temporaries won't be picked up for
13460  // deletion in some later function.
13461  if (getDiagnostics().hasErrorOccurred()) {
13462    DiscardCleanupsInEvaluationContext();
13463  }
13464
13465  return dcl;
13466}
13467
13468/// When we finish delayed parsing of an attribute, we must attach it to the
13469/// relevant Decl.
13470void Sema::ActOnFinishDelayedAttribute(Scope *SDecl *D,
13471                                       ParsedAttributes &Attrs) {
13472  // Always attach attributes to the underlying decl.
13473  if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
13474    D = TD->getTemplatedDecl();
13475  ProcessDeclAttributeList(SDAttrs);
13476
13477  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
13478    if (Method->isStatic())
13479      checkThisInStaticMemberFunctionAttributes(Method);
13480}
13481
13482/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
13483/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
13484NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
13485                                          IdentifierInfo &IIScope *S) {
13486  // Find the scope in which the identifier is injected and the corresponding
13487  // DeclContext.
13488  // FIXME: C89 does not say what happens if there is no enclosing block scope.
13489  // In that case, we inject the declaration into the translation unit scope
13490  // instead.
13491  Scope *BlockScope = S;
13492  while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
13493    BlockScope = BlockScope->getParent();
13494
13495  Scope *ContextScope = BlockScope;
13496  while (!ContextScope->getEntity())
13497    ContextScope = ContextScope->getParent();
13498  ContextRAII SavedContext(*thisContextScope->getEntity());
13499
13500  // Before we produce a declaration for an implicitly defined
13501  // function, see whether there was a locally-scoped declaration of
13502  // this name as a function or variable. If so, use that
13503  // (non-visible) declaration, and complain about it.
13504  NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
13505  if (ExternCPrev) {
13506    // We still need to inject the function into the enclosing block scope so
13507    // that later (non-call) uses can see it.
13508    PushOnScopeChains(ExternCPrevBlockScope/*AddToContext*/false);
13509
13510    // C89 footnote 38:
13511    //   If in fact it is not defined as having type "function returning int",
13512    //   the behavior is undefined.
13513    if (!isa<FunctionDecl>(ExternCPrev) ||
13514        !Context.typesAreCompatible(
13515            cast<FunctionDecl>(ExternCPrev)->getType(),
13516            Context.getFunctionNoProtoType(Context.IntTy))) {
13517      Diag(Loc, diag::ext_use_out_of_scope_declaration)
13518          << ExternCPrev << !getLangOpts().C99;
13519      Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
13520      return ExternCPrev;
13521    }
13522  }
13523
13524  // Extension in C99.  Legal in C90, but warn about it.
13525  unsigned diag_id;
13526  if (II.getName().startswith("__builtin_"))
13527    diag_id = diag::warn_builtin_unknown;
13528  // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
13529  else if (getLangOpts().OpenCL)
13530    diag_id = diag::err_opencl_implicit_function_decl;
13531  else if (getLangOpts().C99)
13532    diag_id = diag::ext_implicit_function_decl;
13533  else
13534    diag_id = diag::warn_implicit_function_decl;
13535  Diag(Locdiag_id) << &II;
13536
13537  // If we found a prior declaration of this function, don't bother building
13538  // another one. We've already pushed that one into scope, so there's nothing
13539  // more to do.
13540  if (ExternCPrev)
13541    return ExternCPrev;
13542
13543  // Because typo correction is expensive, only do it if the implicit
13544  // function declaration is going to be treated as an error.
13545  if (Diags.getDiagnosticLevel(diag_idLoc) >= DiagnosticsEngine::Error) {
13546    TypoCorrection Corrected;
13547    DeclFilterCCC<FunctionDeclCCC{};
13548    if (S && (Corrected =
13549                  CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
13550                              S, nullptr, CCC, CTK_NonError)))
13551      diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
13552                   /*ErrorRecovery*/false);
13553  }
13554
13555  // Set a Declarator for the implicit definition: int foo();
13556  const char *Dummy;
13557  AttributeFactory attrFactory;
13558  DeclSpec DS(attrFactory);
13559  unsigned DiagID;
13560  bool Error = DS.SetTypeSpecType(DeclSpec::TST_intLocDummyDiagID,
13561                                  Context.getPrintingPolicy());
13562  (void)Error// Silence warning.
13563   (0) . __assert_fail ("!Error && \"Error setting up implicit decl!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 13563, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!Error && "Error setting up implicit decl!");
13564  SourceLocation NoLoc;
13565  Declarator D(DSDeclaratorContext::BlockContext);
13566  D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
13567                                             /*IsAmbiguous=*/false,
13568                                             /*LParenLoc=*/NoLoc,
13569                                             /*Params=*/nullptr,
13570                                             /*NumParams=*/0,
13571                                             /*EllipsisLoc=*/NoLoc,
13572                                             /*RParenLoc=*/NoLoc,
13573                                             /*RefQualifierIsLvalueRef=*/true,
13574                                             /*RefQualifierLoc=*/NoLoc,
13575                                             /*MutableLoc=*/NoLoc, EST_None,
13576                                             /*ESpecRange=*/SourceRange(),
13577                                             /*Exceptions=*/nullptr,
13578                                             /*ExceptionRanges=*/nullptr,
13579                                             /*NumExceptions=*/0,
13580                                             /*NoexceptExpr=*/nullptr,
13581                                             /*ExceptionSpecTokens=*/nullptr,
13582                                             /*DeclsInPrototype=*/None, Loc,
13583                                             Loc, D),
13584                std::move(DS.getAttributes()), SourceLocation());
13585  D.SetIdentifier(&IILoc);
13586
13587  // Insert this function into the enclosing block scope.
13588  FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScopeD));
13589  FD->setImplicit();
13590
13591  AddKnownFunctionAttributes(FD);
13592
13593  return FD;
13594}
13595
13596/// Adds any function attributes that we know a priori based on
13597/// the declaration of this function.
13598///
13599/// These attributes can apply both to implicitly-declared builtins
13600/// (like __builtin___printf_chk) or to library-declared functions
13601/// like NSLog or printf.
13602///
13603/// We need to check for duplicate attributes both here and where user-written
13604/// attributes are applied to declarations.
13605void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
13606  if (FD->isInvalidDecl())
13607    return;
13608
13609  // If this is a built-in function, map its builtin attributes to
13610  // actual attributes.
13611  if (unsigned BuiltinID = FD->getBuiltinID()) {
13612    // Handle printf-formatting attributes.
13613    unsigned FormatIdx;
13614    bool HasVAListArg;
13615    if (Context.BuiltinInfo.isPrintfLike(BuiltinIDFormatIdxHasVAListArg)) {
13616      if (!FD->hasAttr<FormatAttr>()) {
13617        const char *fmt = "printf";
13618        unsigned int NumParams = FD->getNumParams();
13619        if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
13620            FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
13621          fmt = "NSString";
13622        FD->addAttr(FormatAttr::CreateImplicit(Context,
13623                                               &Context.Idents.get(fmt),
13624                                               FormatIdx+1,
13625                                               HasVAListArg ? 0 : FormatIdx+2,
13626                                               FD->getLocation()));
13627      }
13628    }
13629    if (Context.BuiltinInfo.isScanfLike(BuiltinIDFormatIdx,
13630                                             HasVAListArg)) {
13631     if (!FD->hasAttr<FormatAttr>())
13632       FD->addAttr(FormatAttr::CreateImplicit(Context,
13633                                              &Context.Idents.get("scanf"),
13634                                              FormatIdx+1,
13635                                              HasVAListArg ? 0 : FormatIdx+2,
13636                                              FD->getLocation()));
13637    }
13638
13639    // Handle automatically recognized callbacks.
13640    SmallVector<int4Encoding;
13641    if (!FD->hasAttr<CallbackAttr>() &&
13642        Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
13643      FD->addAttr(CallbackAttr::CreateImplicit(
13644          Context, Encoding.data(), Encoding.size(), FD->getLocation()));
13645
13646    // Mark const if we don't care about errno and that is the only thing
13647    // preventing the function from being const. This allows IRgen to use LLVM
13648    // intrinsics for such functions.
13649    if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
13650        Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
13651      FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13652
13653    // We make "fma" on some platforms const because we know it does not set
13654    // errno in those environments even though it could set errno based on the
13655    // C standard.
13656    const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
13657    if ((Trip.isGNUEnvironment() || Trip.isAndroid() || Trip.isOSMSVCRT()) &&
13658        !FD->hasAttr<ConstAttr>()) {
13659      switch (BuiltinID) {
13660      case Builtin::BI__builtin_fma:
13661      case Builtin::BI__builtin_fmaf:
13662      case Builtin::BI__builtin_fmal:
13663      case Builtin::BIfma:
13664      case Builtin::BIfmaf:
13665      case Builtin::BIfmal:
13666        FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13667        break;
13668      default:
13669        break;
13670      }
13671    }
13672
13673    if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
13674        !FD->hasAttr<ReturnsTwiceAttr>())
13675      FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
13676                                         FD->getLocation()));
13677    if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
13678      FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13679    if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
13680      FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
13681    if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
13682      FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
13683    if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
13684        !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
13685      // Add the appropriate attribute, depending on the CUDA compilation mode
13686      // and which target the builtin belongs to. For example, during host
13687      // compilation, aux builtins are __device__, while the rest are __host__.
13688      if (getLangOpts().CUDAIsDevice !=
13689          Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
13690        FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
13691      else
13692        FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
13693    }
13694  }
13695
13696  // If C++ exceptions are enabled but we are told extern "C" functions cannot
13697  // throw, add an implicit nothrow attribute to any extern "C" function we come
13698  // across.
13699  if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
13700      FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
13701    const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
13702    if (!FPT || FPT->getExceptionSpecType() == EST_None)
13703      FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
13704  }
13705
13706  IdentifierInfo *Name = FD->getIdentifier();
13707  if (!Name)
13708    return;
13709  if ((!getLangOpts().CPlusPlus &&
13710       FD->getDeclContext()->isTranslationUnit()) ||
13711      (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
13712       cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
13713       LinkageSpecDecl::lang_c)) {
13714    // Okay: this could be a libc/libm/Objective-C function we know
13715    // about.
13716  } else
13717    return;
13718
13719  if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
13720    // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
13721    // target-specific builtins, perhaps?
13722    if (!FD->hasAttr<FormatAttr>())
13723      FD->addAttr(FormatAttr::CreateImplicit(Context,
13724                                             &Context.Idents.get("printf"), 2,
13725                                             Name->isStr("vasprintf") ? 0 : 3,
13726                                             FD->getLocation()));
13727  }
13728
13729  if (Name->isStr("__CFStringMakeConstantString")) {
13730    // We already have a __builtin___CFStringMakeConstantString,
13731    // but builds that use -fno-constant-cfstrings don't go through that.
13732    if (!FD->hasAttr<FormatArgAttr>())
13733      FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
13734                                                FD->getLocation()));
13735  }
13736}
13737
13738TypedefDecl *Sema::ParseTypedefDecl(Scope *SDeclarator &DQualType T,
13739                                    TypeSourceInfo *TInfo) {
13740   (0) . __assert_fail ("D.getIdentifier() && \"Wrong callback for declspec without declarator\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 13740, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
13741   (0) . __assert_fail ("!T.isNull() && \"GetTypeForDeclarator() returned null type\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 13741, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
13742
13743  if (!TInfo) {
13744     (0) . __assert_fail ("D.isInvalidType() && \"no declarator info for valid type\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 13744, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(D.isInvalidType() && "no declarator info for valid type");
13745    TInfo = Context.getTrivialTypeSourceInfo(T);
13746  }
13747
13748  // Scope manipulation handled by caller.
13749  TypedefDecl *NewTD =
13750      TypedefDecl::Create(ContextCurContextD.getBeginLoc(),
13751                          D.getIdentifierLoc(), D.getIdentifier(), TInfo);
13752
13753  // Bail out immediately if we have an invalid declaration.
13754  if (D.isInvalidType()) {
13755    NewTD->setInvalidDecl();
13756    return NewTD;
13757  }
13758
13759  if (D.getDeclSpec().isModulePrivateSpecified()) {
13760    if (CurContext->isFunctionOrMethod())
13761      Diag(NewTD->getLocation(), diag::err_module_private_local)
13762        << 2 << NewTD->getDeclName()
13763        << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
13764        << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
13765    else
13766      NewTD->setModulePrivate();
13767  }
13768
13769  // C++ [dcl.typedef]p8:
13770  //   If the typedef declaration defines an unnamed class (or
13771  //   enum), the first typedef-name declared by the declaration
13772  //   to be that class type (or enum type) is used to denote the
13773  //   class type (or enum type) for linkage purposes only.
13774  // We need to check whether the type was declared in the declaration.
13775  switch (D.getDeclSpec().getTypeSpecType()) {
13776  case TST_enum:
13777  case TST_struct:
13778  case TST_interface:
13779  case TST_union:
13780  case TST_class: {
13781    TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
13782    setTagNameForLinkagePurposes(tagFromDeclSpecNewTD);
13783    break;
13784  }
13785
13786  default:
13787    break;
13788  }
13789
13790  return NewTD;
13791}
13792
13793/// Check that this is a valid underlying type for an enum declaration.
13794bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
13795  SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
13796  QualType T = TI->getType();
13797
13798  if (T->isDependentType())
13799    return false;
13800
13801  if (const BuiltinType *BT = T->getAs<BuiltinType>())
13802    if (BT->isInteger())
13803      return false;
13804
13805  Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
13806  return true;
13807}
13808
13809/// Check whether this is a valid redeclaration of a previous enumeration.
13810/// \return true if the redeclaration was invalid.
13811bool Sema::CheckEnumRedeclaration(SourceLocation EnumLocbool IsScoped,
13812                                  QualType EnumUnderlyingTybool IsFixed,
13813                                  const EnumDecl *Prev) {
13814  if (IsScoped != Prev->isScoped()) {
13815    Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
13816      << Prev->isScoped();
13817    Diag(Prev->getLocation(), diag::note_previous_declaration);
13818    return true;
13819  }
13820
13821  if (IsFixed && Prev->isFixed()) {
13822    if (!EnumUnderlyingTy->isDependentType() &&
13823        !Prev->getIntegerType()->isDependentType() &&
13824        !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
13825                                        Prev->getIntegerType())) {
13826      // TODO: Highlight the underlying type of the redeclaration.
13827      Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
13828        << EnumUnderlyingTy << Prev->getIntegerType();
13829      Diag(Prev->getLocation(), diag::note_previous_declaration)
13830          << Prev->getIntegerTypeRange();
13831      return true;
13832    }
13833  } else if (IsFixed != Prev->isFixed()) {
13834    Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
13835      << Prev->isFixed();
13836    Diag(Prev->getLocation(), diag::note_previous_declaration);
13837    return true;
13838  }
13839
13840  return false;
13841}
13842
13843/// Get diagnostic %select index for tag kind for
13844/// redeclaration diagnostic message.
13845/// WARNING: Indexes apply to particular diagnostics only!
13846///
13847/// \returns diagnostic %select index.
13848static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
13849  switch (Tag) {
13850  case TTK_Structreturn 0;
13851  case TTK_Interfacereturn 1;
13852  case TTK_Class:  return 2;
13853  default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
13854  }
13855}
13856
13857/// Determine if tag kind is a class-key compatible with
13858/// class for redeclaration (class, struct, or __interface).
13859///
13860/// \returns true iff the tag kind is compatible.
13861static bool isClassCompatTagKind(TagTypeKind Tag)
13862{
13863  return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
13864}
13865
13866Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
13867                                             TagTypeKind TTK) {
13868  if (isa<TypedefDecl>(PrevDecl))
13869    return NTK_Typedef;
13870  else if (isa<TypeAliasDecl>(PrevDecl))
13871    return NTK_TypeAlias;
13872  else if (isa<ClassTemplateDecl>(PrevDecl))
13873    return NTK_Template;
13874  else if (isa<TypeAliasTemplateDecl>(PrevDecl))
13875    return NTK_TypeAliasTemplate;
13876  else if (isa<TemplateTemplateParmDecl>(PrevDecl))
13877    return NTK_TemplateTemplateArgument;
13878  switch (TTK) {
13879  case TTK_Struct:
13880  case TTK_Interface:
13881  case TTK_Class:
13882    return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
13883  case TTK_Union:
13884    return NTK_NonUnion;
13885  case TTK_Enum:
13886    return NTK_NonEnum;
13887  }
13888  llvm_unreachable("invalid TTK");
13889}
13890
13891/// Determine whether a tag with a given kind is acceptable
13892/// as a redeclaration of the given tag declaration.
13893///
13894/// \returns true if the new tag kind is acceptable, false otherwise.
13895bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
13896                                        TagTypeKind NewTagbool isDefinition,
13897                                        SourceLocation NewTagLoc,
13898                                        const IdentifierInfo *Name) {
13899  // C++ [dcl.type.elab]p3:
13900  //   The class-key or enum keyword present in the
13901  //   elaborated-type-specifier shall agree in kind with the
13902  //   declaration to which the name in the elaborated-type-specifier
13903  //   refers. This rule also applies to the form of
13904  //   elaborated-type-specifier that declares a class-name or
13905  //   friend class since it can be construed as referring to the
13906  //   definition of the class. Thus, in any
13907  //   elaborated-type-specifier, the enum keyword shall be used to
13908  //   refer to an enumeration (7.2), the union class-key shall be
13909  //   used to refer to a union (clause 9), and either the class or
13910  //   struct class-key shall be used to refer to a class (clause 9)
13911  //   declared using the class or struct class-key.
13912  TagTypeKind OldTag = Previous->getTagKind();
13913  if (OldTag != NewTag &&
13914      !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
13915    return false;
13916
13917  // Tags are compatible, but we might still want to warn on mismatched tags.
13918  // Non-class tags can't be mismatched at this point.
13919  if (!isClassCompatTagKind(NewTag))
13920    return true;
13921
13922  // Declarations for which -Wmismatched-tags is disabled are entirely ignored
13923  // by our warning analysis. We don't want to warn about mismatches with (eg)
13924  // declarations in system headers that are designed to be specialized, but if
13925  // a user asks us to warn, we should warn if their code contains mismatched
13926  // declarations.
13927  auto IsIgnoredLoc = [&](SourceLocation Loc) {
13928    return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
13929                                      Loc);
13930  };
13931  if (IsIgnoredLoc(NewTagLoc))
13932    return true;
13933
13934  auto IsIgnored = [&](const TagDecl *Tag) {
13935    return IsIgnoredLoc(Tag->getLocation());
13936  };
13937  while (IsIgnored(Previous)) {
13938    Previous = Previous->getPreviousDecl();
13939    if (!Previous)
13940      return true;
13941    OldTag = Previous->getTagKind();
13942  }
13943
13944  bool isTemplate = false;
13945  if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
13946    isTemplate = Record->getDescribedClassTemplate();
13947
13948  if (inTemplateInstantiation()) {
13949    if (OldTag != NewTag) {
13950      // In a template instantiation, do not offer fix-its for tag mismatches
13951      // since they usually mess up the template instead of fixing the problem.
13952      Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13953        << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13954        << getRedeclDiagFromTagKind(OldTag);
13955      // FIXME: Note previous location?
13956    }
13957    return true;
13958  }
13959
13960  if (isDefinition) {
13961    // On definitions, check all previous tags and issue a fix-it for each
13962    // one that doesn't match the current tag.
13963    if (Previous->getDefinition()) {
13964      // Don't suggest fix-its for redefinitions.
13965      return true;
13966    }
13967
13968    bool previousMismatch = false;
13969    for (const TagDecl *I : Previous->redecls()) {
13970      if (I->getTagKind() != NewTag) {
13971        // Ignore previous declarations for which the warning was disabled.
13972        if (IsIgnored(I))
13973          continue;
13974
13975        if (!previousMismatch) {
13976          previousMismatch = true;
13977          Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
13978            << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
13979            << getRedeclDiagFromTagKind(I->getTagKind());
13980        }
13981        Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
13982          << getRedeclDiagFromTagKind(NewTag)
13983          << FixItHint::CreateReplacement(I->getInnerLocStart(),
13984               TypeWithKeyword::getTagTypeKindName(NewTag));
13985      }
13986    }
13987    return true;
13988  }
13989
13990  // Identify the prevailing tag kind: this is the kind of the definition (if
13991  // there is a non-ignored definition), or otherwise the kind of the prior
13992  // (non-ignored) declaration.
13993  const TagDecl *PrevDef = Previous->getDefinition();
13994  if (PrevDef && IsIgnored(PrevDef))
13995    PrevDef = nullptr;
13996  const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
13997  if (Redecl->getTagKind() != NewTag) {
13998    Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
13999      << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
14000      << getRedeclDiagFromTagKind(OldTag);
14001    Diag(Redecl->getLocation(), diag::note_previous_use);
14002
14003    // If there is a previous definition, suggest a fix-it.
14004    if (PrevDef) {
14005      Diag(NewTagLoc, diag::note_struct_class_suggestion)
14006        << getRedeclDiagFromTagKind(Redecl->getTagKind())
14007        << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
14008             TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
14009    }
14010  }
14011
14012  return true;
14013}
14014
14015/// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
14016/// from an outer enclosing namespace or file scope inside a friend declaration.
14017/// This should provide the commented out code in the following snippet:
14018///   namespace N {
14019///     struct X;
14020///     namespace M {
14021///       struct Y { friend struct /*N::*/ X; };
14022///     }
14023///   }
14024static FixItHint createFriendTagNNSFixIt(Sema &SemaRefNamedDecl *NDScope *S,
14025                                         SourceLocation NameLoc) {
14026  // While the decl is in a namespace, do repeated lookup of that name and see
14027  // if we get the same namespace back.  If we do not, continue until
14028  // translation unit scope, at which point we have a fully qualified NNS.
14029  SmallVector<IdentifierInfo *, 4Namespaces;
14030  DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14031  for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
14032    // This tag should be declared in a namespace, which can only be enclosed by
14033    // other namespaces.  Bail if there's an anonymous namespace in the chain.
14034    NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
14035    if (!Namespace || Namespace->isAnonymousNamespace())
14036      return FixItHint();
14037    IdentifierInfo *II = Namespace->getIdentifier();
14038    Namespaces.push_back(II);
14039    NamedDecl *Lookup = SemaRef.LookupSingleName(
14040        SIINameLocSema::LookupNestedNameSpecifierName);
14041    if (Lookup == Namespace)
14042      break;
14043  }
14044
14045  // Once we have all the namespaces, reverse them to go outermost first, and
14046  // build an NNS.
14047  SmallString<64Insertion;
14048  llvm::raw_svector_ostream OS(Insertion);
14049  if (DC->isTranslationUnit())
14050    OS << "::";
14051  std::reverse(Namespaces.begin(), Namespaces.end());
14052  for (auto *II : Namespaces)
14053    OS << II->getName() << "::";
14054  return FixItHint::CreateInsertion(NameLoc, Insertion);
14055}
14056
14057/// Determine whether a tag originally declared in context \p OldDC can
14058/// be redeclared with an unqualified name in \p NewDC (assuming name lookup
14059/// found a declaration in \p OldDC as a previous decl, perhaps through a
14060/// using-declaration).
14061static bool isAcceptableTagRedeclContext(Sema &SDeclContext *OldDC,
14062                                         DeclContext *NewDC) {
14063  OldDC = OldDC->getRedeclContext();
14064  NewDC = NewDC->getRedeclContext();
14065
14066  if (OldDC->Equals(NewDC))
14067    return true;
14068
14069  // In MSVC mode, we allow a redeclaration if the contexts are related (either
14070  // encloses the other).
14071  if (S.getLangOpts().MSVCCompat &&
14072      (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
14073    return true;
14074
14075  return false;
14076}
14077
14078/// This is invoked when we see 'struct foo' or 'struct {'.  In the
14079/// former case, Name will be non-null.  In the later case, Name will be null.
14080/// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
14081/// reference/declaration/definition of a tag.
14082///
14083/// \param IsTypeSpecifier \c true if this is a type-specifier (or
14084/// trailing-type-specifier) other than one in an alias-declaration.
14085///
14086/// \param SkipBody If non-null, will be set to indicate if the caller should
14087/// skip the definition of this tag and treat it as if it were a declaration.
14088Decl *Sema::ActOnTag(Scope *Sunsigned TagSpecTagUseKind TUK,
14089                     SourceLocation KWLocCXXScopeSpec &SS,
14090                     IdentifierInfo *NameSourceLocation NameLoc,
14091                     const ParsedAttributesView &AttrsAccessSpecifier AS,
14092                     SourceLocation ModulePrivateLoc,
14093                     MultiTemplateParamsArg TemplateParameterLists,
14094                     bool &OwnedDeclbool &IsDependent,
14095                     SourceLocation ScopedEnumKWLoc,
14096                     bool ScopedEnumUsesClassTagTypeResult UnderlyingType,
14097                     bool IsTypeSpecifierbool IsTemplateParamOrArg,
14098                     SkipBodyInfo *SkipBody) {
14099  // If this is not a definition, it must have a name.
14100  IdentifierInfo *OrigName = Name;
14101   (0) . __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 14102, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert((Name != nullptr || TUK == TUK_Definition) &&
14102 (0) . __assert_fail ("(Name != nullptr || TUK == TUK_Definition) && \"Nameless record must be a definition!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 14102, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "Nameless record must be a definition!");
14103  assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
14104
14105  OwnedDecl = false;
14106  TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
14107  bool ScopedEnum = ScopedEnumKWLoc.isValid();
14108
14109  // FIXME: Check member specializations more carefully.
14110  bool isMemberSpecialization = false;
14111  bool Invalid = false;
14112
14113  // We only need to do this matching if we have template parameters
14114  // or a scope specifier, which also conveniently avoids this work
14115  // for non-C++ cases.
14116  if (TemplateParameterLists.size() > 0 ||
14117      (SS.isNotEmpty() && TUK != TUK_Reference)) {
14118    if (TemplateParameterList *TemplateParams =
14119            MatchTemplateParametersToScopeSpecifier(
14120                KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
14121                TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
14122      if (Kind == TTK_Enum) {
14123        Diag(KWLoc, diag::err_enum_template);
14124        return nullptr;
14125      }
14126
14127      if (TemplateParams->size() > 0) {
14128        // This is a declaration or definition of a class template (which may
14129        // be a member of another template).
14130
14131        if (Invalid)
14132          return nullptr;
14133
14134        OwnedDecl = false;
14135        DeclResult Result = CheckClassTemplate(
14136            S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
14137            AS, ModulePrivateLoc,
14138            /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
14139            TemplateParameterLists.data(), SkipBody);
14140        return Result.get();
14141      } else {
14142        // The "template<>" header is extraneous.
14143        Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
14144          << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
14145        isMemberSpecialization = true;
14146      }
14147    }
14148  }
14149
14150  // Figure out the underlying type if this a enum declaration. We need to do
14151  // this early, because it's needed to detect if this is an incompatible
14152  // redeclaration.
14153  llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
14154  bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
14155
14156  if (Kind == TTK_Enum) {
14157    if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
14158      // No underlying type explicitly specified, or we failed to parse the
14159      // type, default to int.
14160      EnumUnderlying = Context.IntTy.getTypePtr();
14161    } else if (UnderlyingType.get()) {
14162      // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
14163      // integral type; any cv-qualification is ignored.
14164      TypeSourceInfo *TI = nullptr;
14165      GetTypeFromParser(UnderlyingType.get(), &TI);
14166      EnumUnderlying = TI;
14167
14168      if (CheckEnumUnderlyingType(TI))
14169        // Recover by falling back to int.
14170        EnumUnderlying = Context.IntTy.getTypePtr();
14171
14172      if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
14173                                          UPPC_FixedUnderlyingType))
14174        EnumUnderlying = Context.IntTy.getTypePtr();
14175
14176    } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14177      // For MSVC ABI compatibility, unfixed enums must use an underlying type
14178      // of 'int'. However, if this is an unfixed forward declaration, don't set
14179      // the underlying type unless the user enables -fms-compatibility. This
14180      // makes unfixed forward declared enums incomplete and is more conforming.
14181      if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
14182        EnumUnderlying = Context.IntTy.getTypePtr();
14183    }
14184  }
14185
14186  DeclContext *SearchDC = CurContext;
14187  DeclContext *DC = CurContext;
14188  bool isStdBadAlloc = false;
14189  bool isStdAlignValT = false;
14190
14191  RedeclarationKind Redecl = forRedeclarationInCurContext();
14192  if (TUK == TUK_Friend || TUK == TUK_Reference)
14193    Redecl = NotForRedeclaration;
14194
14195  /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
14196  /// implemented asks for structural equivalence checking, the returned decl
14197  /// here is passed back to the parser, allowing the tag body to be parsed.
14198  auto createTagFromNewDecl = [&]() -> TagDecl * {
14199     (0) . __assert_fail ("!getLangOpts().CPlusPlus && \"not meant for C++ usage\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 14199, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
14200    // If there is an identifier, use the location of the identifier as the
14201    // location of the decl, otherwise use the location of the struct/union
14202    // keyword.
14203    SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14204    TagDecl *New = nullptr;
14205
14206    if (Kind == TTK_Enum) {
14207      New = EnumDecl::Create(ContextSearchDCKWLocLocNamenullptr,
14208                             ScopedEnumScopedEnumUsesClassTagIsFixed);
14209      // If this is an undefined enum, bail.
14210      if (TUK != TUK_Definition && !Invalid)
14211        return nullptr;
14212      if (EnumUnderlying) {
14213        EnumDecl *ED = cast<EnumDecl>(New);
14214        if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
14215          ED->setIntegerTypeSourceInfo(TI);
14216        else
14217          ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
14218        ED->setPromotionType(ED->getIntegerType());
14219      }
14220    } else { // struct/union
14221      New = RecordDecl::Create(ContextKindSearchDCKWLocLocName,
14222                               nullptr);
14223    }
14224
14225    if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14226      // Add alignment attributes if necessary; these attributes are checked
14227      // when the ASTContext lays out the structure.
14228      //
14229      // It is important for implementing the correct semantics that this
14230      // happen here (in ActOnTag). The #pragma pack stack is
14231      // maintained as a result of parser callbacks which can occur at
14232      // many points during the parsing of a struct declaration (because
14233      // the #pragma tokens are effectively skipped over during the
14234      // parsing of the struct).
14235      if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14236        AddAlignmentAttributesForRecord(RD);
14237        AddMsStructLayoutForRecord(RD);
14238      }
14239    }
14240    New->setLexicalDeclContext(CurContext);
14241    return New;
14242  };
14243
14244  LookupResult Previous(*thisNameNameLocLookupTagNameRedecl);
14245  if (Name && SS.isNotEmpty()) {
14246    // We have a nested-name tag ('struct foo::bar').
14247
14248    // Check for invalid 'foo::'.
14249    if (SS.isInvalid()) {
14250      Name = nullptr;
14251      goto CreateNewDecl;
14252    }
14253
14254    // If this is a friend or a reference to a class in a dependent
14255    // context, don't try to make a decl for it.
14256    if (TUK == TUK_Friend || TUK == TUK_Reference) {
14257      DC = computeDeclContext(SSfalse);
14258      if (!DC) {
14259        IsDependent = true;
14260        return nullptr;
14261      }
14262    } else {
14263      DC = computeDeclContext(SStrue);
14264      if (!DC) {
14265        Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
14266          << SS.getRange();
14267        return nullptr;
14268      }
14269    }
14270
14271    if (RequireCompleteDeclContext(SSDC))
14272      return nullptr;
14273
14274    SearchDC = DC;
14275    // Look-up name inside 'foo::'.
14276    LookupQualifiedName(PreviousDC);
14277
14278    if (Previous.isAmbiguous())
14279      return nullptr;
14280
14281    if (Previous.empty()) {
14282      // Name lookup did not find anything. However, if the
14283      // nested-name-specifier refers to the current instantiation,
14284      // and that current instantiation has any dependent base
14285      // classes, we might find something at instantiation time: treat
14286      // this as a dependent elaborated-type-specifier.
14287      // But this only makes any sense for reference-like lookups.
14288      if (Previous.wasNotFoundInCurrentInstantiation() &&
14289          (TUK == TUK_Reference || TUK == TUK_Friend)) {
14290        IsDependent = true;
14291        return nullptr;
14292      }
14293
14294      // A tag 'foo::bar' must already exist.
14295      Diag(NameLoc, diag::err_not_tag_in_scope)
14296        << Kind << Name << DC << SS.getRange();
14297      Name = nullptr;
14298      Invalid = true;
14299      goto CreateNewDecl;
14300    }
14301  } else if (Name) {
14302    // C++14 [class.mem]p14:
14303    //   If T is the name of a class, then each of the following shall have a
14304    //   name different from T:
14305    //    -- every member of class T that is itself a type
14306    if (TUK != TUK_Reference && TUK != TUK_Friend &&
14307        DiagnoseClassNameShadow(SearchDCDeclarationNameInfo(NameNameLoc)))
14308      return nullptr;
14309
14310    // If this is a named struct, check to see if there was a previous forward
14311    // declaration or definition.
14312    // FIXME: We're looking into outer scopes here, even when we
14313    // shouldn't be. Doing so can result in ambiguities that we
14314    // shouldn't be diagnosing.
14315    LookupName(PreviousS);
14316
14317    // When declaring or defining a tag, ignore ambiguities introduced
14318    // by types using'ed into this scope.
14319    if (Previous.isAmbiguous() &&
14320        (TUK == TUK_Definition || TUK == TUK_Declaration)) {
14321      LookupResult::Filter F = Previous.makeFilter();
14322      while (F.hasNext()) {
14323        NamedDecl *ND = F.next();
14324        if (!ND->getDeclContext()->getRedeclContext()->Equals(
14325                SearchDC->getRedeclContext()))
14326          F.erase();
14327      }
14328      F.done();
14329    }
14330
14331    // C++11 [namespace.memdef]p3:
14332    //   If the name in a friend declaration is neither qualified nor
14333    //   a template-id and the declaration is a function or an
14334    //   elaborated-type-specifier, the lookup to determine whether
14335    //   the entity has been previously declared shall not consider
14336    //   any scopes outside the innermost enclosing namespace.
14337    //
14338    // MSVC doesn't implement the above rule for types, so a friend tag
14339    // declaration may be a redeclaration of a type declared in an enclosing
14340    // scope.  They do implement this rule for friend functions.
14341    //
14342    // Does it matter that this should be by scope instead of by
14343    // semantic context?
14344    if (!Previous.empty() && TUK == TUK_Friend) {
14345      DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
14346      LookupResult::Filter F = Previous.makeFilter();
14347      bool FriendSawTagOutsideEnclosingNamespace = false;
14348      while (F.hasNext()) {
14349        NamedDecl *ND = F.next();
14350        DeclContext *DC = ND->getDeclContext()->getRedeclContext();
14351        if (DC->isFileContext() &&
14352            !EnclosingNS->Encloses(ND->getDeclContext())) {
14353          if (getLangOpts().MSVCCompat)
14354            FriendSawTagOutsideEnclosingNamespace = true;
14355          else
14356            F.erase();
14357        }
14358      }
14359      F.done();
14360
14361      // Diagnose this MSVC extension in the easy case where lookup would have
14362      // unambiguously found something outside the enclosing namespace.
14363      if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
14364        NamedDecl *ND = Previous.getFoundDecl();
14365        Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
14366            << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
14367      }
14368    }
14369
14370    // Note:  there used to be some attempt at recovery here.
14371    if (Previous.isAmbiguous())
14372      return nullptr;
14373
14374    if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
14375      // FIXME: This makes sure that we ignore the contexts associated
14376      // with C structs, unions, and enums when looking for a matching
14377      // tag declaration or definition. See the similar lookup tweak
14378      // in Sema::LookupName; is there a better way to deal with this?
14379      while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
14380        SearchDC = SearchDC->getParent();
14381    }
14382  }
14383
14384  if (Previous.isSingleResult() &&
14385      Previous.getFoundDecl()->isTemplateParameter()) {
14386    // Maybe we will complain about the shadowed template parameter.
14387    DiagnoseTemplateParameterShadow(NameLocPrevious.getFoundDecl());
14388    // Just pretend that we didn't see the previous declaration.
14389    Previous.clear();
14390  }
14391
14392  if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
14393      DC->Equals(getStdNamespace())) {
14394    if (Name->isStr("bad_alloc")) {
14395      // This is a declaration of or a reference to "std::bad_alloc".
14396      isStdBadAlloc = true;
14397
14398      // If std::bad_alloc has been implicitly declared (but made invisible to
14399      // name lookup), fill in this implicit declaration as the previous
14400      // declaration, so that the declarations get chained appropriately.
14401      if (Previous.empty() && StdBadAlloc)
14402        Previous.addDecl(getStdBadAlloc());
14403    } else if (Name->isStr("align_val_t")) {
14404      isStdAlignValT = true;
14405      if (Previous.empty() && StdAlignValT)
14406        Previous.addDecl(getStdAlignValT());
14407    }
14408  }
14409
14410  // If we didn't find a previous declaration, and this is a reference
14411  // (or friend reference), move to the correct scope.  In C++, we
14412  // also need to do a redeclaration lookup there, just in case
14413  // there's a shadow friend decl.
14414  if (Name && Previous.empty() &&
14415      (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
14416    if (Invalidgoto CreateNewDecl;
14417    assert(SS.isEmpty());
14418
14419    if (TUK == TUK_Reference || IsTemplateParamOrArg) {
14420      // C++ [basic.scope.pdecl]p5:
14421      //   -- for an elaborated-type-specifier of the form
14422      //
14423      //          class-key identifier
14424      //
14425      //      if the elaborated-type-specifier is used in the
14426      //      decl-specifier-seq or parameter-declaration-clause of a
14427      //      function defined in namespace scope, the identifier is
14428      //      declared as a class-name in the namespace that contains
14429      //      the declaration; otherwise, except as a friend
14430      //      declaration, the identifier is declared in the smallest
14431      //      non-class, non-function-prototype scope that contains the
14432      //      declaration.
14433      //
14434      // C99 6.7.2.3p8 has a similar (but not identical!) provision for
14435      // C structs and unions.
14436      //
14437      // It is an error in C++ to declare (rather than define) an enum
14438      // type, including via an elaborated type specifier.  We'll
14439      // diagnose that later; for now, declare the enum in the same
14440      // scope as we would have picked for any other tag type.
14441      //
14442      // GNU C also supports this behavior as part of its incomplete
14443      // enum types extension, while GNU C++ does not.
14444      //
14445      // Find the context where we'll be declaring the tag.
14446      // FIXME: We would like to maintain the current DeclContext as the
14447      // lexical context,
14448      SearchDC = getTagInjectionContext(SearchDC);
14449
14450      // Find the scope where we'll be declaring the tag.
14451      S = getTagInjectionScope(SgetLangOpts());
14452    } else {
14453      assert(TUK == TUK_Friend);
14454      // C++ [namespace.memdef]p3:
14455      //   If a friend declaration in a non-local class first declares a
14456      //   class or function, the friend class or function is a member of
14457      //   the innermost enclosing namespace.
14458      SearchDC = SearchDC->getEnclosingNamespaceContext();
14459    }
14460
14461    // In C++, we need to do a redeclaration lookup to properly
14462    // diagnose some problems.
14463    // FIXME: redeclaration lookup is also used (with and without C++) to find a
14464    // hidden declaration so that we don't get ambiguity errors when using a
14465    // type declared by an elaborated-type-specifier.  In C that is not correct
14466    // and we should instead merge compatible types found by lookup.
14467    if (getLangOpts().CPlusPlus) {
14468      Previous.setRedeclarationKind(forRedeclarationInCurContext());
14469      LookupQualifiedName(PreviousSearchDC);
14470    } else {
14471      Previous.setRedeclarationKind(forRedeclarationInCurContext());
14472      LookupName(PreviousS);
14473    }
14474  }
14475
14476  // If we have a known previous declaration to use, then use it.
14477  if (Previous.empty() && SkipBody && SkipBody->Previous)
14478    Previous.addDecl(SkipBody->Previous);
14479
14480  if (!Previous.empty()) {
14481    NamedDecl *PrevDecl = Previous.getFoundDecl();
14482    NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
14483
14484    // It's okay to have a tag decl in the same scope as a typedef
14485    // which hides a tag decl in the same scope.  Finding this
14486    // insanity with a redeclaration lookup can only actually happen
14487    // in C++.
14488    //
14489    // This is also okay for elaborated-type-specifiers, which is
14490    // technically forbidden by the current standard but which is
14491    // okay according to the likely resolution of an open issue;
14492    // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
14493    if (getLangOpts().CPlusPlus) {
14494      if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14495        if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
14496          TagDecl *Tag = TT->getDecl();
14497          if (Tag->getDeclName() == Name &&
14498              Tag->getDeclContext()->getRedeclContext()
14499                          ->Equals(TD->getDeclContext()->getRedeclContext())) {
14500            PrevDecl = Tag;
14501            Previous.clear();
14502            Previous.addDecl(Tag);
14503            Previous.resolveKind();
14504          }
14505        }
14506      }
14507    }
14508
14509    // If this is a redeclaration of a using shadow declaration, it must
14510    // declare a tag in the same context. In MSVC mode, we allow a
14511    // redefinition if either context is within the other.
14512    if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
14513      auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
14514      if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
14515          isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
14516          !(OldTag && isAcceptableTagRedeclContext(
14517                          *this, OldTag->getDeclContext(), SearchDC))) {
14518        Diag(KWLoc, diag::err_using_decl_conflict_reverse);
14519        Diag(Shadow->getTargetDecl()->getLocation(),
14520             diag::note_using_decl_target);
14521        Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
14522            << 0;
14523        // Recover by ignoring the old declaration.
14524        Previous.clear();
14525        goto CreateNewDecl;
14526      }
14527    }
14528
14529    if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
14530      // If this is a use of a previous tag, or if the tag is already declared
14531      // in the same scope (so that the definition/declaration completes or
14532      // rementions the tag), reuse the decl.
14533      if (TUK == TUK_Reference || TUK == TUK_Friend ||
14534          isDeclInScope(DirectPrevDeclSearchDCS,
14535                        SS.isNotEmpty() || isMemberSpecialization)) {
14536        // Make sure that this wasn't declared as an enum and now used as a
14537        // struct or something similar.
14538        if (!isAcceptableTagRedeclaration(PrevTagDeclKind,
14539                                          TUK == TUK_DefinitionKWLoc,
14540                                          Name)) {
14541          bool SafeToContinue
14542            = (PrevTagDecl->getTagKind() != TTK_Enum &&
14543               Kind != TTK_Enum);
14544          if (SafeToContinue)
14545            Diag(KWLoc, diag::err_use_with_wrong_tag)
14546              << Name
14547              << FixItHint::CreateReplacement(SourceRange(KWLoc),
14548                                              PrevTagDecl->getKindName());
14549          else
14550            Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
14551          Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
14552
14553          if (SafeToContinue)
14554            Kind = PrevTagDecl->getTagKind();
14555          else {
14556            // Recover by making this an anonymous redefinition.
14557            Name = nullptr;
14558            Previous.clear();
14559            Invalid = true;
14560          }
14561        }
14562
14563        if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
14564          const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
14565
14566          // If this is an elaborated-type-specifier for a scoped enumeration,
14567          // the 'class' keyword is not necessary and not permitted.
14568          if (TUK == TUK_Reference || TUK == TUK_Friend) {
14569            if (ScopedEnum)
14570              Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
14571                << PrevEnum->isScoped()
14572                << FixItHint::CreateRemoval(ScopedEnumKWLoc);
14573            return PrevTagDecl;
14574          }
14575
14576          QualType EnumUnderlyingTy;
14577          if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14578            EnumUnderlyingTy = TI->getType().getUnqualifiedType();
14579          else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
14580            EnumUnderlyingTy = QualType(T0);
14581
14582          // All conflicts with previous declarations are recovered by
14583          // returning the previous declaration, unless this is a definition,
14584          // in which case we want the caller to bail out.
14585          if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
14586                                     ScopedEnum, EnumUnderlyingTy,
14587                                     IsFixed, PrevEnum))
14588            return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
14589        }
14590
14591        // C++11 [class.mem]p1:
14592        //   A member shall not be declared twice in the member-specification,
14593        //   except that a nested class or member class template can be declared
14594        //   and then later defined.
14595        if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
14596            S->isDeclScope(PrevDecl)) {
14597          Diag(NameLoc, diag::ext_member_redeclared);
14598          Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
14599        }
14600
14601        if (!Invalid) {
14602          // If this is a use, just return the declaration we found, unless
14603          // we have attributes.
14604          if (TUK == TUK_Reference || TUK == TUK_Friend) {
14605            if (!Attrs.empty()) {
14606              // FIXME: Diagnose these attributes. For now, we create a new
14607              // declaration to hold them.
14608            } else if (TUK == TUK_Reference &&
14609                       (PrevTagDecl->getFriendObjectKind() ==
14610                            Decl::FOK_Undeclared ||
14611                        PrevDecl->getOwningModule() != getCurrentModule()) &&
14612                       SS.isEmpty()) {
14613              // This declaration is a reference to an existing entity, but
14614              // has different visibility from that entity: it either makes
14615              // a friend visible or it makes a type visible in a new module.
14616              // In either case, create a new declaration. We only do this if
14617              // the declaration would have meant the same thing if no prior
14618              // declaration were found, that is, if it was found in the same
14619              // scope where we would have injected a declaration.
14620              if (!getTagInjectionContext(CurContext)->getRedeclContext()
14621                       ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
14622                return PrevTagDecl;
14623              // This is in the injected scope, create a new declaration in
14624              // that scope.
14625              S = getTagInjectionScope(SgetLangOpts());
14626            } else {
14627              return PrevTagDecl;
14628            }
14629          }
14630
14631          // Diagnose attempts to redefine a tag.
14632          if (TUK == TUK_Definition) {
14633            if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
14634              // If we're defining a specialization and the previous definition
14635              // is from an implicit instantiation, don't emit an error
14636              // here; we'll catch this in the general case below.
14637              bool IsExplicitSpecializationAfterInstantiation = false;
14638              if (isMemberSpecialization) {
14639                if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
14640                  IsExplicitSpecializationAfterInstantiation =
14641                    RD->getTemplateSpecializationKind() !=
14642                    TSK_ExplicitSpecialization;
14643                else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
14644                  IsExplicitSpecializationAfterInstantiation =
14645                    ED->getTemplateSpecializationKind() !=
14646                    TSK_ExplicitSpecialization;
14647              }
14648
14649              // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
14650              // not keep more that one definition around (merge them). However,
14651              // ensure the decl passes the structural compatibility check in
14652              // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
14653              NamedDecl *Hidden = nullptr;
14654              if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
14655                // There is a definition of this tag, but it is not visible. We
14656                // explicitly make use of C++'s one definition rule here, and
14657                // assume that this definition is identical to the hidden one
14658                // we already have. Make the existing definition visible and
14659                // use it in place of this one.
14660                if (!getLangOpts().CPlusPlus) {
14661                  // Postpone making the old definition visible until after we
14662                  // complete parsing the new one and do the structural
14663                  // comparison.
14664                  SkipBody->CheckSameAsPrevious = true;
14665                  SkipBody->New = createTagFromNewDecl();
14666                  SkipBody->Previous = Def;
14667                  return Def;
14668                } else {
14669                  SkipBody->ShouldSkip = true;
14670                  SkipBody->Previous = Def;
14671                  makeMergedDefinitionVisible(Hidden);
14672                  // Carry on and handle it like a normal definition. We'll
14673                  // skip starting the definitiion later.
14674                }
14675              } else if (!IsExplicitSpecializationAfterInstantiation) {
14676                // A redeclaration in function prototype scope in C isn't
14677                // visible elsewhere, so merely issue a warning.
14678                if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
14679                  Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
14680                else
14681                  Diag(NameLoc, diag::err_redefinition) << Name;
14682                notePreviousDefinition(Def,
14683                                       NameLoc.isValid() ? NameLoc : KWLoc);
14684                // If this is a redefinition, recover by making this
14685                // struct be anonymous, which will make any later
14686                // references get the previous definition.
14687                Name = nullptr;
14688                Previous.clear();
14689                Invalid = true;
14690              }
14691            } else {
14692              // If the type is currently being defined, complain
14693              // about a nested redefinition.
14694              auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
14695              if (TD->isBeingDefined()) {
14696                Diag(NameLoc, diag::err_nested_redefinition) << Name;
14697                Diag(PrevTagDecl->getLocation(),
14698                     diag::note_previous_definition);
14699                Name = nullptr;
14700                Previous.clear();
14701                Invalid = true;
14702              }
14703            }
14704
14705            // Okay, this is definition of a previously declared or referenced
14706            // tag. We're going to create a new Decl for it.
14707          }
14708
14709          // Okay, we're going to make a redeclaration.  If this is some kind
14710          // of reference, make sure we build the redeclaration in the same DC
14711          // as the original, and ignore the current access specifier.
14712          if (TUK == TUK_Friend || TUK == TUK_Reference) {
14713            SearchDC = PrevTagDecl->getDeclContext();
14714            AS = AS_none;
14715          }
14716        }
14717        // If we get here we have (another) forward declaration or we
14718        // have a definition.  Just create a new decl.
14719
14720      } else {
14721        // If we get here, this is a definition of a new tag type in a nested
14722        // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
14723        // new decl/type.  We set PrevDecl to NULL so that the entities
14724        // have distinct types.
14725        Previous.clear();
14726      }
14727      // If we get here, we're going to create a new Decl. If PrevDecl
14728      // is non-NULL, it's a definition of the tag declared by
14729      // PrevDecl. If it's NULL, we have a new definition.
14730
14731    // Otherwise, PrevDecl is not a tag, but was found with tag
14732    // lookup.  This is only actually possible in C++, where a few
14733    // things like templates still live in the tag namespace.
14734    } else {
14735      // Use a better diagnostic if an elaborated-type-specifier
14736      // found the wrong kind of type on the first
14737      // (non-redeclaration) lookup.
14738      if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
14739          !Previous.isForRedeclaration()) {
14740        NonTagKind NTK = getNonTagTypeDeclKind(PrevDeclKind);
14741        Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
14742                                                       << Kind;
14743        Diag(PrevDecl->getLocation(), diag::note_declared_at);
14744        Invalid = true;
14745
14746      // Otherwise, only diagnose if the declaration is in scope.
14747      } else if (!isDeclInScope(DirectPrevDeclSearchDCS,
14748                                SS.isNotEmpty() || isMemberSpecialization)) {
14749        // do nothing
14750
14751      // Diagnose implicit declarations introduced by elaborated types.
14752      } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
14753        NonTagKind NTK = getNonTagTypeDeclKind(PrevDeclKind);
14754        Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
14755        Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14756        Invalid = true;
14757
14758      // Otherwise it's a declaration.  Call out a particularly common
14759      // case here.
14760      } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
14761        unsigned Kind = 0;
14762        if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
14763        Diag(NameLoc, diag::err_tag_definition_of_typedef)
14764          << Name << Kind << TND->getUnderlyingType();
14765        Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
14766        Invalid = true;
14767
14768      // Otherwise, diagnose.
14769      } else {
14770        // The tag name clashes with something else in the target scope,
14771        // issue an error and recover by making this tag be anonymous.
14772        Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
14773        notePreviousDefinition(PrevDeclNameLoc);
14774        Name = nullptr;
14775        Invalid = true;
14776      }
14777
14778      // The existing declaration isn't relevant to us; we're in a
14779      // new scope, so clear out the previous declaration.
14780      Previous.clear();
14781    }
14782  }
14783
14784CreateNewDecl:
14785
14786  TagDecl *PrevDecl = nullptr;
14787  if (Previous.isSingleResult())
14788    PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
14789
14790  // If there is an identifier, use the location of the identifier as the
14791  // location of the decl, otherwise use the location of the struct/union
14792  // keyword.
14793  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
14794
14795  // Otherwise, create a new declaration. If there is a previous
14796  // declaration of the same entity, the two will be linked via
14797  // PrevDecl.
14798  TagDecl *New;
14799
14800  if (Kind == TTK_Enum) {
14801    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14802    // enum X { A, B, C } D;    D should chain to X.
14803    New = EnumDecl::Create(ContextSearchDCKWLocLocName,
14804                           cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
14805                           ScopedEnumUsesClassTagIsFixed);
14806
14807    if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
14808      StdAlignValT = cast<EnumDecl>(New);
14809
14810    // If this is an undefined enum, warn.
14811    if (TUK != TUK_Definition && !Invalid) {
14812      TagDecl *Def;
14813      if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
14814        // C++0x: 7.2p2: opaque-enum-declaration.
14815        // Conflicts are diagnosed above. Do nothing.
14816      }
14817      else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
14818        Diag(Loc, diag::ext_forward_ref_enum_def)
14819          << New;
14820        Diag(Def->getLocation(), diag::note_previous_definition);
14821      } else {
14822        unsigned DiagID = diag::ext_forward_ref_enum;
14823        if (getLangOpts().MSVCCompat)
14824          DiagID = diag::ext_ms_forward_ref_enum;
14825        else if (getLangOpts().CPlusPlus)
14826          DiagID = diag::err_forward_ref_enum;
14827        Diag(LocDiagID);
14828      }
14829    }
14830
14831    if (EnumUnderlying) {
14832      EnumDecl *ED = cast<EnumDecl>(New);
14833      if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
14834        ED->setIntegerTypeSourceInfo(TI);
14835      else
14836        ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
14837      ED->setPromotionType(ED->getIntegerType());
14838       (0) . __assert_fail ("ED->isComplete() && \"enum with type should be complete\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 14838, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(ED->isComplete() && "enum with type should be complete");
14839    }
14840  } else {
14841    // struct/union/class
14842
14843    // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
14844    // struct X { int A; } D;    D should chain to X.
14845    if (getLangOpts().CPlusPlus) {
14846      // FIXME: Look for a way to use RecordDecl for simple structs.
14847      New = CXXRecordDecl::Create(ContextKindSearchDCKWLocLocName,
14848                                  cast_or_null<CXXRecordDecl>(PrevDecl));
14849
14850      if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
14851        StdBadAlloc = cast<CXXRecordDecl>(New);
14852    } else
14853      New = RecordDecl::Create(ContextKindSearchDCKWLocLocName,
14854                               cast_or_null<RecordDecl>(PrevDecl));
14855  }
14856
14857  // C++11 [dcl.type]p3:
14858  //   A type-specifier-seq shall not define a class or enumeration [...].
14859  if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
14860      TUK == TUK_Definition) {
14861    Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
14862      << Context.getTagDeclType(New);
14863    Invalid = true;
14864  }
14865
14866  if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
14867      DC->getDeclKind() == Decl::Enum) {
14868    Diag(New->getLocation(), diag::err_type_defined_in_enum)
14869      << Context.getTagDeclType(New);
14870    Invalid = true;
14871  }
14872
14873  // Maybe add qualifier info.
14874  if (SS.isNotEmpty()) {
14875    if (SS.isSet()) {
14876      // If this is either a declaration or a definition, check the
14877      // nested-name-specifier against the current context.
14878      if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
14879          diagnoseQualifiedDeclaration(SSDCOrigNameLoc,
14880                                       isMemberSpecialization))
14881        Invalid = true;
14882
14883      New->setQualifierInfo(SS.getWithLocInContext(Context));
14884      if (TemplateParameterLists.size() > 0) {
14885        New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
14886      }
14887    }
14888    else
14889      Invalid = true;
14890  }
14891
14892  if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
14893    // Add alignment attributes if necessary; these attributes are checked when
14894    // the ASTContext lays out the structure.
14895    //
14896    // It is important for implementing the correct semantics that this
14897    // happen here (in ActOnTag). The #pragma pack stack is
14898    // maintained as a result of parser callbacks which can occur at
14899    // many points during the parsing of a struct declaration (because
14900    // the #pragma tokens are effectively skipped over during the
14901    // parsing of the struct).
14902    if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
14903      AddAlignmentAttributesForRecord(RD);
14904      AddMsStructLayoutForRecord(RD);
14905    }
14906  }
14907
14908  if (ModulePrivateLoc.isValid()) {
14909    if (isMemberSpecialization)
14910      Diag(New->getLocation(), diag::err_module_private_specialization)
14911        << 2
14912        << FixItHint::CreateRemoval(ModulePrivateLoc);
14913    // __module_private__ does not apply to local classes. However, we only
14914    // diagnose this as an error when the declaration specifiers are
14915    // freestanding. Here, we just ignore the __module_private__.
14916    else if (!SearchDC->isFunctionOrMethod())
14917      New->setModulePrivate();
14918  }
14919
14920  // If this is a specialization of a member class (of a class template),
14921  // check the specialization.
14922  if (isMemberSpecialization && CheckMemberSpecialization(NewPrevious))
14923    Invalid = true;
14924
14925  // If we're declaring or defining a tag in function prototype scope in C,
14926  // note that this type can only be used within the function and add it to
14927  // the list of decls to inject into the function definition scope.
14928  if ((Name || Kind == TTK_Enum) &&
14929      getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
14930    if (getLangOpts().CPlusPlus) {
14931      // C++ [dcl.fct]p6:
14932      //   Types shall not be defined in return or parameter types.
14933      if (TUK == TUK_Definition && !IsTypeSpecifier) {
14934        Diag(Loc, diag::err_type_defined_in_param_type)
14935            << Name;
14936        Invalid = true;
14937      }
14938    } else if (!PrevDecl) {
14939      Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
14940    }
14941  }
14942
14943  if (Invalid)
14944    New->setInvalidDecl();
14945
14946  // Set the lexical context. If the tag has a C++ scope specifier, the
14947  // lexical context will be different from the semantic context.
14948  New->setLexicalDeclContext(CurContext);
14949
14950  // Mark this as a friend decl if applicable.
14951  // In Microsoft mode, a friend declaration also acts as a forward
14952  // declaration so we always pass true to setObjectOfFriendDecl to make
14953  // the tag name visible.
14954  if (TUK == TUK_Friend)
14955    New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
14956
14957  // Set the access specifier.
14958  if (!Invalid && SearchDC->isRecord())
14959    SetMemberAccessSpecifier(NewPrevDeclAS);
14960
14961  if (PrevDecl)
14962    CheckRedeclarationModuleOwnership(NewPrevDecl);
14963
14964  if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
14965    New->startDefinition();
14966
14967  ProcessDeclAttributeList(SNewAttrs);
14968  AddPragmaAttributes(SNew);
14969
14970  // If this has an identifier, add it to the scope stack.
14971  if (TUK == TUK_Friend) {
14972    // We might be replacing an existing declaration in the lookup tables;
14973    // if so, borrow its access specifier.
14974    if (PrevDecl)
14975      New->setAccess(PrevDecl->getAccess());
14976
14977    DeclContext *DC = New->getDeclContext()->getRedeclContext();
14978    DC->makeDeclVisibleInContext(New);
14979    if (Name// can be null along some error paths
14980      if (Scope *EnclosingScope = getScopeForDeclContext(SDC))
14981        PushOnScopeChains(NewEnclosingScope/* AddToContext = */ false);
14982  } else if (Name) {
14983    S = getNonFieldDeclScope(S);
14984    PushOnScopeChains(NewStrue);
14985  } else {
14986    CurContext->addDecl(New);
14987  }
14988
14989  // If this is the C FILE type, notify the AST context.
14990  if (IdentifierInfo *II = New->getIdentifier())
14991    if (!New->isInvalidDecl() &&
14992        New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
14993        II->isStr("FILE"))
14994      Context.setFILEDecl(New);
14995
14996  if (PrevDecl)
14997    mergeDeclAttributes(NewPrevDecl);
14998
14999  // If there's a #pragma GCC visibility in scope, set the visibility of this
15000  // record.
15001  AddPushedVisibilityAttribute(New);
15002
15003  if (isMemberSpecialization && !New->isInvalidDecl())
15004    CompleteMemberSpecialization(NewPrevious);
15005
15006  OwnedDecl = true;
15007  // In C++, don't return an invalid declaration. We can't recover well from
15008  // the cases where we make the type anonymous.
15009  if (Invalid && getLangOpts().CPlusPlus) {
15010    if (New->isBeingDefined())
15011      if (auto RD = dyn_cast<RecordDecl>(New))
15012        RD->completeDefinition();
15013    return nullptr;
15014  } else if (SkipBody && SkipBody->ShouldSkip) {
15015    return SkipBody->Previous;
15016  } else {
15017    return New;
15018  }
15019}
15020
15021void Sema::ActOnTagStartDefinition(Scope *SDecl *TagD) {
15022  AdjustDeclIfTemplate(TagD);
15023  TagDecl *Tag = cast<TagDecl>(TagD);
15024
15025  // Enter the tag context.
15026  PushDeclContext(STag);
15027
15028  ActOnDocumentableDecl(TagD);
15029
15030  // If there's a #pragma GCC visibility in scope, set the visibility of this
15031  // record.
15032  AddPushedVisibilityAttribute(Tag);
15033}
15034
15035bool Sema::ActOnDuplicateDefinition(DeclSpec &DSDecl *Prev,
15036                                    SkipBodyInfo &SkipBody) {
15037  if (!hasStructuralCompatLayout(PrevSkipBody.New))
15038    return false;
15039
15040  // Make the previous decl visible.
15041  makeMergedDefinitionVisible(SkipBody.Previous);
15042  return true;
15043}
15044
15045Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
15046   (0) . __assert_fail ("isa(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 15047, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(isa<ObjCContainerDecl>(IDecl) &&
15047 (0) . __assert_fail ("isa(IDecl) && \"ActOnObjCContainerStartDefinition - Not ObjCContainerDecl\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 15047, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
15048  DeclContext *OCD = cast<DeclContext>(IDecl);
15049   (0) . __assert_fail ("getContainingDC(OCD) == CurContext && \"The next DeclContext should be lexically contained in the current one.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 15050, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(getContainingDC(OCD) == CurContext &&
15050 (0) . __assert_fail ("getContainingDC(OCD) == CurContext && \"The next DeclContext should be lexically contained in the current one.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 15050, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">      "The next DeclContext should be lexically contained in the current one.");
15051  CurContext = OCD;
15052  return IDecl;
15053}
15054
15055void Sema::ActOnStartCXXMemberDeclarations(Scope *SDecl *TagD,
15056                                           SourceLocation FinalLoc,
15057                                           bool IsFinalSpelledSealed,
15058                                           SourceLocation LBraceLoc) {
15059  AdjustDeclIfTemplate(TagD);
15060  CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
15061
15062  FieldCollector->StartClass();
15063
15064  if (!Record->getIdentifier())
15065    return;
15066
15067  if (FinalLoc.isValid())
15068    Record->addAttr(new (Context)
15069                    FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
15070
15071  // C++ [class]p2:
15072  //   [...] The class-name is also inserted into the scope of the
15073  //   class itself; this is known as the injected-class-name. For
15074  //   purposes of access checking, the injected-class-name is treated
15075  //   as if it were a public member name.
15076  CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
15077      ContextRecord->getTagKind(), CurContextRecord->getBeginLoc(),
15078      Record->getLocation(), Record->getIdentifier(),
15079      /*PrevDecl=*/nullptr,
15080      /*DelayTypeCreation=*/true);
15081  Context.getTypeDeclType(InjectedClassNameRecord);
15082  InjectedClassName->setImplicit();
15083  InjectedClassName->setAccess(AS_public);
15084  if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
15085      InjectedClassName->setDescribedClassTemplate(Template);
15086  PushOnScopeChains(InjectedClassNameS);
15087   (0) . __assert_fail ("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 15088, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(InjectedClassName->isInjectedClassName() &&
15088 (0) . __assert_fail ("InjectedClassName->isInjectedClassName() && \"Broken injected-class-name\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 15088, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "Broken injected-class-name");
15089}
15090
15091void Sema::ActOnTagFinishDefinition(Scope *SDecl *TagD,
15092                                    SourceRange BraceRange) {
15093  AdjustDeclIfTemplate(TagD);
15094  TagDecl *Tag = cast<TagDecl>(TagD);
15095  Tag->setBraceRange(BraceRange);
15096
15097  // Make sure we "complete" the definition even it is invalid.
15098  if (Tag->isBeingDefined()) {
15099     (0) . __assert_fail ("Tag->isInvalidDecl() && \"We should already have completed it\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 15099, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Tag->isInvalidDecl() && "We should already have completed it");
15100    if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15101      RD->completeDefinition();
15102  }
15103
15104  if (isa<CXXRecordDecl>(Tag)) {
15105    FieldCollector->FinishClass();
15106  }
15107
15108  // Exit this scope of this tag's definition.
15109  PopDeclContext();
15110
15111  if (getCurLexicalContext()->isObjCContainer() &&
15112      Tag->getDeclContext()->isFileContext())
15113    Tag->setTopLevelDeclInObjCContainer();
15114
15115  // Notify the consumer that we've defined a tag.
15116  if (!Tag->isInvalidDecl())
15117    Consumer.HandleTagDeclDefinition(Tag);
15118}
15119
15120void Sema::ActOnObjCContainerFinishDefinition() {
15121  // Exit this scope of this interface definition.
15122  PopDeclContext();
15123}
15124
15125void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
15126   (0) . __assert_fail ("DC == CurContext && \"Mismatch of container contexts\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 15126, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(DC == CurContext && "Mismatch of container contexts");
15127  OriginalLexicalContext = DC;
15128  ActOnObjCContainerFinishDefinition();
15129}
15130
15131void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
15132  ActOnObjCContainerStartDefinition(cast<Decl>(DC));
15133  OriginalLexicalContext = nullptr;
15134}
15135
15136void Sema::ActOnTagDefinitionError(Scope *SDecl *TagD) {
15137  AdjustDeclIfTemplate(TagD);
15138  TagDecl *Tag = cast<TagDecl>(TagD);
15139  Tag->setInvalidDecl();
15140
15141  // Make sure we "complete" the definition even it is invalid.
15142  if (Tag->isBeingDefined()) {
15143    if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
15144      RD->completeDefinition();
15145  }
15146
15147  // We're undoing ActOnTagStartDefinition here, not
15148  // ActOnStartCXXMemberDeclarations, so we don't have to mess with
15149  // the FieldCollector.
15150
15151  PopDeclContext();
15152}
15153
15154// Note that FieldName may be null for anonymous bitfields.
15155ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
15156                                IdentifierInfo *FieldName,
15157                                QualType FieldTybool IsMsStruct,
15158                                Expr *BitWidthbool *ZeroWidth) {
15159  // Default to true; that shouldn't confuse checks for emptiness
15160  if (ZeroWidth)
15161    *ZeroWidth = true;
15162
15163  // C99 6.7.2.1p4 - verify the field type.
15164  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
15165  if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
15166    // Handle incomplete types with specific error.
15167    if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
15168      return ExprError();
15169    if (FieldName)
15170      return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
15171        << FieldName << FieldTy << BitWidth->getSourceRange();
15172    return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
15173      << FieldTy << BitWidth->getSourceRange();
15174  } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
15175                                             UPPC_BitFieldWidth))
15176    return ExprError();
15177
15178  // If the bit-width is type- or value-dependent, don't try to check
15179  // it now.
15180  if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
15181    return BitWidth;
15182
15183  llvm::APSInt Value;
15184  ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
15185  if (ICE.isInvalid())
15186    return ICE;
15187  BitWidth = ICE.get();
15188
15189  if (Value != 0 && ZeroWidth)
15190    *ZeroWidth = false;
15191
15192  // Zero-width bitfield is ok for anonymous field.
15193  if (Value == 0 && FieldName)
15194    return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
15195
15196  if (Value.isSigned() && Value.isNegative()) {
15197    if (FieldName)
15198      return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
15199               << FieldName << Value.toString(10);
15200    return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
15201      << Value.toString(10);
15202  }
15203
15204  if (!FieldTy->isDependentType()) {
15205    uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
15206    uint64_t TypeWidth = Context.getIntWidth(FieldTy);
15207    bool BitfieldIsOverwide = Value.ugt(TypeWidth);
15208
15209    // Over-wide bitfields are an error in C or when using the MSVC bitfield
15210    // ABI.
15211    bool CStdConstraintViolation =
15212        BitfieldIsOverwide && !getLangOpts().CPlusPlus;
15213    bool MSBitfieldViolation =
15214        Value.ugt(TypeStorageSize) &&
15215        (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
15216    if (CStdConstraintViolation || MSBitfieldViolation) {
15217      unsigned DiagWidth =
15218          CStdConstraintViolation ? TypeWidth : TypeStorageSize;
15219      if (FieldName)
15220        return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
15221               << FieldName << (unsigned)Value.getZExtValue()
15222               << !CStdConstraintViolation << DiagWidth;
15223
15224      return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
15225             << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
15226             << DiagWidth;
15227    }
15228
15229    // Warn on types where the user might conceivably expect to get all
15230    // specified bits as value bits: that's all integral types other than
15231    // 'bool'.
15232    if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
15233      if (FieldName)
15234        Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
15235            << FieldName << (unsigned)Value.getZExtValue()
15236            << (unsigned)TypeWidth;
15237      else
15238        Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
15239            << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
15240    }
15241  }
15242
15243  return BitWidth;
15244}
15245
15246/// ActOnField - Each field of a C struct/union is passed into this in order
15247/// to create a FieldDecl object for it.
15248Decl *Sema::ActOnField(Scope *SDecl *TagDSourceLocation DeclStart,
15249                       Declarator &DExpr *BitfieldWidth) {
15250  FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
15251                               DeclStartDstatic_cast<Expr*>(BitfieldWidth),
15252                               /*InitStyle=*/ICIS_NoInitAS_public);
15253  return Res;
15254}
15255
15256/// HandleField - Analyze a field of a C struct or a C++ data member.
15257///
15258FieldDecl *Sema::HandleField(Scope *SRecordDecl *Record,
15259                             SourceLocation DeclStart,
15260                             Declarator &DExpr *BitWidth,
15261                             InClassInitStyle InitStyle,
15262                             AccessSpecifier AS) {
15263  if (D.isDecompositionDeclarator()) {
15264    const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
15265    Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
15266      << Decomp.getSourceRange();
15267    return nullptr;
15268  }
15269
15270  IdentifierInfo *II = D.getIdentifier();
15271  SourceLocation Loc = DeclStart;
15272  if (IILoc = D.getIdentifierLoc();
15273
15274  TypeSourceInfo *TInfo = GetTypeForDeclarator(DS);
15275  QualType T = TInfo->getType();
15276  if (getLangOpts().CPlusPlus) {
15277    CheckExtraCXXDefaultArguments(D);
15278
15279    if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
15280                                        UPPC_DataMemberType)) {
15281      D.setInvalidType();
15282      T = Context.IntTy;
15283      TInfo = Context.getTrivialTypeSourceInfo(TLoc);
15284    }
15285  }
15286
15287  DiagnoseFunctionSpecifiers(D.getDeclSpec());
15288
15289  if (D.getDeclSpec().isInlineSpecified())
15290    Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
15291        << getLangOpts().CPlusPlus17;
15292  if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
15293    Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
15294         diag::err_invalid_thread)
15295      << DeclSpec::getSpecifierName(TSCS);
15296
15297  // Check to see if this name was declared as a member previously
15298  NamedDecl *PrevDecl = nullptr;
15299  LookupResult Previous(*thisIILocLookupMemberName,
15300                        ForVisibleRedeclaration);
15301  LookupName(PreviousS);
15302  switch (Previous.getResultKind()) {
15303    case LookupResult::Found:
15304    case LookupResult::FoundUnresolvedValue:
15305      PrevDecl = Previous.getAsSingle<NamedDecl>();
15306      break;
15307
15308    case LookupResult::FoundOverloaded:
15309      PrevDecl = Previous.getRepresentativeDecl();
15310      break;
15311
15312    case LookupResult::NotFound:
15313    case LookupResult::NotFoundInCurrentInstantiation:
15314    case LookupResult::Ambiguous:
15315      break;
15316  }
15317  Previous.suppressDiagnostics();
15318
15319  if (PrevDecl && PrevDecl->isTemplateParameter()) {
15320    // Maybe we will complain about the shadowed template parameter.
15321    DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15322    // Just pretend that we didn't see the previous declaration.
15323    PrevDecl = nullptr;
15324  }
15325
15326  if (PrevDecl && !isDeclInScope(PrevDeclRecordS))
15327    PrevDecl = nullptr;
15328
15329  bool Mutable
15330    = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
15331  SourceLocation TSSL = D.getBeginLoc();
15332  FieldDecl *NewFD
15333    = CheckFieldDecl(IITTInfoRecordLocMutableBitWidthInitStyle,
15334                     TSSLASPrevDecl, &D);
15335
15336  if (NewFD->isInvalidDecl())
15337    Record->setInvalidDecl();
15338
15339  if (D.getDeclSpec().isModulePrivateSpecified())
15340    NewFD->setModulePrivate();
15341
15342  if (NewFD->isInvalidDecl() && PrevDecl) {
15343    // Don't introduce NewFD into scope; there's already something
15344    // with the same name in the same scope.
15345  } else if (II) {
15346    PushOnScopeChains(NewFDS);
15347  } else
15348    Record->addDecl(NewFD);
15349
15350  return NewFD;
15351}
15352
15353/// Build a new FieldDecl and check its well-formedness.
15354///
15355/// This routine builds a new FieldDecl given the fields name, type,
15356/// record, etc. \p PrevDecl should refer to any previous declaration
15357/// with the same name and in the same scope as the field to be
15358/// created.
15359///
15360/// \returns a new FieldDecl.
15361///
15362/// \todo The Declarator argument is a hack. It will be removed once
15363FieldDecl *Sema::CheckFieldDecl(DeclarationName NameQualType T,
15364                                TypeSourceInfo *TInfo,
15365                                RecordDecl *RecordSourceLocation Loc,
15366                                bool MutableExpr *BitWidth,
15367                                InClassInitStyle InitStyle,
15368                                SourceLocation TSSL,
15369                                AccessSpecifier ASNamedDecl *PrevDecl,
15370                                Declarator *D) {
15371  IdentifierInfo *II = Name.getAsIdentifierInfo();
15372  bool InvalidDecl = false;
15373  if (DInvalidDecl = D->isInvalidType();
15374
15375  // If we receive a broken type, recover by assuming 'int' and
15376  // marking this declaration as invalid.
15377  if (T.isNull()) {
15378    InvalidDecl = true;
15379    T = Context.IntTy;
15380  }
15381
15382  QualType EltTy = Context.getBaseElementType(T);
15383  if (!EltTy->isDependentType()) {
15384    if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
15385      // Fields of incomplete type force their record to be invalid.
15386      Record->setInvalidDecl();
15387      InvalidDecl = true;
15388    } else {
15389      NamedDecl *Def;
15390      EltTy->isIncompleteType(&Def);
15391      if (Def && Def->isInvalidDecl()) {
15392        Record->setInvalidDecl();
15393        InvalidDecl = true;
15394      }
15395    }
15396  }
15397
15398  // TR 18037 does not allow fields to be declared with address space
15399  if (T.getQualifiers().hasAddressSpace() || T->isDependentAddressSpaceType() ||
15400      T->getBaseElementTypeUnsafe()->isDependentAddressSpaceType()) {
15401    Diag(Loc, diag::err_field_with_address_space);
15402    Record->setInvalidDecl();
15403    InvalidDecl = true;
15404  }
15405
15406  if (LangOpts.OpenCL) {
15407    // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
15408    // used as structure or union field: image, sampler, event or block types.
15409    if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
15410        T->isBlockPointerType()) {
15411      Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
15412      Record->setInvalidDecl();
15413      InvalidDecl = true;
15414    }
15415    // OpenCL v1.2 s6.9.c: bitfields are not supported.
15416    if (BitWidth) {
15417      Diag(Loc, diag::err_opencl_bitfields);
15418      InvalidDecl = true;
15419    }
15420  }
15421
15422  // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
15423  if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
15424      T.hasQualifiers()) {
15425    InvalidDecl = true;
15426    Diag(Loc, diag::err_anon_bitfield_qualifiers);
15427  }
15428
15429  // C99 6.7.2.1p8: A member of a structure or union may have any type other
15430  // than a variably modified type.
15431  if (!InvalidDecl && T->isVariablyModifiedType()) {
15432    bool SizeIsNegative;
15433    llvm::APSInt Oversized;
15434
15435    TypeSourceInfo *FixedTInfo =
15436      TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
15437                                                    SizeIsNegative,
15438                                                    Oversized);
15439    if (FixedTInfo) {
15440      Diag(Loc, diag::warn_illegal_constant_array_size);
15441      TInfo = FixedTInfo;
15442      T = FixedTInfo->getType();
15443    } else {
15444      if (SizeIsNegative)
15445        Diag(Loc, diag::err_typecheck_negative_array_size);
15446      else if (Oversized.getBoolValue())
15447        Diag(Loc, diag::err_array_too_large)
15448          << Oversized.toString(10);
15449      else
15450        Diag(Loc, diag::err_typecheck_field_variable_size);
15451      InvalidDecl = true;
15452    }
15453  }
15454
15455  // Fields can not have abstract class types
15456  if (!InvalidDecl && RequireNonAbstractType(Loc, T,
15457                                             diag::err_abstract_type_in_decl,
15458                                             AbstractFieldType))
15459    InvalidDecl = true;
15460
15461  bool ZeroWidth = false;
15462  if (InvalidDecl)
15463    BitWidth = nullptr;
15464  // If this is declared as a bit-field, check the bit-field.
15465  if (BitWidth) {
15466    BitWidth = VerifyBitField(LocIITRecord->isMsStruct(Context), BitWidth,
15467                              &ZeroWidth).get();
15468    if (!BitWidth) {
15469      InvalidDecl = true;
15470      BitWidth = nullptr;
15471      ZeroWidth = false;
15472    }
15473  }
15474
15475  // Check that 'mutable' is consistent with the type of the declaration.
15476  if (!InvalidDecl && Mutable) {
15477    unsigned DiagID = 0;
15478    if (T->isReferenceType())
15479      DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
15480                                        : diag::err_mutable_reference;
15481    else if (T.isConstQualified())
15482      DiagID = diag::err_mutable_const;
15483
15484    if (DiagID) {
15485      SourceLocation ErrLoc = Loc;
15486      if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
15487        ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
15488      Diag(ErrLocDiagID);
15489      if (DiagID != diag::ext_mutable_reference) {
15490        Mutable = false;
15491        InvalidDecl = true;
15492      }
15493    }
15494  }
15495
15496  // C++11 [class.union]p8 (DR1460):
15497  //   At most one variant member of a union may have a
15498  //   brace-or-equal-initializer.
15499  if (InitStyle != ICIS_NoInit)
15500    checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
15501
15502  FieldDecl *NewFD = FieldDecl::Create(ContextRecordTSSLLocIITTInfo,
15503                                       BitWidthMutableInitStyle);
15504  if (InvalidDecl)
15505    NewFD->setInvalidDecl();
15506
15507  if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
15508    Diag(Loc, diag::err_duplicate_member) << II;
15509    Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15510    NewFD->setInvalidDecl();
15511  }
15512
15513  if (!InvalidDecl && getLangOpts().CPlusPlus) {
15514    if (Record->isUnion()) {
15515      if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15516        CXXRecordDeclRDecl = cast<CXXRecordDecl>(RT->getDecl());
15517        if (RDecl->getDefinition()) {
15518          // C++ [class.union]p1: An object of a class with a non-trivial
15519          // constructor, a non-trivial copy constructor, a non-trivial
15520          // destructor, or a non-trivial copy assignment operator
15521          // cannot be a member of a union, nor can an array of such
15522          // objects.
15523          if (CheckNontrivialField(NewFD))
15524            NewFD->setInvalidDecl();
15525        }
15526      }
15527
15528      // C++ [class.union]p1: If a union contains a member of reference type,
15529      // the program is ill-formed, except when compiling with MSVC extensions
15530      // enabled.
15531      if (EltTy->isReferenceType()) {
15532        Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
15533                                    diag::ext_union_member_of_reference_type :
15534                                    diag::err_union_member_of_reference_type)
15535          << NewFD->getDeclName() << EltTy;
15536        if (!getLangOpts().MicrosoftExt)
15537          NewFD->setInvalidDecl();
15538      }
15539    }
15540  }
15541
15542  // FIXME: We need to pass in the attributes given an AST
15543  // representation, not a parser representation.
15544  if (D) {
15545    // FIXME: The current scope is almost... but not entirely... correct here.
15546    ProcessDeclAttributes(getCurScope(), NewFD, *D);
15547
15548    if (NewFD->hasAttrs())
15549      CheckAlignasUnderalignment(NewFD);
15550  }
15551
15552  // In auto-retain/release, infer strong retension for fields of
15553  // retainable type.
15554  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
15555    NewFD->setInvalidDecl();
15556
15557  if (T.isObjCGCWeak())
15558    Diag(Loc, diag::warn_attribute_weak_on_field);
15559
15560  NewFD->setAccess(AS);
15561  return NewFD;
15562}
15563
15564bool Sema::CheckNontrivialField(FieldDecl *FD) {
15565  assert(FD);
15566   (0) . __assert_fail ("getLangOpts().CPlusPlus && \"valid check only for C++\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 15566, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(getLangOpts().CPlusPlus && "valid check only for C++");
15567
15568  if (FD->isInvalidDecl() || FD->getType()->isDependentType())
15569    return false;
15570
15571  QualType EltTy = Context.getBaseElementType(FD->getType());
15572  if (const RecordType *RT = EltTy->getAs<RecordType>()) {
15573    CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
15574    if (RDecl->getDefinition()) {
15575      // We check for copy constructors before constructors
15576      // because otherwise we'll never get complaints about
15577      // copy constructors.
15578
15579      CXXSpecialMember member = CXXInvalid;
15580      // We're required to check for any non-trivial constructors. Since the
15581      // implicit default constructor is suppressed if there are any
15582      // user-declared constructors, we just need to check that there is a
15583      // trivial default constructor and a trivial copy constructor. (We don't
15584      // worry about move constructors here, since this is a C++98 check.)
15585      if (RDecl->hasNonTrivialCopyConstructor())
15586        member = CXXCopyConstructor;
15587      else if (!RDecl->hasTrivialDefaultConstructor())
15588        member = CXXDefaultConstructor;
15589      else if (RDecl->hasNonTrivialCopyAssignment())
15590        member = CXXCopyAssignment;
15591      else if (RDecl->hasNonTrivialDestructor())
15592        member = CXXDestructor;
15593
15594      if (member != CXXInvalid) {
15595        if (!getLangOpts().CPlusPlus11 &&
15596            getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
15597          // Objective-C++ ARC: it is an error to have a non-trivial field of
15598          // a union. However, system headers in Objective-C programs
15599          // occasionally have Objective-C lifetime objects within unions,
15600          // and rather than cause the program to fail, we make those
15601          // members unavailable.
15602          SourceLocation Loc = FD->getLocation();
15603          if (getSourceManager().isInSystemHeader(Loc)) {
15604            if (!FD->hasAttr<UnavailableAttr>())
15605              FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15606                            UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
15607            return false;
15608          }
15609        }
15610
15611        Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
15612               diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
15613               diag::err_illegal_union_or_anon_struct_member)
15614          << FD->getParent()->isUnion() << FD->getDeclName() << member;
15615        DiagnoseNontrivial(RDeclmember);
15616        return !getLangOpts().CPlusPlus11;
15617      }
15618    }
15619  }
15620
15621  return false;
15622}
15623
15624/// TranslateIvarVisibility - Translate visibility from a token ID to an
15625///  AST enum value.
15626static ObjCIvarDecl::AccessControl
15627TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
15628  switch (ivarVisibility) {
15629  default: llvm_unreachable("Unknown visitibility kind");
15630  case tok::objc_privatereturn ObjCIvarDecl::Private;
15631  case tok::objc_publicreturn ObjCIvarDecl::Public;
15632  case tok::objc_protectedreturn ObjCIvarDecl::Protected;
15633  case tok::objc_packagereturn ObjCIvarDecl::Package;
15634  }
15635}
15636
15637/// ActOnIvar - Each ivar field of an objective-c class is passed into this
15638/// in order to create an IvarDecl object for it.
15639Decl *Sema::ActOnIvar(Scope *S,
15640                                SourceLocation DeclStart,
15641                                Declarator &DExpr *BitfieldWidth,
15642                                tok::ObjCKeywordKind Visibility) {
15643
15644  IdentifierInfo *II = D.getIdentifier();
15645  Expr *BitWidth = (Expr*)BitfieldWidth;
15646  SourceLocation Loc = DeclStart;
15647  if (IILoc = D.getIdentifierLoc();
15648
15649  // FIXME: Unnamed fields can be handled in various different ways, for
15650  // example, unnamed unions inject all members into the struct namespace!
15651
15652  TypeSourceInfo *TInfo = GetTypeForDeclarator(DS);
15653  QualType T = TInfo->getType();
15654
15655  if (BitWidth) {
15656    // 6.7.2.1p3, 6.7.2.1p4
15657    BitWidth = VerifyBitField(LocIIT/*IsMsStruct*/falseBitWidth).get();
15658    if (!BitWidth)
15659      D.setInvalidType();
15660  } else {
15661    // Not a bitfield.
15662
15663    // validate II.
15664
15665  }
15666  if (T->isReferenceType()) {
15667    Diag(Loc, diag::err_ivar_reference_type);
15668    D.setInvalidType();
15669  }
15670  // C99 6.7.2.1p8: A member of a structure or union may have any type other
15671  // than a variably modified type.
15672  else if (T->isVariablyModifiedType()) {
15673    Diag(Loc, diag::err_typecheck_ivar_variable_size);
15674    D.setInvalidType();
15675  }
15676
15677  // Get the visibility (access control) for this ivar.
15678  ObjCIvarDecl::AccessControl ac =
15679    Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
15680                                        : ObjCIvarDecl::None;
15681  // Must set ivar's DeclContext to its enclosing interface.
15682  ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
15683  if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
15684    return nullptr;
15685  ObjCContainerDecl *EnclosingContext;
15686  if (ObjCImplementationDecl *IMPDecl =
15687      dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
15688    if (LangOpts.ObjCRuntime.isFragile()) {
15689    // Case of ivar declared in an implementation. Context is that of its class.
15690      EnclosingContext = IMPDecl->getClassInterface();
15691       (0) . __assert_fail ("EnclosingContext && \"Implementation has no class interface!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 15691, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(EnclosingContext && "Implementation has no class interface!");
15692    }
15693    else
15694      EnclosingContext = EnclosingDecl;
15695  } else {
15696    if (ObjCCategoryDecl *CDecl =
15697        dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
15698      if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
15699        Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
15700        return nullptr;
15701      }
15702    }
15703    EnclosingContext = EnclosingDecl;
15704  }
15705
15706  // Construct the decl.
15707  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(ContextEnclosingContext,
15708                                             DeclStartLocIIT,
15709                                             TInfoac, (Expr *)BitfieldWidth);
15710
15711  if (II) {
15712    NamedDecl *PrevDecl = LookupSingleName(SIILocLookupMemberName,
15713                                           ForVisibleRedeclaration);
15714    if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
15715        && !isa<TagDecl>(PrevDecl)) {
15716      Diag(Loc, diag::err_duplicate_member) << II;
15717      Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
15718      NewID->setInvalidDecl();
15719    }
15720  }
15721
15722  // Process attributes attached to the ivar.
15723  ProcessDeclAttributes(SNewIDD);
15724
15725  if (D.isInvalidType())
15726    NewID->setInvalidDecl();
15727
15728  // In ARC, infer 'retaining' for ivars of retainable type.
15729  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
15730    NewID->setInvalidDecl();
15731
15732  if (D.getDeclSpec().isModulePrivateSpecified())
15733    NewID->setModulePrivate();
15734
15735  if (II) {
15736    // FIXME: When interfaces are DeclContexts, we'll need to add
15737    // these to the interface.
15738    S->AddDecl(NewID);
15739    IdResolver.AddDecl(NewID);
15740  }
15741
15742  if (LangOpts.ObjCRuntime.isNonFragile() &&
15743      !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
15744    Diag(Loc, diag::warn_ivars_in_interface);
15745
15746  return NewID;
15747}
15748
15749/// ActOnLastBitfield - This routine handles synthesized bitfields rules for
15750/// class and class extensions. For every class \@interface and class
15751/// extension \@interface, if the last ivar is a bitfield of any type,
15752/// then add an implicit `char :0` ivar to the end of that interface.
15753void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
15754                             SmallVectorImpl<Decl *> &AllIvarDecls) {
15755  if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
15756    return;
15757
15758  Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
15759  ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
15760
15761  if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
15762    return;
15763  ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
15764  if (!ID) {
15765    if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
15766      if (!CD->IsClassExtension())
15767        return;
15768    }
15769    // No need to add this to end of @implementation.
15770    else
15771      return;
15772  }
15773  // All conditions are met. Add a new bitfield to the tail end of ivars.
15774  llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
15775  Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
15776
15777  Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
15778                              DeclLocDeclLocnullptr,
15779                              Context.CharTy,
15780                              Context.getTrivialTypeSourceInfo(Context.CharTy,
15781                                                               DeclLoc),
15782                              ObjCIvarDecl::PrivateBW,
15783                              true);
15784  AllIvarDecls.push_back(Ivar);
15785}
15786
15787void Sema::ActOnFields(Scope *SSourceLocation RecLocDecl *EnclosingDecl,
15788                       ArrayRef<Decl *> FieldsSourceLocation LBrac,
15789                       SourceLocation RBrac,
15790                       const ParsedAttributesView &Attrs) {
15791   (0) . __assert_fail ("EnclosingDecl && \"missing record or interface decl\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 15791, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(EnclosingDecl && "missing record or interface decl");
15792
15793  // If this is an Objective-C @implementation or category and we have
15794  // new fields here we should reset the layout of the interface since
15795  // it will now change.
15796  if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
15797    ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
15798    switch (DC->getKind()) {
15799    defaultbreak;
15800    case Decl::ObjCCategory:
15801      Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
15802      break;
15803    case Decl::ObjCImplementation:
15804      Context.
15805        ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
15806      break;
15807    }
15808  }
15809
15810  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
15811  CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
15812
15813  // Start counting up the number of named members; make sure to include
15814  // members of anonymous structs and unions in the total.
15815  unsigned NumNamedMembers = 0;
15816  if (Record) {
15817    for (const auto *I : Record->decls()) {
15818      if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
15819        if (IFD->getDeclName())
15820          ++NumNamedMembers;
15821    }
15822  }
15823
15824  // Verify that all the fields are okay.
15825  SmallVector<FieldDecl*, 32RecFields;
15826
15827  bool ObjCFieldLifetimeErrReported = false;
15828  for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
15829       i != end; ++i) {
15830    FieldDecl *FD = cast<FieldDecl>(*i);
15831
15832    // Get the type for the field.
15833    const Type *FDTy = FD->getType().getTypePtr();
15834
15835    if (!FD->isAnonymousStructOrUnion()) {
15836      // Remember all fields written by the user.
15837      RecFields.push_back(FD);
15838    }
15839
15840    // If the field is already invalid for some reason, don't emit more
15841    // diagnostics about it.
15842    if (FD->isInvalidDecl()) {
15843      EnclosingDecl->setInvalidDecl();
15844      continue;
15845    }
15846
15847    // C99 6.7.2.1p2:
15848    //   A structure or union shall not contain a member with
15849    //   incomplete or function type (hence, a structure shall not
15850    //   contain an instance of itself, but may contain a pointer to
15851    //   an instance of itself), except that the last member of a
15852    //   structure with more than one named member may have incomplete
15853    //   array type; such a structure (and any union containing,
15854    //   possibly recursively, a member that is such a structure)
15855    //   shall not be a member of a structure or an element of an
15856    //   array.
15857    bool IsLastField = (i + 1 == Fields.end());
15858    if (FDTy->isFunctionType()) {
15859      // Field declared as a function.
15860      Diag(FD->getLocation(), diag::err_field_declared_as_function)
15861        << FD->getDeclName();
15862      FD->setInvalidDecl();
15863      EnclosingDecl->setInvalidDecl();
15864      continue;
15865    } else if (FDTy->isIncompleteArrayType() &&
15866               (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
15867      if (Record) {
15868        // Flexible array member.
15869        // Microsoft and g++ is more permissive regarding flexible array.
15870        // It will accept flexible array in union and also
15871        // as the sole element of a struct/class.
15872        unsigned DiagID = 0;
15873        if (!Record->isUnion() && !IsLastField) {
15874          Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
15875            << FD->getDeclName() << FD->getType() << Record->getTagKind();
15876          Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
15877          FD->setInvalidDecl();
15878          EnclosingDecl->setInvalidDecl();
15879          continue;
15880        } else if (Record->isUnion())
15881          DiagID = getLangOpts().MicrosoftExt
15882                       ? diag::ext_flexible_array_union_ms
15883                       : getLangOpts().CPlusPlus
15884                             ? diag::ext_flexible_array_union_gnu
15885                             : diag::err_flexible_array_union;
15886        else if (NumNamedMembers < 1)
15887          DiagID = getLangOpts().MicrosoftExt
15888                       ? diag::ext_flexible_array_empty_aggregate_ms
15889                       : getLangOpts().CPlusPlus
15890                             ? diag::ext_flexible_array_empty_aggregate_gnu
15891                             : diag::err_flexible_array_empty_aggregate;
15892
15893        if (DiagID)
15894          Diag(FD->getLocation(), DiagID) << FD->getDeclName()
15895                                          << Record->getTagKind();
15896        // While the layout of types that contain virtual bases is not specified
15897        // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
15898        // virtual bases after the derived members.  This would make a flexible
15899        // array member declared at the end of an object not adjacent to the end
15900        // of the type.
15901        if (CXXRecord && CXXRecord->getNumVBases() != 0)
15902          Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
15903              << FD->getDeclName() << Record->getTagKind();
15904        if (!getLangOpts().C99)
15905          Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
15906            << FD->getDeclName() << Record->getTagKind();
15907
15908        // If the element type has a non-trivial destructor, we would not
15909        // implicitly destroy the elements, so disallow it for now.
15910        //
15911        // FIXME: GCC allows this. We should probably either implicitly delete
15912        // the destructor of the containing class, or just allow this.
15913        QualType BaseElem = Context.getBaseElementType(FD->getType());
15914        if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
15915          Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
15916            << FD->getDeclName() << FD->getType();
15917          FD->setInvalidDecl();
15918          EnclosingDecl->setInvalidDecl();
15919          continue;
15920        }
15921        // Okay, we have a legal flexible array member at the end of the struct.
15922        Record->setHasFlexibleArrayMember(true);
15923      } else {
15924        // In ObjCContainerDecl ivars with incomplete array type are accepted,
15925        // unless they are followed by another ivar. That check is done
15926        // elsewhere, after synthesized ivars are known.
15927      }
15928    } else if (!FDTy->isDependentType() &&
15929               RequireCompleteType(FD->getLocation(), FD->getType(),
15930                                   diag::err_field_incomplete)) {
15931      // Incomplete type
15932      FD->setInvalidDecl();
15933      EnclosingDecl->setInvalidDecl();
15934      continue;
15935    } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
15936      if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
15937        // A type which contains a flexible array member is considered to be a
15938        // flexible array member.
15939        Record->setHasFlexibleArrayMember(true);
15940        if (!Record->isUnion()) {
15941          // If this is a struct/class and this is not the last element, reject
15942          // it.  Note that GCC supports variable sized arrays in the middle of
15943          // structures.
15944          if (!IsLastField)
15945            Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
15946              << FD->getDeclName() << FD->getType();
15947          else {
15948            // We support flexible arrays at the end of structs in
15949            // other structs as an extension.
15950            Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
15951              << FD->getDeclName();
15952          }
15953        }
15954      }
15955      if (isa<ObjCContainerDecl>(EnclosingDecl) &&
15956          RequireNonAbstractType(FD->getLocation(), FD->getType(),
15957                                 diag::err_abstract_type_in_decl,
15958                                 AbstractIvarType)) {
15959        // Ivars can not have abstract class types
15960        FD->setInvalidDecl();
15961      }
15962      if (Record && FDTTy->getDecl()->hasObjectMember())
15963        Record->setHasObjectMember(true);
15964      if (Record && FDTTy->getDecl()->hasVolatileMember())
15965        Record->setHasVolatileMember(true);
15966      if (Record && Record->isUnion() &&
15967          FD->getType().isNonTrivialPrimitiveCType(Context))
15968        Diag(FD->getLocation(),
15969             diag::err_nontrivial_primitive_type_in_union);
15970    } else if (FDTy->isObjCObjectType()) {
15971      /// A field cannot be an Objective-c object
15972      Diag(FD->getLocation(), diag::err_statically_allocated_object)
15973        << FixItHint::CreateInsertion(FD->getLocation(), "*");
15974      QualType T = Context.getObjCObjectPointerType(FD->getType());
15975      FD->setType(T);
15976    } else if (getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
15977               Record && !ObjCFieldLifetimeErrReported && Record->isUnion() &&
15978               !getLangOpts().CPlusPlus) {
15979      // It's an error in ARC or Weak if a field has lifetime.
15980      // We don't want to report this in a system header, though,
15981      // so we just make the field unavailable.
15982      // FIXME: that's really not sufficient; we need to make the type
15983      // itself invalid to, say, initialize or copy.
15984      QualType T = FD->getType();
15985      if (T.hasNonTrivialObjCLifetime()) {
15986        SourceLocation loc = FD->getLocation();
15987        if (getSourceManager().isInSystemHeader(loc)) {
15988          if (!FD->hasAttr<UnavailableAttr>()) {
15989            FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
15990                          UnavailableAttr::IR_ARCFieldWithOwnership, loc));
15991          }
15992        } else {
15993          Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
15994            << T->isBlockPointerType() << Record->getTagKind();
15995        }
15996        ObjCFieldLifetimeErrReported = true;
15997      }
15998    } else if (getLangOpts().ObjC &&
15999               getLangOpts().getGC() != LangOptions::NonGC &&
16000               Record && !Record->hasObjectMember()) {
16001      if (FD->getType()->isObjCObjectPointerType() ||
16002          FD->getType().isObjCGCStrong())
16003        Record->setHasObjectMember(true);
16004      else if (Context.getAsArrayType(FD->getType())) {
16005        QualType BaseType = Context.getBaseElementType(FD->getType());
16006        if (BaseType->isRecordType() &&
16007            BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
16008          Record->setHasObjectMember(true);
16009        else if (BaseType->isObjCObjectPointerType() ||
16010                 BaseType.isObjCGCStrong())
16011               Record->setHasObjectMember(true);
16012      }
16013    }
16014
16015    if (Record && !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>()) {
16016      QualType FT = FD->getType();
16017      if (FT.isNonTrivialToPrimitiveDefaultInitialize())
16018        Record->setNonTrivialToPrimitiveDefaultInitialize(true);
16019      QualType::PrimitiveCopyKind PCK = FT.isNonTrivialToPrimitiveCopy();
16020      if (PCK != QualType::PCK_Trivial && PCK != QualType::PCK_VolatileTrivial)
16021        Record->setNonTrivialToPrimitiveCopy(true);
16022      if (FT.isDestructedType()) {
16023        Record->setNonTrivialToPrimitiveDestroy(true);
16024        Record->setParamDestroyedInCallee(true);
16025      }
16026
16027      if (const auto *RT = FT->getAs<RecordType>()) {
16028        if (RT->getDecl()->getArgPassingRestrictions() ==
16029            RecordDecl::APK_CanNeverPassInRegs)
16030          Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16031      } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
16032        Record->setArgPassingRestrictions(RecordDecl::APK_CanNeverPassInRegs);
16033    }
16034
16035    if (Record && FD->getType().isVolatileQualified())
16036      Record->setHasVolatileMember(true);
16037    // Keep track of the number of named members.
16038    if (FD->getIdentifier())
16039      ++NumNamedMembers;
16040  }
16041
16042  // Okay, we successfully defined 'Record'.
16043  if (Record) {
16044    bool Completed = false;
16045    if (CXXRecord) {
16046      if (!CXXRecord->isInvalidDecl()) {
16047        // Set access bits correctly on the directly-declared conversions.
16048        for (CXXRecordDecl::conversion_iterator
16049               I = CXXRecord->conversion_begin(),
16050               E = CXXRecord->conversion_end(); I != E; ++I)
16051          I.setAccess((*I)->getAccess());
16052      }
16053
16054      if (!CXXRecord->isDependentType()) {
16055        // Add any implicitly-declared members to this class.
16056        AddImplicitlyDeclaredMembersToClass(CXXRecord);
16057
16058        if (!CXXRecord->isInvalidDecl()) {
16059          // If we have virtual base classes, we may end up finding multiple
16060          // final overriders for a given virtual function. Check for this
16061          // problem now.
16062          if (CXXRecord->getNumVBases()) {
16063            CXXFinalOverriderMap FinalOverriders;
16064            CXXRecord->getFinalOverriders(FinalOverriders);
16065
16066            for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
16067                                             MEnd = FinalOverriders.end();
16068                 M != MEnd; ++M) {
16069              for (OverridingMethods::iterator SO = M->second.begin(),
16070                                            SOEnd = M->second.end();
16071                   SO != SOEnd; ++SO) {
16072                 (0) . __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 16073, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(SO->second.size() > 0 &&
16073 (0) . __assert_fail ("SO->second.size() > 0 && \"Virtual function without overriding functions?\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 16073, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">                       "Virtual function without overriding functions?");
16074                if (SO->second.size() == 1)
16075                  continue;
16076
16077                // C++ [class.virtual]p2:
16078                //   In a derived class, if a virtual member function of a base
16079                //   class subobject has more than one final overrider the
16080                //   program is ill-formed.
16081                Diag(Record->getLocation(), diag::err_multiple_final_overriders)
16082                  << (const NamedDecl *)M->first << Record;
16083                Diag(M->first->getLocation(),
16084                     diag::note_overridden_virtual_function);
16085                for (OverridingMethods::overriding_iterator
16086                          OM = SO->second.begin(),
16087                       OMEnd = SO->second.end();
16088                     OM != OMEnd; ++OM)
16089                  Diag(OM->Method->getLocation(), diag::note_final_overrider)
16090                    << (const NamedDecl *)M->first << OM->Method->getParent();
16091
16092                Record->setInvalidDecl();
16093              }
16094            }
16095            CXXRecord->completeDefinition(&FinalOverriders);
16096            Completed = true;
16097          }
16098        }
16099      }
16100    }
16101
16102    if (!Completed)
16103      Record->completeDefinition();
16104
16105    // Handle attributes before checking the layout.
16106    ProcessDeclAttributeList(S, Record, Attrs);
16107
16108    // We may have deferred checking for a deleted destructor. Check now.
16109    if (CXXRecord) {
16110      auto *Dtor = CXXRecord->getDestructor();
16111      if (Dtor && Dtor->isImplicit() &&
16112          ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
16113        CXXRecord->setImplicitDestructorIsDeleted();
16114        SetDeclDeleted(Dtor, CXXRecord->getLocation());
16115      }
16116    }
16117
16118    if (Record->hasAttrs()) {
16119      CheckAlignasUnderalignment(Record);
16120
16121      if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
16122        checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
16123                                           IA->getRange(), IA->getBestCase(),
16124                                           IA->getSemanticSpelling());
16125    }
16126
16127    // Check if the structure/union declaration is a type that can have zero
16128    // size in C. For C this is a language extension, for C++ it may cause
16129    // compatibility problems.
16130    bool CheckForZeroSize;
16131    if (!getLangOpts().CPlusPlus) {
16132      CheckForZeroSize = true;
16133    } else {
16134      // For C++ filter out types that cannot be referenced in C code.
16135      CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
16136      CheckForZeroSize =
16137          CXXRecord->getLexicalDeclContext()->isExternCContext() &&
16138          !CXXRecord->isDependentType() &&
16139          CXXRecord->isCLike();
16140    }
16141    if (CheckForZeroSize) {
16142      bool ZeroSize = true;
16143      bool IsEmpty = true;
16144      unsigned NonBitFields = 0;
16145      for (RecordDecl::field_iterator I = Record->field_begin(),
16146                                      E = Record->field_end();
16147           (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
16148        IsEmpty = false;
16149        if (I->isUnnamedBitfield()) {
16150          if (!I->isZeroLengthBitField(Context))
16151            ZeroSize = false;
16152        } else {
16153          ++NonBitFields;
16154          QualType FieldType = I->getType();
16155          if (FieldType->isIncompleteType() ||
16156              !Context.getTypeSizeInChars(FieldType).isZero())
16157            ZeroSize = false;
16158        }
16159      }
16160
16161      // Empty structs are an extension in C (C99 6.7.2.1p7). They are
16162      // allowed in C++, but warn if its declaration is inside
16163      // extern "C" block.
16164      if (ZeroSize) {
16165        Diag(RecLoc, getLangOpts().CPlusPlus ?
16166                         diag::warn_zero_size_struct_union_in_extern_c :
16167                         diag::warn_zero_size_struct_union_compat)
16168          << IsEmpty << Record->isUnion() << (NonBitFields > 1);
16169      }
16170
16171      // Structs without named members are extension in C (C99 6.7.2.1p7),
16172      // but are accepted by GCC.
16173      if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
16174        Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
16175                               diag::ext_no_named_members_in_struct_union)
16176          << Record->isUnion();
16177      }
16178    }
16179  } else {
16180    ObjCIvarDecl **ClsFields =
16181      reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
16182    if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
16183      ID->setEndOfDefinitionLoc(RBrac);
16184      // Add ivar's to class's DeclContext.
16185      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16186        ClsFields[i]->setLexicalDeclContext(ID);
16187        ID->addDecl(ClsFields[i]);
16188      }
16189      // Must enforce the rule that ivars in the base classes may not be
16190      // duplicates.
16191      if (ID->getSuperClass())
16192        DiagnoseDuplicateIvars(ID, ID->getSuperClass());
16193    } else if (ObjCImplementationDecl *IMPDecl =
16194                  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
16195       (0) . __assert_fail ("IMPDecl && \"ActOnFields - missing ObjCImplementationDecl\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 16195, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
16196      for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
16197        // Ivar declared in @implementation never belongs to the implementation.
16198        // Only it is in implementation's lexical context.
16199        ClsFields[I]->setLexicalDeclContext(IMPDecl);
16200      CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
16201      IMPDecl->setIvarLBraceLoc(LBrac);
16202      IMPDecl->setIvarRBraceLoc(RBrac);
16203    } else if (ObjCCategoryDecl *CDecl =
16204                dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
16205      // case of ivars in class extension; all other cases have been
16206      // reported as errors elsewhere.
16207      // FIXME. Class extension does not have a LocEnd field.
16208      // CDecl->setLocEnd(RBrac);
16209      // Add ivar's to class extension's DeclContext.
16210      // Diagnose redeclaration of private ivars.
16211      ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
16212      for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
16213        if (IDecl) {
16214          if (const ObjCIvarDecl *ClsIvar =
16215              IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
16216            Diag(ClsFields[i]->getLocation(),
16217                 diag::err_duplicate_ivar_declaration);
16218            Diag(ClsIvar->getLocation(), diag::note_previous_definition);
16219            continue;
16220          }
16221          for (const auto *Ext : IDecl->known_extensions()) {
16222            if (const ObjCIvarDecl *ClsExtIvar
16223                  = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
16224              Diag(ClsFields[i]->getLocation(),
16225                   diag::err_duplicate_ivar_declaration);
16226              Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
16227              continue;
16228            }
16229          }
16230        }
16231        ClsFields[i]->setLexicalDeclContext(CDecl);
16232        CDecl->addDecl(ClsFields[i]);
16233      }
16234      CDecl->setIvarLBraceLoc(LBrac);
16235      CDecl->setIvarRBraceLoc(RBrac);
16236    }
16237  }
16238}
16239
16240/// Determine whether the given integral value is representable within
16241/// the given type T.
16242static bool isRepresentableIntegerValue(ASTContext &Context,
16243                                        llvm::APSInt &Value,
16244                                        QualType T) {
16245   (0) . __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 16246, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
16246 (0) . __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 16246, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "Integral type required!");
16247  unsigned BitWidth = Context.getIntWidth(T);
16248
16249  if (Value.isUnsigned() || Value.isNonNegative()) {
16250    if (T->isSignedIntegerOrEnumerationType())
16251      --BitWidth;
16252    return Value.getActiveBits() <= BitWidth;
16253  }
16254  return Value.getMinSignedBits() <= BitWidth;
16255}
16256
16257// Given an integral type, return the next larger integral type
16258// (or a NULL type of no such type exists).
16259static QualType getNextLargerIntegralType(ASTContext &ContextQualType T) {
16260  // FIXME: Int128/UInt128 support, which also needs to be introduced into
16261  // enum checking below.
16262   (0) . __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 16263, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert((T->isIntegralType(Context) ||
16263 (0) . __assert_fail ("(T->isIntegralType(Context) || T->isEnumeralType()) && \"Integral type required!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 16263, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         T->isEnumeralType()) && "Integral type required!");
16264  const unsigned NumTypes = 4;
16265  QualType SignedIntegralTypes[NumTypes] = {
16266    Context.ShortTyContext.IntTyContext.LongTyContext.LongLongTy
16267  };
16268  QualType UnsignedIntegralTypes[NumTypes] = {
16269    Context.UnsignedShortTyContext.UnsignedIntTyContext.UnsignedLongTy,
16270    Context.UnsignedLongLongTy
16271  };
16272
16273  unsigned BitWidth = Context.getTypeSize(T);
16274  QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
16275                                                        : UnsignedIntegralTypes;
16276  for (unsigned I = 0I != NumTypes; ++I)
16277    if (Context.getTypeSize(Types[I]) > BitWidth)
16278      return Types[I];
16279
16280  return QualType();
16281}
16282
16283EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
16284                                          EnumConstantDecl *LastEnumConst,
16285                                          SourceLocation IdLoc,
16286                                          IdentifierInfo *Id,
16287                                          Expr *Val) {
16288  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16289  llvm::APSInt EnumVal(IntWidth);
16290  QualType EltTy;
16291
16292  if (Val && DiagnoseUnexpandedParameterPack(ValUPPC_EnumeratorValue))
16293    Val = nullptr;
16294
16295  if (Val)
16296    Val = DefaultLvalueConversion(Val).get();
16297
16298  if (Val) {
16299    if (Enum->isDependentType() || Val->isTypeDependent())
16300      EltTy = Context.DependentTy;
16301    else {
16302      if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
16303          !getLangOpts().MSVCCompat) {
16304        // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
16305        // constant-expression in the enumerator-definition shall be a converted
16306        // constant expression of the underlying type.
16307        EltTy = Enum->getIntegerType();
16308        ExprResult Converted =
16309          CheckConvertedConstantExpression(Val, EltTy, EnumVal,
16310                                           CCEK_Enumerator);
16311        if (Converted.isInvalid())
16312          Val = nullptr;
16313        else
16314          Val = Converted.get();
16315      } else if (!Val->isValueDependent() &&
16316                 !(Val = VerifyIntegerConstantExpression(Val,
16317                                                         &EnumVal).get())) {
16318        // C99 6.7.2.2p2: Make sure we have an integer constant expression.
16319      } else {
16320        if (Enum->isComplete()) {
16321          EltTy = Enum->getIntegerType();
16322
16323          // In Obj-C and Microsoft mode, require the enumeration value to be
16324          // representable in the underlying type of the enumeration. In C++11,
16325          // we perform a non-narrowing conversion as part of converted constant
16326          // expression checking.
16327          if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16328            if (getLangOpts().MSVCCompat) {
16329              Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
16330              Val = ImpCastExprToType(ValEltTyCK_IntegralCast).get();
16331            } else
16332              Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
16333          } else
16334            Val = ImpCastExprToType(ValEltTy,
16335                                    EltTy->isBooleanType() ?
16336                                    CK_IntegralToBoolean : CK_IntegralCast)
16337                    .get();
16338        } else if (getLangOpts().CPlusPlus) {
16339          // C++11 [dcl.enum]p5:
16340          //   If the underlying type is not fixed, the type of each enumerator
16341          //   is the type of its initializing value:
16342          //     - If an initializer is specified for an enumerator, the
16343          //       initializing value has the same type as the expression.
16344          EltTy = Val->getType();
16345        } else {
16346          // C99 6.7.2.2p2:
16347          //   The expression that defines the value of an enumeration constant
16348          //   shall be an integer constant expression that has a value
16349          //   representable as an int.
16350
16351          // Complain if the value is not representable in an int.
16352          if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
16353            Diag(IdLoc, diag::ext_enum_value_not_int)
16354              << EnumVal.toString(10) << Val->getSourceRange()
16355              << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
16356          else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
16357            // Force the type of the expression to 'int'.
16358            Val = ImpCastExprToType(ValContext.IntTyCK_IntegralCast).get();
16359          }
16360          EltTy = Val->getType();
16361        }
16362      }
16363    }
16364  }
16365
16366  if (!Val) {
16367    if (Enum->isDependentType())
16368      EltTy = Context.DependentTy;
16369    else if (!LastEnumConst) {
16370      // C++0x [dcl.enum]p5:
16371      //   If the underlying type is not fixed, the type of each enumerator
16372      //   is the type of its initializing value:
16373      //     - If no initializer is specified for the first enumerator, the
16374      //       initializing value has an unspecified integral type.
16375      //
16376      // GCC uses 'int' for its unspecified integral type, as does
16377      // C99 6.7.2.2p3.
16378      if (Enum->isFixed()) {
16379        EltTy = Enum->getIntegerType();
16380      }
16381      else {
16382        EltTy = Context.IntTy;
16383      }
16384    } else {
16385      // Assign the last value + 1.
16386      EnumVal = LastEnumConst->getInitVal();
16387      ++EnumVal;
16388      EltTy = LastEnumConst->getType();
16389
16390      // Check for overflow on increment.
16391      if (EnumVal < LastEnumConst->getInitVal()) {
16392        // C++0x [dcl.enum]p5:
16393        //   If the underlying type is not fixed, the type of each enumerator
16394        //   is the type of its initializing value:
16395        //
16396        //     - Otherwise the type of the initializing value is the same as
16397        //       the type of the initializing value of the preceding enumerator
16398        //       unless the incremented value is not representable in that type,
16399        //       in which case the type is an unspecified integral type
16400        //       sufficient to contain the incremented value. If no such type
16401        //       exists, the program is ill-formed.
16402        QualType T = getNextLargerIntegralType(ContextEltTy);
16403        if (T.isNull() || Enum->isFixed()) {
16404          // There is no integral type larger enough to represent this
16405          // value. Complain, then allow the value to wrap around.
16406          EnumVal = LastEnumConst->getInitVal();
16407          EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
16408          ++EnumVal;
16409          if (Enum->isFixed())
16410            // When the underlying type is fixed, this is ill-formed.
16411            Diag(IdLoc, diag::err_enumerator_wrapped)
16412              << EnumVal.toString(10)
16413              << EltTy;
16414          else
16415            Diag(IdLoc, diag::ext_enumerator_increment_too_large)
16416              << EnumVal.toString(10);
16417        } else {
16418          EltTy = T;
16419        }
16420
16421        // Retrieve the last enumerator's value, extent that type to the
16422        // type that is supposed to be large enough to represent the incremented
16423        // value, then increment.
16424        EnumVal = LastEnumConst->getInitVal();
16425        EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16426        EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
16427        ++EnumVal;
16428
16429        // If we're not in C++, diagnose the overflow of enumerator values,
16430        // which in C99 means that the enumerator value is not representable in
16431        // an int (C99 6.7.2.2p2). However, we support GCC's extension that
16432        // permits enumerator values that are representable in some larger
16433        // integral type.
16434        if (!getLangOpts().CPlusPlus && !T.isNull())
16435          Diag(IdLoc, diag::warn_enum_value_overflow);
16436      } else if (!getLangOpts().CPlusPlus &&
16437                 !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
16438        // Enforce C99 6.7.2.2p2 even when we compute the next value.
16439        Diag(IdLoc, diag::ext_enum_value_not_int)
16440          << EnumVal.toString(10) << 1;
16441      }
16442    }
16443  }
16444
16445  if (!EltTy->isDependentType()) {
16446    // Make the enumerator value match the signedness and size of the
16447    // enumerator's type.
16448    EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
16449    EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
16450  }
16451
16452  return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
16453                                  Val, EnumVal);
16454}
16455
16456Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *SIdentifierInfo *II,
16457                                                SourceLocation IILoc) {
16458  if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
16459      !getLangOpts().CPlusPlus)
16460    return SkipBodyInfo();
16461
16462  // We have an anonymous enum definition. Look up the first enumerator to
16463  // determine if we should merge the definition with an existing one and
16464  // skip the body.
16465  NamedDecl *PrevDecl = LookupSingleName(SIIIILocLookupOrdinaryName,
16466                                         forRedeclarationInCurContext());
16467  auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
16468  if (!PrevECD)
16469    return SkipBodyInfo();
16470
16471  EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
16472  NamedDecl *Hidden;
16473  if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
16474    SkipBodyInfo Skip;
16475    Skip.Previous = Hidden;
16476    return Skip;
16477  }
16478
16479  return SkipBodyInfo();
16480}
16481
16482Decl *Sema::ActOnEnumConstant(Scope *SDecl *theEnumDeclDecl *lastEnumConst,
16483                              SourceLocation IdLocIdentifierInfo *Id,
16484                              const ParsedAttributesView &Attrs,
16485                              SourceLocation EqualLocExpr *Val) {
16486  EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
16487  EnumConstantDecl *LastEnumConst =
16488    cast_or_null<EnumConstantDecl>(lastEnumConst);
16489
16490  // The scope passed in may not be a decl scope.  Zip up the scope tree until
16491  // we find one that is.
16492  S = getNonFieldDeclScope(S);
16493
16494  // Verify that there isn't already something declared with this name in this
16495  // scope.
16496  LookupResult R(*thisIdIdLocLookupOrdinaryNameForVisibleRedeclaration);
16497  LookupName(RS);
16498  NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
16499
16500  if (PrevDecl && PrevDecl->isTemplateParameter()) {
16501    // Maybe we will complain about the shadowed template parameter.
16502    DiagnoseTemplateParameterShadow(IdLocPrevDecl);
16503    // Just pretend that we didn't see the previous declaration.
16504    PrevDecl = nullptr;
16505  }
16506
16507  // C++ [class.mem]p15:
16508  // If T is the name of a class, then each of the following shall have a name
16509  // different from T:
16510  // - every enumerator of every member of class T that is an unscoped
16511  // enumerated type
16512  if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
16513    DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
16514                            DeclarationNameInfo(IdIdLoc));
16515
16516  EnumConstantDecl *New =
16517    CheckEnumConstant(TheEnumDeclLastEnumConstIdLocIdVal);
16518  if (!New)
16519    return nullptr;
16520
16521  if (PrevDecl) {
16522    if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
16523      // Check for other kinds of shadowing not already handled.
16524      CheckShadow(NewPrevDeclR);
16525    }
16526
16527    // When in C++, we may get a TagDecl with the same name; in this case the
16528    // enum constant will 'hide' the tag.
16529     (0) . __assert_fail ("(getLangOpts().CPlusPlus || !isa(PrevDecl)) && \"Received TagDecl when not in C++!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 16530, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
16530 (0) . __assert_fail ("(getLangOpts().CPlusPlus || !isa(PrevDecl)) && \"Received TagDecl when not in C++!\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 16530, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           "Received TagDecl when not in C++!");
16531    if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
16532      if (isa<EnumConstantDecl>(PrevDecl))
16533        Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
16534      else
16535        Diag(IdLoc, diag::err_redefinition) << Id;
16536      notePreviousDefinition(PrevDeclIdLoc);
16537      return nullptr;
16538    }
16539  }
16540
16541  // Process attributes.
16542  ProcessDeclAttributeList(SNewAttrs);
16543  AddPragmaAttributes(SNew);
16544
16545  // Register this decl in the current scope stack.
16546  New->setAccess(TheEnumDecl->getAccess());
16547  PushOnScopeChains(NewS);
16548
16549  ActOnDocumentableDecl(New);
16550
16551  return New;
16552}
16553
16554// Returns true when the enum initial expression does not trigger the
16555// duplicate enum warning.  A few common cases are exempted as follows:
16556// Element2 = Element1
16557// Element2 = Element1 + 1
16558// Element2 = Element1 - 1
16559// Where Element2 and Element1 are from the same enum.
16560static bool ValidDuplicateEnum(EnumConstantDecl *ECDEnumDecl *Enum) {
16561  Expr *InitExpr = ECD->getInitExpr();
16562  if (!InitExpr)
16563    return true;
16564  InitExpr = InitExpr->IgnoreImpCasts();
16565
16566  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
16567    if (!BO->isAdditiveOp())
16568      return true;
16569    IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
16570    if (!IL)
16571      return true;
16572    if (IL->getValue() != 1)
16573      return true;
16574
16575    InitExpr = BO->getLHS();
16576  }
16577
16578  // This checks if the elements are from the same enum.
16579  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
16580  if (!DRE)
16581    return true;
16582
16583  EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
16584  if (!EnumConstant)
16585    return true;
16586
16587  if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
16588      Enum)
16589    return true;
16590
16591  return false;
16592}
16593
16594// Emits a warning when an element is implicitly set a value that
16595// a previous element has already been set to.
16596static void CheckForDuplicateEnumValues(Sema &SArrayRef<Decl *> Elements,
16597                                        EnumDecl *EnumQualType EnumType) {
16598  // Avoid anonymous enums
16599  if (!Enum->getIdentifier())
16600    return;
16601
16602  // Only check for small enums.
16603  if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
16604    return;
16605
16606  if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
16607    return;
16608
16609  typedef SmallVector<EnumConstantDecl *, 3ECDVector;
16610  typedef SmallVector<std::unique_ptr<ECDVector>, 3DuplicatesVector;
16611
16612  typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
16613  typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
16614
16615  // Use int64_t as a key to avoid needing special handling for DenseMap keys.
16616  auto EnumConstantToKey = [](const EnumConstantDecl *D) {
16617    llvm::APSInt Val = D->getInitVal();
16618    return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
16619  };
16620
16621  DuplicatesVector DupVector;
16622  ValueToVectorMap EnumMap;
16623
16624  // Populate the EnumMap with all values represented by enum constants without
16625  // an initializer.
16626  for (auto *Element : Elements) {
16627    EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
16628
16629    // Null EnumConstantDecl means a previous diagnostic has been emitted for
16630    // this constant.  Skip this enum since it may be ill-formed.
16631    if (!ECD) {
16632      return;
16633    }
16634
16635    // Constants with initalizers are handled in the next loop.
16636    if (ECD->getInitExpr())
16637      continue;
16638
16639    // Duplicate values are handled in the next loop.
16640    EnumMap.insert({EnumConstantToKey(ECD), ECD});
16641  }
16642
16643  if (EnumMap.size() == 0)
16644    return;
16645
16646  // Create vectors for any values that has duplicates.
16647  for (auto *Element : Elements) {
16648    // The last loop returned if any constant was null.
16649    EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
16650    if (!ValidDuplicateEnum(ECD, Enum))
16651      continue;
16652
16653    auto Iter = EnumMap.find(EnumConstantToKey(ECD));
16654    if (Iter == EnumMap.end())
16655      continue;
16656
16657    DeclOrVector& Entry = Iter->second;
16658    if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
16659      // Ensure constants are different.
16660      if (D == ECD)
16661        continue;
16662
16663      // Create new vector and push values onto it.
16664      auto Vec = llvm::make_unique<ECDVector>();
16665      Vec->push_back(D);
16666      Vec->push_back(ECD);
16667
16668      // Update entry to point to the duplicates vector.
16669      Entry = Vec.get();
16670
16671      // Store the vector somewhere we can consult later for quick emission of
16672      // diagnostics.
16673      DupVector.emplace_back(std::move(Vec));
16674      continue;
16675    }
16676
16677    ECDVector *Vec = Entry.get<ECDVector*>();
16678    // Make sure constants are not added more than once.
16679    if (*Vec->begin() == ECD)
16680      continue;
16681
16682    Vec->push_back(ECD);
16683  }
16684
16685  // Emit diagnostics.
16686  for (const auto &Vec : DupVector) {
16687     (0) . __assert_fail ("Vec->size() > 1 && \"ECDVector should have at least 2 elements.\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 16687, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
16688
16689    // Emit warning for one enum constant.
16690    auto *FirstECD = Vec->front();
16691    S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
16692      << FirstECD << FirstECD->getInitVal().toString(10)
16693      << FirstECD->getSourceRange();
16694
16695    // Emit one note for each of the remaining enum constants with
16696    // the same value.
16697    for (auto *ECD : llvm::make_range(Vec->begin() + 1, Vec->end()))
16698      S.Diag(ECD->getLocation(), diag::note_duplicate_element)
16699        << ECD << ECD->getInitVal().toString(10)
16700        << ECD->getSourceRange();
16701  }
16702}
16703
16704bool Sema::IsValueInFlagEnum(const EnumDecl *EDconst llvm::APInt &Val,
16705                             bool AllowMaskconst {
16706   (0) . __assert_fail ("ED->isClosedFlag() && \"looking for value in non-flag or open enum\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 16706, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
16707   (0) . __assert_fail ("ED->isCompleteDefinition() && \"expected enum definition\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 16707, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(ED->isCompleteDefinition() && "expected enum definition");
16708
16709  auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
16710  llvm::APInt &FlagBits = R.first->second;
16711
16712  if (R.second) {
16713    for (auto *E : ED->enumerators()) {
16714      const auto &EVal = E->getInitVal();
16715      // Only single-bit enumerators introduce new flag values.
16716      if (EVal.isPowerOf2())
16717        FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
16718    }
16719  }
16720
16721  // A value is in a flag enum if either its bits are a subset of the enum's
16722  // flag bits (the first condition) or we are allowing masks and the same is
16723  // true of its complement (the second condition). When masks are allowed, we
16724  // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
16725  //
16726  // While it's true that any value could be used as a mask, the assumption is
16727  // that a mask will have all of the insignificant bits set. Anything else is
16728  // likely a logic error.
16729  llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
16730  return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
16731}
16732
16733void Sema::ActOnEnumBody(SourceLocation EnumLocSourceRange BraceRange,
16734                         Decl *EnumDeclXArrayRef<Decl *> ElementsScope *S,
16735                         const ParsedAttributesView &Attrs) {
16736  EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
16737  QualType EnumType = Context.getTypeDeclType(Enum);
16738
16739  ProcessDeclAttributeList(SEnumAttrs);
16740
16741  if (Enum->isDependentType()) {
16742    for (unsigned i = 0e = Elements.size(); i != e; ++i) {
16743      EnumConstantDecl *ECD =
16744        cast_or_null<EnumConstantDecl>(Elements[i]);
16745      if (!ECDcontinue;
16746
16747      ECD->setType(EnumType);
16748    }
16749
16750    Enum->completeDefinition(Context.DependentTyContext.DependentTy00);
16751    return;
16752  }
16753
16754  // TODO: If the result value doesn't fit in an int, it must be a long or long
16755  // long value.  ISO C does not support this, but GCC does as an extension,
16756  // emit a warning.
16757  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
16758  unsigned CharWidth = Context.getTargetInfo().getCharWidth();
16759  unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
16760
16761  // Verify that all the values are okay, compute the size of the values, and
16762  // reverse the list.
16763  unsigned NumNegativeBits = 0;
16764  unsigned NumPositiveBits = 0;
16765
16766  // Keep track of whether all elements have type int.
16767  bool AllElementsInt = true;
16768
16769  for (unsigned i = 0e = Elements.size(); i != e; ++i) {
16770    EnumConstantDecl *ECD =
16771      cast_or_null<EnumConstantDecl>(Elements[i]);
16772    if (!ECDcontinue;  // Already issued a diagnostic.
16773
16774    const llvm::APSInt &InitVal = ECD->getInitVal();
16775
16776    // Keep track of the size of positive and negative values.
16777    if (InitVal.isUnsigned() || InitVal.isNonNegative())
16778      NumPositiveBits = std::max(NumPositiveBits,
16779                                 (unsigned)InitVal.getActiveBits());
16780    else
16781      NumNegativeBits = std::max(NumNegativeBits,
16782                                 (unsigned)InitVal.getMinSignedBits());
16783
16784    // Keep track of whether every enum element has type int (very common).
16785    if (AllElementsInt)
16786      AllElementsInt = ECD->getType() == Context.IntTy;
16787  }
16788
16789  // Figure out the type that should be used for this enum.
16790  QualType BestType;
16791  unsigned BestWidth;
16792
16793  // C++0x N3000 [conv.prom]p3:
16794  //   An rvalue of an unscoped enumeration type whose underlying
16795  //   type is not fixed can be converted to an rvalue of the first
16796  //   of the following types that can represent all the values of
16797  //   the enumeration: int, unsigned int, long int, unsigned long
16798  //   int, long long int, or unsigned long long int.
16799  // C99 6.4.4.3p2:
16800  //   An identifier declared as an enumeration constant has type int.
16801  // The C99 rule is modified by a gcc extension
16802  QualType BestPromotionType;
16803
16804  bool Packed = Enum->hasAttr<PackedAttr>();
16805  // -fshort-enums is the equivalent to specifying the packed attribute on all
16806  // enum definitions.
16807  if (LangOpts.ShortEnums)
16808    Packed = true;
16809
16810  // If the enum already has a type because it is fixed or dictated by the
16811  // target, promote that type instead of analyzing the enumerators.
16812  if (Enum->isComplete()) {
16813    BestType = Enum->getIntegerType();
16814    if (BestType->isPromotableIntegerType())
16815      BestPromotionType = Context.getPromotedIntegerType(BestType);
16816    else
16817      BestPromotionType = BestType;
16818
16819    BestWidth = Context.getIntWidth(BestType);
16820  }
16821  else if (NumNegativeBits) {
16822    // If there is a negative value, figure out the smallest integer type (of
16823    // int/long/longlong) that fits.
16824    // If it's packed, check also if it fits a char or a short.
16825    if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
16826      BestType = Context.SignedCharTy;
16827      BestWidth = CharWidth;
16828    } else if (Packed && NumNegativeBits <= ShortWidth &&
16829               NumPositiveBits < ShortWidth) {
16830      BestType = Context.ShortTy;
16831      BestWidth = ShortWidth;
16832    } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
16833      BestType = Context.IntTy;
16834      BestWidth = IntWidth;
16835    } else {
16836      BestWidth = Context.getTargetInfo().getLongWidth();
16837
16838      if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
16839        BestType = Context.LongTy;
16840      } else {
16841        BestWidth = Context.getTargetInfo().getLongLongWidth();
16842
16843        if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
16844          Diag(Enum->getLocation(), diag::ext_enum_too_large);
16845        BestType = Context.LongLongTy;
16846      }
16847    }
16848    BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
16849  } else {
16850    // If there is no negative value, figure out the smallest type that fits
16851    // all of the enumerator values.
16852    // If it's packed, check also if it fits a char or a short.
16853    if (Packed && NumPositiveBits <= CharWidth) {
16854      BestType = Context.UnsignedCharTy;
16855      BestPromotionType = Context.IntTy;
16856      BestWidth = CharWidth;
16857    } else if (Packed && NumPositiveBits <= ShortWidth) {
16858      BestType = Context.UnsignedShortTy;
16859      BestPromotionType = Context.IntTy;
16860      BestWidth = ShortWidth;
16861    } else if (NumPositiveBits <= IntWidth) {
16862      BestType = Context.UnsignedIntTy;
16863      BestWidth = IntWidth;
16864      BestPromotionType
16865        = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16866                           ? Context.UnsignedIntTy : Context.IntTy;
16867    } else if (NumPositiveBits <=
16868               (BestWidth = Context.getTargetInfo().getLongWidth())) {
16869      BestType = Context.UnsignedLongTy;
16870      BestPromotionType
16871        = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16872                           ? Context.UnsignedLongTy : Context.LongTy;
16873    } else {
16874      BestWidth = Context.getTargetInfo().getLongLongWidth();
16875       (0) . __assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 16876, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(NumPositiveBits <= BestWidth &&
16876 (0) . __assert_fail ("NumPositiveBits <= BestWidth && \"How could an initializer get larger than ULL?\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 16876, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">             "How could an initializer get larger than ULL?");
16877      BestType = Context.UnsignedLongLongTy;
16878      BestPromotionType
16879        = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
16880                           ? Context.UnsignedLongLongTy : Context.LongLongTy;
16881    }
16882  }
16883
16884  // Loop over all of the enumerator constants, changing their types to match
16885  // the type of the enum if needed.
16886  for (auto *D : Elements) {
16887    auto *ECD = cast_or_null<EnumConstantDecl>(D);
16888    if (!ECD) continue;  // Already issued a diagnostic.
16889
16890    // Standard C says the enumerators have int type, but we allow, as an
16891    // extension, the enumerators to be larger than int size.  If each
16892    // enumerator value fits in an int, type it as an int, otherwise type it the
16893    // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
16894    // that X has type 'int', not 'unsigned'.
16895
16896    // Determine whether the value fits into an int.
16897    llvm::APSInt InitVal = ECD->getInitVal();
16898
16899    // If it fits into an integer type, force it.  Otherwise force it to match
16900    // the enum decl type.
16901    QualType NewTy;
16902    unsigned NewWidth;
16903    bool NewSign;
16904    if (!getLangOpts().CPlusPlus &&
16905        !Enum->isFixed() &&
16906        isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
16907      NewTy = Context.IntTy;
16908      NewWidth = IntWidth;
16909      NewSign = true;
16910    } else if (ECD->getType() == BestType) {
16911      // Already the right type!
16912      if (getLangOpts().CPlusPlus)
16913        // C++ [dcl.enum]p4: Following the closing brace of an
16914        // enum-specifier, each enumerator has the type of its
16915        // enumeration.
16916        ECD->setType(EnumType);
16917      continue;
16918    } else {
16919      NewTy = BestType;
16920      NewWidth = BestWidth;
16921      NewSign = BestType->isSignedIntegerOrEnumerationType();
16922    }
16923
16924    // Adjust the APSInt value.
16925    InitVal = InitVal.extOrTrunc(NewWidth);
16926    InitVal.setIsSigned(NewSign);
16927    ECD->setInitVal(InitVal);
16928
16929    // Adjust the Expr initializer and type.
16930    if (ECD->getInitExpr() &&
16931        !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
16932      ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
16933                                                CK_IntegralCast,
16934                                                ECD->getInitExpr(),
16935                                                /*base paths*/ nullptr,
16936                                                VK_RValue));
16937    if (getLangOpts().CPlusPlus)
16938      // C++ [dcl.enum]p4: Following the closing brace of an
16939      // enum-specifier, each enumerator has the type of its
16940      // enumeration.
16941      ECD->setType(EnumType);
16942    else
16943      ECD->setType(NewTy);
16944  }
16945
16946  Enum->completeDefinition(BestTypeBestPromotionType,
16947                           NumPositiveBitsNumNegativeBits);
16948
16949  CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
16950
16951  if (Enum->isClosedFlag()) {
16952    for (Decl *D : Elements) {
16953      EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
16954      if (!ECD) continue;  // Already issued a diagnostic.
16955
16956      llvm::APSInt InitVal = ECD->getInitVal();
16957      if (InitVal != 0 && !InitVal.isPowerOf2() &&
16958          !IsValueInFlagEnum(Enum, InitVal, true))
16959        Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
16960          << ECD << Enum;
16961    }
16962  }
16963
16964  // Now that the enum type is defined, ensure it's not been underaligned.
16965  if (Enum->hasAttrs())
16966    CheckAlignasUnderalignment(Enum);
16967}
16968
16969Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
16970                                  SourceLocation StartLoc,
16971                                  SourceLocation EndLoc) {
16972  StringLiteral *AsmString = cast<StringLiteral>(expr);
16973
16974  FileScopeAsmDecl *New = FileScopeAsmDecl::Create(ContextCurContext,
16975                                                   AsmStringStartLoc,
16976                                                   EndLoc);
16977  CurContext->addDecl(New);
16978  return New;
16979}
16980
16981static void checkModuleImportContext(Sema &SModule *M,
16982                                     SourceLocation ImportLocDeclContext *DC,
16983                                     bool FromInclude = false) {
16984  SourceLocation ExternCLoc;
16985
16986  if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
16987    switch (LSD->getLanguage()) {
16988    case LinkageSpecDecl::lang_c:
16989      if (ExternCLoc.isInvalid())
16990        ExternCLoc = LSD->getBeginLoc();
16991      break;
16992    case LinkageSpecDecl::lang_cxx:
16993      break;
16994    }
16995    DC = LSD->getParent();
16996  }
16997
16998  while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
16999    DC = DC->getParent();
17000
17001  if (!isa<TranslationUnitDecl>(DC)) {
17002    S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
17003                          ? diag::ext_module_import_not_at_top_level_noop
17004                          : diag::err_module_import_not_at_top_level_fatal)
17005        << M->getFullModuleName() << DC;
17006    S.Diag(cast<Decl>(DC)->getBeginLoc(),
17007           diag::note_module_import_not_at_top_level)
17008        << DC;
17009  } else if (!M->IsExternC && ExternCLoc.isValid()) {
17010    S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
17011      << M->getFullModuleName();
17012    S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
17013  }
17014}
17015
17016Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation StartLoc,
17017                                           SourceLocation ModuleLoc,
17018                                           ModuleDeclKind MDK,
17019                                           ModuleIdPath Path) {
17020   (0) . __assert_fail ("getLangOpts().ModulesTS && \"should only have module decl in modules TS\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 17021, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(getLangOpts().ModulesTS &&
17021 (0) . __assert_fail ("getLangOpts().ModulesTS && \"should only have module decl in modules TS\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 17021, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "should only have module decl in modules TS");
17022
17023  // A module implementation unit requires that we are not compiling a module
17024  // of any kind. A module interface unit requires that we are not compiling a
17025  // module map.
17026  switch (getLangOpts().getCompilingModule()) {
17027  case LangOptions::CMK_None:
17028    // It's OK to compile a module interface as a normal translation unit.
17029    break;
17030
17031  case LangOptions::CMK_ModuleInterface:
17032    if (MDK != ModuleDeclKind::Implementation)
17033      break;
17034
17035    // We were asked to compile a module interface unit but this is a module
17036    // implementation unit. That indicates the 'export' is missing.
17037    Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
17038      << FixItHint::CreateInsertion(ModuleLoc, "export ");
17039    MDK = ModuleDeclKind::Interface;
17040    break;
17041
17042  case LangOptions::CMK_ModuleMap:
17043    Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
17044    return nullptr;
17045
17046  case LangOptions::CMK_HeaderModule:
17047    Diag(ModuleLoc, diag::err_module_decl_in_header_module);
17048    return nullptr;
17049  }
17050
17051   (0) . __assert_fail ("ModuleScopes.size() == 1 && \"expected to be at global module scope\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 17051, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(ModuleScopes.size() == 1 && "expected to be at global module scope");
17052
17053  // FIXME: Most of this work should be done by the preprocessor rather than
17054  // here, in order to support macro import.
17055
17056  // Only one module-declaration is permitted per source file.
17057  if (ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) {
17058    Diag(ModuleLoc, diag::err_module_redeclaration);
17059    Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
17060         diag::note_prev_module_declaration);
17061    return nullptr;
17062  }
17063
17064  // Flatten the dots in a module name. Unlike Clang's hierarchical module map
17065  // modules, the dots here are just another character that can appear in a
17066  // module name.
17067  std::string ModuleName;
17068  for (auto &Piece : Path) {
17069    if (!ModuleName.empty())
17070      ModuleName += ".";
17071    ModuleName += Piece.first->getName();
17072  }
17073
17074  // If a module name was explicitly specified on the command line, it must be
17075  // correct.
17076  if (!getLangOpts().CurrentModule.empty() &&
17077      getLangOpts().CurrentModule != ModuleName) {
17078    Diag(Path.front().second, diag::err_current_module_name_mismatch)
17079        << SourceRange(Path.front().second, Path.back().second)
17080        << getLangOpts().CurrentModule;
17081    return nullptr;
17082  }
17083  const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
17084
17085  auto &Map = PP.getHeaderSearchInfo().getModuleMap();
17086  Module *Mod;
17087
17088  switch (MDK) {
17089  case ModuleDeclKind::Interface: {
17090    // We can't have parsed or imported a definition of this module or parsed a
17091    // module map defining it already.
17092    if (auto *M = Map.findModule(ModuleName)) {
17093      Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
17094      if (M->DefinitionLoc.isValid())
17095        Diag(M->DefinitionLoc, diag::note_prev_module_definition);
17096      else if (const auto *FE = M->getASTFile())
17097        Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
17098            << FE->getName();
17099      Mod = M;
17100      break;
17101    }
17102
17103    // Create a Module for the module that we're defining.
17104    Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
17105                                           ModuleScopes.front().Module);
17106     (0) . __assert_fail ("Mod && \"module creation should not fail\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 17106, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(Mod && "module creation should not fail");
17107    break;
17108  }
17109
17110  case ModuleDeclKind::Partition:
17111    // FIXME: Check we are in a submodule of the named module.
17112    return nullptr;
17113
17114  case ModuleDeclKind::Implementation:
17115    std::pair<IdentifierInfo *, SourceLocationModuleNameLoc(
17116        PP.getIdentifierInfo(ModuleName), Path[0].second);
17117    Mod = getModuleLoader().loadModule(ModuleLoc, {ModuleNameLoc},
17118                                       Module::AllVisible,
17119                                       /*IsIncludeDirective=*/false);
17120    if (!Mod) {
17121      Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
17122      // Create an empty module interface unit for error recovery.
17123      Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
17124                                             ModuleScopes.front().Module);
17125    }
17126    break;
17127  }
17128
17129  // Switch from the global module to the named module.
17130  ModuleScopes.back().Module = Mod;
17131  ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
17132  VisibleModules.setVisible(ModModuleLoc);
17133
17134  // From now on, we have an owning module for all declarations we see.
17135  // However, those declarations are module-private unless explicitly
17136  // exported.
17137  auto *TU = Context.getTranslationUnitDecl();
17138  TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
17139  TU->setLocalOwningModule(Mod);
17140
17141  // FIXME: Create a ModuleDecl.
17142  return nullptr;
17143}
17144
17145DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
17146                                   SourceLocation ImportLoc,
17147                                   ModuleIdPath Path) {
17148  // Flatten the module path for a Modules TS module name.
17149  std::pair<IdentifierInfo *, SourceLocationModuleNameLoc;
17150  if (getLangOpts().ModulesTS) {
17151    std::string ModuleName;
17152    for (auto &Piece : Path) {
17153      if (!ModuleName.empty())
17154        ModuleName += ".";
17155      ModuleName += Piece.first->getName();
17156    }
17157    ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
17158    Path = ModuleIdPath(ModuleNameLoc);
17159  }
17160
17161  Module *Mod =
17162      getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
17163                                   /*IsIncludeDirective=*/false);
17164  if (!Mod)
17165    return true;
17166
17167  VisibleModules.setVisible(ModImportLoc);
17168
17169  checkModuleImportContext(*thisModImportLocCurContext);
17170
17171  // FIXME: we should support importing a submodule within a different submodule
17172  // of the same top-level module. Until we do, make it an error rather than
17173  // silently ignoring the import.
17174  // Import-from-implementation is valid in the Modules TS. FIXME: Should we
17175  // warn on a redundant import of the current module?
17176  if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
17177      (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
17178    Diag(ImportLoc, getLangOpts().isCompilingModule()
17179                        ? diag::err_module_self_import
17180                        : diag::err_module_import_in_implementation)
17181        << Mod->getFullModuleName() << getLangOpts().CurrentModule;
17182
17183  SmallVector<SourceLocation2IdentifierLocs;
17184  Module *ModCheck = Mod;
17185  for (unsigned I = 0N = Path.size(); I != N; ++I) {
17186    // If we've run out of module parents, just drop the remaining identifiers.
17187    // We need the length to be consistent.
17188    if (!ModCheck)
17189      break;
17190    ModCheck = ModCheck->Parent;
17191
17192    IdentifierLocs.push_back(Path[I].second);
17193  }
17194
17195  ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
17196                                          Mod, IdentifierLocs);
17197  if (!ModuleScopes.empty())
17198    Context.addModuleInitializer(ModuleScopes.back().Module, Import);
17199  CurContext->addDecl(Import);
17200
17201  // Re-export the module if needed.
17202  if (Import->isExported() &&
17203      !ModuleScopes.empty() && ModuleScopes.back().ModuleInterface)
17204    getCurrentModule()->Exports.emplace_back(Modfalse);
17205
17206  return Import;
17207}
17208
17209void Sema::ActOnModuleInclude(SourceLocation DirectiveLocModule *Mod) {
17210  checkModuleImportContext(*thisModDirectiveLocCurContexttrue);
17211  BuildModuleInclude(DirectiveLocMod);
17212}
17213
17214void Sema::BuildModuleInclude(SourceLocation DirectiveLocModule *Mod) {
17215  // Determine whether we're in the #include buffer for a module. The #includes
17216  // in that buffer do not qualify as module imports; they're just an
17217  // implementation detail of us building the module.
17218  //
17219  // FIXME: Should we even get ActOnModuleInclude calls for those?
17220  bool IsInModuleIncludes =
17221      TUKind == TU_Module &&
17222      getSourceManager().isWrittenInMainFile(DirectiveLoc);
17223
17224  bool ShouldAddImport = !IsInModuleIncludes;
17225
17226  // If this module import was due to an inclusion directive, create an
17227  // implicit import declaration to capture it in the AST.
17228  if (ShouldAddImport) {
17229    TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
17230    ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
17231                                                     DirectiveLocMod,
17232                                                     DirectiveLoc);
17233    if (!ModuleScopes.empty())
17234      Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
17235    TU->addDecl(ImportD);
17236    Consumer.HandleImplicitImportDecl(ImportD);
17237  }
17238
17239  getModuleLoader().makeModuleVisible(ModModule::AllVisibleDirectiveLoc);
17240  VisibleModules.setVisible(ModDirectiveLoc);
17241}
17242
17243void Sema::ActOnModuleBegin(SourceLocation DirectiveLocModule *Mod) {
17244  checkModuleImportContext(*thisModDirectiveLocCurContexttrue);
17245
17246  ModuleScopes.push_back({});
17247  ModuleScopes.back().Module = Mod;
17248  if (getLangOpts().ModulesLocalVisibility)
17249    ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
17250
17251  VisibleModules.setVisible(ModDirectiveLoc);
17252
17253  // The enclosing context is now part of this module.
17254  // FIXME: Consider creating a child DeclContext to hold the entities
17255  // lexically within the module.
17256  if (getLangOpts().trackLocalOwningModule()) {
17257    for (auto *DC = CurContextDCDC = DC->getLexicalParent()) {
17258      cast<Decl>(DC)->setModuleOwnershipKind(
17259          getLangOpts().ModulesLocalVisibility
17260              ? Decl::ModuleOwnershipKind::VisibleWhenImported
17261              : Decl::ModuleOwnershipKind::Visible);
17262      cast<Decl>(DC)->setLocalOwningModule(Mod);
17263    }
17264  }
17265}
17266
17267void Sema::ActOnModuleEnd(SourceLocation EomLocModule *Mod) {
17268  if (getLangOpts().ModulesLocalVisibility) {
17269    VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
17270    // Leaving a module hides namespace names, so our visible namespace cache
17271    // is now out of date.
17272    VisibleNamespaceCache.clear();
17273  }
17274
17275   (0) . __assert_fail ("!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && \"left the wrong module scope\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 17276, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
17276 (0) . __assert_fail ("!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && \"left the wrong module scope\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 17276, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">         "left the wrong module scope");
17277  ModuleScopes.pop_back();
17278
17279  // We got to the end of processing a local module. Create an
17280  // ImportDecl as we would for an imported module.
17281  FileID File = getSourceManager().getFileID(EomLoc);
17282  SourceLocation DirectiveLoc;
17283  if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
17284    // We reached the end of a #included module header. Use the #include loc.
17285     (0) . __assert_fail ("File != getSourceManager().getMainFileID() && \"end of submodule in main source file\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 17286, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">assert(File != getSourceManager().getMainFileID() &&
17286 (0) . __assert_fail ("File != getSourceManager().getMainFileID() && \"end of submodule in main source file\"", "/home/seafit/code_projects/clang_source/clang/lib/Sema/SemaDecl.cpp", 17286, __PRETTY_FUNCTION__))" file_link="../../../include/assert.h.html#88" macro="true">           "end of submodule in main source file");
17287    DirectiveLoc = getSourceManager().getIncludeLoc(File);
17288  } else {
17289    // We reached an EOM pragma. Use the pragma location.
17290    DirectiveLoc = EomLoc;
17291  }
17292  BuildModuleInclude(DirectiveLocMod);
17293
17294  // Any further declarations are in whatever module we returned to.
17295  if (getLangOpts().trackLocalOwningModule()) {
17296    // The parser guarantees that this is the same context that we entered
17297    // the module within.
17298    for (auto *DC = CurContextDCDC = DC->getLexicalParent()) {
17299      cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
17300      if (!getCurrentModule())
17301        cast<Decl>(DC)->setModuleOwnershipKind(
17302            Decl::ModuleOwnershipKind::Unowned);
17303    }
17304  }
17305}
17306
17307void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
17308                                                      Module *Mod) {
17309  // Bail if we're not allowed to implicitly import a module here.
17310  if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
17311      VisibleModules.isVisible(Mod))
17312    return;
17313
17314  // Create the implicit import declaration.
17315  TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
17316  ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
17317                                                   LocModLoc);
17318  TU->addDecl(ImportD);
17319  Consumer.HandleImplicitImportDecl(ImportD);
17320
17321  // Make the module visible.
17322  getModuleLoader().makeModuleVisible(ModModule::AllVisibleLoc);
17323  VisibleModules.setVisible(ModLoc);
17324}
17325
17326/// We have parsed the start of an export declaration, including the '{'
17327/// (if present).
17328Decl *Sema::ActOnStartExportDecl(Scope *SSourceLocation ExportLoc,
17329                                 SourceLocation LBraceLoc) {
17330  ExportDecl *D = ExportDecl::Create(ContextCurContextExportLoc);
17331
17332  // C++ Modules TS draft:
17333  //   An export-declaration shall appear in the purview of a module other than
17334  //   the global module.
17335  if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface)
17336    Diag(ExportLoc, diag::err_export_not_in_module_interface);
17337
17338  //   An export-declaration [...] shall not contain more than one
17339  //   export keyword.
17340  //
17341  // The intent here is that an export-declaration cannot appear within another
17342  // export-declaration.
17343  if (D->isExported())
17344    Diag(ExportLoc, diag::err_export_within_export);
17345
17346  CurContext->addDecl(D);
17347  PushDeclContext(SD);
17348  D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
17349  return D;
17350}
17351
17352/// Complete the definition of an export declaration.
17353Decl *Sema::ActOnFinishExportDecl(Scope *SDecl *DSourceLocation RBraceLoc) {
17354  auto *ED = cast<ExportDecl>(D);
17355  if (RBraceLoc.isValid())
17356    ED->setRBraceLoc(RBraceLoc);
17357
17358  // FIXME: Diagnose export of internal-linkage declaration (including
17359  // anonymous namespace).
17360
17361  PopDeclContext();
17362  return D;
17363}
17364
17365void Sema::ActOnPragmaRedefineExtname(IdentifierInfoName,
17366                                      IdentifierInfoAliasName,
17367                                      SourceLocation PragmaLoc,
17368                                      SourceLocation NameLoc,
17369                                      SourceLocation AliasNameLoc) {
17370  NamedDecl *PrevDecl = LookupSingleName(TUScopeNameNameLoc,
17371                                         LookupOrdinaryName);
17372  AsmLabelAttr *Attr =
17373      AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
17374
17375  // If a declaration that:
17376  // 1) declares a function or a variable
17377  // 2) has external linkage
17378  // already exists, add a label attribute to it.
17379  if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17380    if (isDeclExternC(PrevDecl))
17381      PrevDecl->addAttr(Attr);
17382    else
17383      Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
17384          << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
17385  // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
17386  } else
17387    (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
17388}
17389
17390void Sema::ActOnPragmaWeakID(IdentifierInfoName,
17391                             SourceLocation PragmaLoc,
17392                             SourceLocation NameLoc) {
17393  Decl *PrevDecl = LookupSingleName(TUScopeNameNameLocLookupOrdinaryName);
17394
17395  if (PrevDecl) {
17396    PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
17397  } else {
17398    (void)WeakUndeclaredIdentifiers.insert(
17399      std::pair<IdentifierInfo*,WeakInfo>
17400        (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
17401  }
17402}
17403
17404void Sema::ActOnPragmaWeakAlias(IdentifierInfoName,
17405                                IdentifierInfoAliasName,
17406                                SourceLocation PragmaLoc,
17407                                SourceLocation NameLoc,
17408                                SourceLocation AliasNameLoc) {
17409  Decl *PrevDecl = LookupSingleName(TUScopeAliasNameAliasNameLoc,
17410                                    LookupOrdinaryName);
17411  WeakInfo W = WeakInfo(NameNameLoc);
17412
17413  if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
17414    if (!PrevDecl->hasAttr<AliasAttr>())
17415      if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
17416        DeclApplyPragmaWeak(TUScopeNDW);
17417  } else {
17418    (void)WeakUndeclaredIdentifiers.insert(
17419      std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
17420  }
17421}
17422
17423Decl *Sema::getObjCDeclContext() const {
17424  return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
17425}
17426
clang::Sema::ConvertDeclToDeclGroup
clang::Sema::isSimpleTypeSpecifier
clang::Sema::getTypeName
clang::Sema::ActOnMSVCUnknownTypeName
clang::Sema::isTagName
clang::Sema::isMicrosoftMissingTypename
clang::Sema::DiagnoseUnknownTypeName
clang::Sema::ClassifyName
clang::Sema::getTemplateNameKindForDiagnostics
clang::Sema::getContainingDC
clang::Sema::PushDeclContext
clang::Sema::PopDeclContext
clang::Sema::ActOnTagStartSkippedDefinition
clang::Sema::ActOnTagFinishSkippedDefinition
clang::Sema::EnterDeclaratorContext
clang::Sema::ExitDeclaratorContext
clang::Sema::ActOnReenterFunctionContext
clang::Sema::ActOnExitFunctionContext
clang::Sema::PushOnScopeChains
clang::Sema::pushExternalDeclIntoScope
clang::Sema::isDeclInScope
clang::Sema::getScopeForDeclContext
clang::Sema::FilterLookupForScope
clang::Sema::CheckRedeclarationModuleOwnership
clang::Sema::mightHaveNonExternalLinkage
clang::Sema::ShouldWarnIfUnusedFileScopedDecl
clang::Sema::MarkUnusedFileScopedDecl
clang::Sema::DiagnoseUnusedNestedTypedefs
clang::Sema::DiagnoseUnusedDecl
clang::Sema::ActOnPopScope
clang::Sema::getObjCInterfaceDecl
clang::Sema::getNonFieldDeclScope
clang::Sema::LazilyCreateBuiltin
clang::Sema::isIncompatibleTypedef
clang::Sema::MergeTypedefNameDecl
clang::Sema::mergeDeclAttributes
clang::Sema::getSpecialMember
clang::Sema::getCallingConvAttributedType
clang::Sema::MergeFunctionDecl
clang::Sema::MergeCompatibleFunctionDecls
clang::Sema::mergeObjCMethodDecls
clang::Sema::MergeVarDeclTypes
clang::Sema::MergeVarDecl
clang::Sema::notePreviousDefinition
clang::Sema::checkVarDeclRedefinition
clang::Sema::ParsedFreeStandingDeclSpec
clang::Sema::handleTagNumbering
clang::Sema::setTagNameForLinkagePurposes
clang::Sema::ParsedFreeStandingDeclSpec
clang::Sema::BuildAnonymousStructOrUnion
clang::Sema::BuildMicrosoftCAnonymousStruct
clang::Sema::GetNameForDeclarator
clang::Sema::GetNameFromUnqualifiedId
clang::Sema::ActOnDeclarator
clang::Sema::DiagnoseClassNameShadow
clang::Sema::diagnoseQualifiedDeclaration
clang::Sema::HandleDeclarator
clang::Sema::RegisterLocallyScopedExternCDecl
clang::Sema::findLocallyScopedExternCDecl
clang::Sema::DiagnoseFunctionSpecifiers
clang::Sema::ActOnTypedefDeclarator
clang::Sema::CheckTypedefForVariablyModifiedType
clang::Sema::ActOnTypedefNameDecl
clang::Sema::inferObjCARCLifetime
clang::Sema::adjustContextForLocalExternDecl
clang::Sema::ActOnVariableDeclarator
clang::Sema::getShadowedDeclaration
clang::Sema::getShadowedDeclaration
clang::Sema::CheckShadow
clang::Sema::DiagnoseShadowingLambdaDecls
clang::Sema::CheckShadow
clang::Sema::CheckShadowingDeclModification
clang::Sema::CheckVariableDeclarationType
clang::Sema::CheckVariableDeclaration
clang::Sema::AddOverriddenMethods
clang::Sema::MarkTypoCorrectedFunctionDefinition
clang::Sema::ActOnFunctionDeclarator
clang::Sema::getImplicitCodeSegOrSectionAttrForFunction
clang::Sema::canFullyTypeCheckRedeclaration
clang::Sema::shouldLinkDependentDeclWithPrevious
clang::Sema::CheckFunctionDeclaration
clang::Sema::CheckMain
clang::Sema::CheckMSVCRTEntryPoint
clang::Sema::CheckForConstantInitializer
clang::Sema::deduceVarTypeFromInitializer
clang::Sema::DeduceVariableDeclarationType
clang::Sema::AddInitializerToDecl
clang::Sema::ActOnInitializerError
clang::Sema::ActOnUninitializedDecl
clang::Sema::ActOnCXXForRangeDecl
clang::Sema::ActOnCXXForRangeIdentifier
clang::Sema::CheckCompleteVariableDeclaration
clang::Sema::CheckStaticLocalForDllExport
clang::Sema::FinalizeDeclaration
clang::Sema::FinalizeDeclaratorGroup
clang::Sema::BuildDeclaratorGroup
clang::Sema::ActOnDocumentableDecl
clang::Sema::ActOnDocumentableDecls
clang::Sema::ActOnParamDeclarator
clang::Sema::BuildParmVarDeclForTypedef
clang::Sema::DiagnoseUnusedParameters
clang::Sema::DiagnoseSizeOfParametersAndReturnValue
clang::Sema::CheckParameter
clang::Sema::ActOnFinishKNRParamDeclarations
clang::Sema::ActOnStartOfFunctionDef
clang::Sema::ActOnFinishInlineFunctionDef
clang::Sema::CheckForFunctionRedefinition
clang::Sema::ActOnStartOfFunctionDef
clang::Sema::computeNRVO
clang::Sema::canDelayFunctionBody
clang::Sema::canSkipFunctionBody
clang::Sema::ActOnSkippedFunctionBody
clang::Sema::ActOnFinishFunctionBody
clang::Sema::ActOnFinishFunctionBody
clang::Sema::ActOnFinishDelayedAttribute
clang::Sema::ImplicitlyDefineFunction
clang::Sema::AddKnownFunctionAttributes
clang::Sema::ParseTypedefDecl
clang::Sema::CheckEnumUnderlyingType
clang::Sema::CheckEnumRedeclaration
clang::Sema::getNonTagTypeDeclKind
clang::Sema::isAcceptableTagRedeclaration
clang::Sema::ActOnTag
clang::Sema::ActOnTagStartDefinition
clang::Sema::ActOnDuplicateDefinition
clang::Sema::ActOnObjCContainerStartDefinition
clang::Sema::ActOnStartCXXMemberDeclarations
clang::Sema::ActOnTagFinishDefinition
clang::Sema::ActOnObjCContainerFinishDefinition
clang::Sema::ActOnObjCTemporaryExitContainerContext
clang::Sema::ActOnObjCReenterContainerContext
clang::Sema::ActOnTagDefinitionError
clang::Sema::VerifyBitField
clang::Sema::ActOnField
clang::Sema::HandleField
clang::Sema::CheckFieldDecl
clang::Sema::CheckNontrivialField
clang::Sema::ActOnIvar
clang::Sema::ActOnLastBitfield
clang::Sema::ActOnFields
clang::Sema::CheckEnumConstant
clang::Sema::shouldSkipAnonEnumBody
clang::Sema::ActOnEnumConstant
clang::Sema::IsValueInFlagEnum
clang::Sema::ActOnEnumBody
clang::Sema::ActOnFileScopeAsmDecl
clang::Sema::ActOnModuleDecl
clang::Sema::ActOnModuleImport
clang::Sema::ActOnModuleInclude
clang::Sema::BuildModuleInclude
clang::Sema::ActOnModuleBegin
clang::Sema::ActOnModuleEnd
clang::Sema::createImplicitModuleImportForErrorRecovery
clang::Sema::ActOnStartExportDecl
clang::Sema::ActOnFinishExportDecl
clang::Sema::ActOnPragmaRedefineExtname
clang::Sema::ActOnPragmaWeakID
clang::Sema::ActOnPragmaWeakAlias
clang::Sema::getObjCDeclContext