1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/CommentDiagnostic.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/StmtCXX.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/PartialDiagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
32 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
33 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
34 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
35 #include "clang/Sema/CXXFieldCollector.h"
36 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/DelayedDiagnostic.h"
38 #include "clang/Sema/Initialization.h"
39 #include "clang/Sema/Lookup.h"
40 #include "clang/Sema/ParsedTemplate.h"
41 #include "clang/Sema/Scope.h"
42 #include "clang/Sema/ScopeInfo.h"
43 #include "clang/Sema/SemaInternal.h"
44 #include "clang/Sema/Template.h"
45 #include "llvm/ADT/SmallString.h"
46 #include "llvm/ADT/Triple.h"
47 #include <algorithm>
48 #include <cstring>
49 #include <functional>
50 
51 using namespace clang;
52 using namespace sema;
53 
54 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
55   if (OwnedType) {
56     Decl *Group[2] = { OwnedType, Ptr };
57     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
58   }
59 
60   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
61 }
62 
63 namespace {
64 
65 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
66  public:
67   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
68                        bool AllowTemplates=false)
69       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
70         AllowClassTemplates(AllowTemplates) {
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       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
79       bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
80       return (IsType || AllowedTemplate) &&
81              (AllowInvalidDecl || !ND->isInvalidDecl());
82     }
83     return !WantClassName && candidate.isKeyword();
84   }
85 
86  private:
87   bool AllowInvalidDecl;
88   bool WantClassName;
89   bool AllowClassTemplates;
90 };
91 
92 } // end anonymous namespace
93 
94 /// \brief Determine whether the token kind starts a simple-type-specifier.
95 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
96   switch (Kind) {
97   // FIXME: Take into account the current language when deciding whether a
98   // token kind is a valid type specifier
99   case tok::kw_short:
100   case tok::kw_long:
101   case tok::kw___int64:
102   case tok::kw___int128:
103   case tok::kw_signed:
104   case tok::kw_unsigned:
105   case tok::kw_void:
106   case tok::kw_char:
107   case tok::kw_int:
108   case tok::kw_half:
109   case tok::kw_float:
110   case tok::kw_double:
111   case tok::kw___float128:
112   case tok::kw_wchar_t:
113   case tok::kw_bool:
114   case tok::kw___underlying_type:
115   case tok::kw___auto_type:
116     return true;
117 
118   case tok::annot_typename:
119   case tok::kw_char16_t:
120   case tok::kw_char32_t:
121   case tok::kw_typeof:
122   case tok::annot_decltype:
123   case tok::kw_decltype:
124     return getLangOpts().CPlusPlus;
125 
126   default:
127     break;
128   }
129 
130   return false;
131 }
132 
133 namespace {
134 enum class UnqualifiedTypeNameLookupResult {
135   NotFound,
136   FoundNonType,
137   FoundType
138 };
139 } // end anonymous namespace
140 
141 /// \brief Tries to perform unqualified lookup of the type decls in bases for
142 /// dependent class.
143 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
144 /// type decl, \a FoundType if only type decls are found.
145 static UnqualifiedTypeNameLookupResult
146 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
147                                 SourceLocation NameLoc,
148                                 const CXXRecordDecl *RD) {
149   if (!RD->hasDefinition())
150     return UnqualifiedTypeNameLookupResult::NotFound;
151   // Look for type decls in base classes.
152   UnqualifiedTypeNameLookupResult FoundTypeDecl =
153       UnqualifiedTypeNameLookupResult::NotFound;
154   for (const auto &Base : RD->bases()) {
155     const CXXRecordDecl *BaseRD = nullptr;
156     if (auto *BaseTT = Base.getType()->getAs<TagType>())
157       BaseRD = BaseTT->getAsCXXRecordDecl();
158     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
159       // Look for type decls in dependent base classes that have known primary
160       // templates.
161       if (!TST || !TST->isDependentType())
162         continue;
163       auto *TD = TST->getTemplateName().getAsTemplateDecl();
164       if (!TD)
165         continue;
166       if (auto *BasePrimaryTemplate =
167           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
168         if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
169           BaseRD = BasePrimaryTemplate;
170         else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
171           if (const ClassTemplatePartialSpecializationDecl *PS =
172                   CTD->findPartialSpecialization(Base.getType()))
173             if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
174               BaseRD = PS;
175         }
176       }
177     }
178     if (BaseRD) {
179       for (NamedDecl *ND : BaseRD->lookup(&II)) {
180         if (!isa<TypeDecl>(ND))
181           return UnqualifiedTypeNameLookupResult::FoundNonType;
182         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
183       }
184       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
185         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
186         case UnqualifiedTypeNameLookupResult::FoundNonType:
187           return UnqualifiedTypeNameLookupResult::FoundNonType;
188         case UnqualifiedTypeNameLookupResult::FoundType:
189           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
190           break;
191         case UnqualifiedTypeNameLookupResult::NotFound:
192           break;
193         }
194       }
195     }
196   }
197 
198   return FoundTypeDecl;
199 }
200 
201 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
202                                                       const IdentifierInfo &II,
203                                                       SourceLocation NameLoc) {
204   // Lookup in the parent class template context, if any.
205   const CXXRecordDecl *RD = nullptr;
206   UnqualifiedTypeNameLookupResult FoundTypeDecl =
207       UnqualifiedTypeNameLookupResult::NotFound;
208   for (DeclContext *DC = S.CurContext;
209        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
210        DC = DC->getParent()) {
211     // Look for type decls in dependent base classes that have known primary
212     // templates.
213     RD = dyn_cast<CXXRecordDecl>(DC);
214     if (RD && RD->getDescribedClassTemplate())
215       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
216   }
217   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
218     return nullptr;
219 
220   // We found some types in dependent base classes.  Recover as if the user
221   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
222   // lookup during template instantiation.
223   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
224 
225   ASTContext &Context = S.Context;
226   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
227                                           cast<Type>(Context.getRecordType(RD)));
228   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
229 
230   CXXScopeSpec SS;
231   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
232 
233   TypeLocBuilder Builder;
234   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
235   DepTL.setNameLoc(NameLoc);
236   DepTL.setElaboratedKeywordLoc(SourceLocation());
237   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
238   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
239 }
240 
241 /// \brief If the identifier refers to a type name within this scope,
242 /// return the declaration of that type.
243 ///
244 /// This routine performs ordinary name lookup of the identifier II
245 /// within the given scope, with optional C++ scope specifier SS, to
246 /// determine whether the name refers to a type. If so, returns an
247 /// opaque pointer (actually a QualType) corresponding to that
248 /// type. Otherwise, returns NULL.
249 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
250                              Scope *S, CXXScopeSpec *SS,
251                              bool isClassName, bool HasTrailingDot,
252                              ParsedType ObjectTypePtr,
253                              bool IsCtorOrDtorName,
254                              bool WantNontrivialTypeSourceInfo,
255                              IdentifierInfo **CorrectedII) {
256   // Determine where we will perform name lookup.
257   DeclContext *LookupCtx = nullptr;
258   if (ObjectTypePtr) {
259     QualType ObjectType = ObjectTypePtr.get();
260     if (ObjectType->isRecordType())
261       LookupCtx = computeDeclContext(ObjectType);
262   } else if (SS && SS->isNotEmpty()) {
263     LookupCtx = computeDeclContext(*SS, false);
264 
265     if (!LookupCtx) {
266       if (isDependentScopeSpecifier(*SS)) {
267         // C++ [temp.res]p3:
268         //   A qualified-id that refers to a type and in which the
269         //   nested-name-specifier depends on a template-parameter (14.6.2)
270         //   shall be prefixed by the keyword typename to indicate that the
271         //   qualified-id denotes a type, forming an
272         //   elaborated-type-specifier (7.1.5.3).
273         //
274         // We therefore do not perform any name lookup if the result would
275         // refer to a member of an unknown specialization.
276         if (!isClassName && !IsCtorOrDtorName)
277           return nullptr;
278 
279         // We know from the grammar that this name refers to a type,
280         // so build a dependent node to describe the type.
281         if (WantNontrivialTypeSourceInfo)
282           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
283 
284         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
285         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
286                                        II, NameLoc);
287         return ParsedType::make(T);
288       }
289 
290       return nullptr;
291     }
292 
293     if (!LookupCtx->isDependentContext() &&
294         RequireCompleteDeclContext(*SS, LookupCtx))
295       return nullptr;
296   }
297 
298   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
299   // lookup for class-names.
300   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
301                                       LookupOrdinaryName;
302   LookupResult Result(*this, &II, NameLoc, Kind);
303   if (LookupCtx) {
304     // Perform "qualified" name lookup into the declaration context we
305     // computed, which is either the type of the base of a member access
306     // expression or the declaration context associated with a prior
307     // nested-name-specifier.
308     LookupQualifiedName(Result, LookupCtx);
309 
310     if (ObjectTypePtr && Result.empty()) {
311       // C++ [basic.lookup.classref]p3:
312       //   If the unqualified-id is ~type-name, the type-name is looked up
313       //   in the context of the entire postfix-expression. If the type T of
314       //   the object expression is of a class type C, the type-name is also
315       //   looked up in the scope of class C. At least one of the lookups shall
316       //   find a name that refers to (possibly cv-qualified) T.
317       LookupName(Result, S);
318     }
319   } else {
320     // Perform unqualified name lookup.
321     LookupName(Result, S);
322 
323     // For unqualified lookup in a class template in MSVC mode, look into
324     // dependent base classes where the primary class template is known.
325     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
326       if (ParsedType TypeInBase =
327               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
328         return TypeInBase;
329     }
330   }
331 
332   NamedDecl *IIDecl = nullptr;
333   switch (Result.getResultKind()) {
334   case LookupResult::NotFound:
335   case LookupResult::NotFoundInCurrentInstantiation:
336     if (CorrectedII) {
337       TypoCorrection Correction = CorrectTypo(
338           Result.getLookupNameInfo(), Kind, S, SS,
339           llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
340           CTK_ErrorRecovery);
341       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
342       TemplateTy Template;
343       bool MemberOfUnknownSpecialization;
344       UnqualifiedId TemplateName;
345       TemplateName.setIdentifier(NewII, NameLoc);
346       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
347       CXXScopeSpec NewSS, *NewSSPtr = SS;
348       if (SS && NNS) {
349         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
350         NewSSPtr = &NewSS;
351       }
352       if (Correction && (NNS || NewII != &II) &&
353           // Ignore a correction to a template type as the to-be-corrected
354           // identifier is not a template (typo correction for template names
355           // is handled elsewhere).
356           !(getLangOpts().CPlusPlus && NewSSPtr &&
357             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
358                            Template, MemberOfUnknownSpecialization))) {
359         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
360                                     isClassName, HasTrailingDot, ObjectTypePtr,
361                                     IsCtorOrDtorName,
362                                     WantNontrivialTypeSourceInfo);
363         if (Ty) {
364           diagnoseTypo(Correction,
365                        PDiag(diag::err_unknown_type_or_class_name_suggest)
366                          << Result.getLookupName() << isClassName);
367           if (SS && NNS)
368             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
369           *CorrectedII = NewII;
370           return Ty;
371         }
372       }
373     }
374     // If typo correction failed or was not performed, fall through
375   case LookupResult::FoundOverloaded:
376   case LookupResult::FoundUnresolvedValue:
377     Result.suppressDiagnostics();
378     return nullptr;
379 
380   case LookupResult::Ambiguous:
381     // Recover from type-hiding ambiguities by hiding the type.  We'll
382     // do the lookup again when looking for an object, and we can
383     // diagnose the error then.  If we don't do this, then the error
384     // about hiding the type will be immediately followed by an error
385     // that only makes sense if the identifier was treated like a type.
386     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
387       Result.suppressDiagnostics();
388       return nullptr;
389     }
390 
391     // Look to see if we have a type anywhere in the list of results.
392     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
393          Res != ResEnd; ++Res) {
394       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
395         if (!IIDecl ||
396             (*Res)->getLocation().getRawEncoding() <
397               IIDecl->getLocation().getRawEncoding())
398           IIDecl = *Res;
399       }
400     }
401 
402     if (!IIDecl) {
403       // None of the entities we found is a type, so there is no way
404       // to even assume that the result is a type. In this case, don't
405       // complain about the ambiguity. The parser will either try to
406       // perform this lookup again (e.g., as an object name), which
407       // will produce the ambiguity, or will complain that it expected
408       // a type name.
409       Result.suppressDiagnostics();
410       return nullptr;
411     }
412 
413     // We found a type within the ambiguous lookup; diagnose the
414     // ambiguity and then return that type. This might be the right
415     // answer, or it might not be, but it suppresses any attempt to
416     // perform the name lookup again.
417     break;
418 
419   case LookupResult::Found:
420     IIDecl = Result.getFoundDecl();
421     break;
422   }
423 
424   assert(IIDecl && "Didn't find decl");
425 
426   QualType T;
427   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
428     // C++ [class.qual]p2: A lookup that would find the injected-class-name
429     // instead names the constructors of the class, except when naming a class.
430     // This is ill-formed when we're not actually forming a ctor or dtor name.
431     auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
432     auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
433     if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
434         FoundRD->isInjectedClassName() &&
435         declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
436       Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
437           << &II << /*Type*/1;
438 
439     DiagnoseUseOfDecl(IIDecl, NameLoc);
440 
441     T = Context.getTypeDeclType(TD);
442     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
443 
444     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
445     // constructor or destructor name (in such a case, the scope specifier
446     // will be attached to the enclosing Expr or Decl node).
447     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
448       if (WantNontrivialTypeSourceInfo) {
449         // Construct a type with type-source information.
450         TypeLocBuilder Builder;
451         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
452 
453         T = getElaboratedType(ETK_None, *SS, T);
454         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
455         ElabTL.setElaboratedKeywordLoc(SourceLocation());
456         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
457         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
458       } else {
459         T = getElaboratedType(ETK_None, *SS, T);
460       }
461     }
462   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
463     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
464     if (!HasTrailingDot)
465       T = Context.getObjCInterfaceType(IDecl);
466   }
467 
468   if (T.isNull()) {
469     // If it's not plausibly a type, suppress diagnostics.
470     Result.suppressDiagnostics();
471     return nullptr;
472   }
473   return ParsedType::make(T);
474 }
475 
476 // Builds a fake NNS for the given decl context.
477 static NestedNameSpecifier *
478 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
479   for (;; DC = DC->getLookupParent()) {
480     DC = DC->getPrimaryContext();
481     auto *ND = dyn_cast<NamespaceDecl>(DC);
482     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
483       return NestedNameSpecifier::Create(Context, nullptr, ND);
484     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
485       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
486                                          RD->getTypeForDecl());
487     else if (isa<TranslationUnitDecl>(DC))
488       return NestedNameSpecifier::GlobalSpecifier(Context);
489   }
490   llvm_unreachable("something isn't in TU scope?");
491 }
492 
493 /// Find the parent class with dependent bases of the innermost enclosing method
494 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
495 /// up allowing unqualified dependent type names at class-level, which MSVC
496 /// correctly rejects.
497 static const CXXRecordDecl *
498 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
499   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
500     DC = DC->getPrimaryContext();
501     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
502       if (MD->getParent()->hasAnyDependentBases())
503         return MD->getParent();
504   }
505   return nullptr;
506 }
507 
508 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
509                                           SourceLocation NameLoc,
510                                           bool IsTemplateTypeArg) {
511   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
512 
513   NestedNameSpecifier *NNS = nullptr;
514   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
515     // If we weren't able to parse a default template argument, delay lookup
516     // until instantiation time by making a non-dependent DependentTypeName. We
517     // pretend we saw a NestedNameSpecifier referring to the current scope, and
518     // lookup is retried.
519     // FIXME: This hurts our diagnostic quality, since we get errors like "no
520     // type named 'Foo' in 'current_namespace'" when the user didn't write any
521     // name specifiers.
522     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
523     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
524   } else if (const CXXRecordDecl *RD =
525                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
526     // Build a DependentNameType that will perform lookup into RD at
527     // instantiation time.
528     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
529                                       RD->getTypeForDecl());
530 
531     // Diagnose that this identifier was undeclared, and retry the lookup during
532     // template instantiation.
533     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
534                                                                       << RD;
535   } else {
536     // This is not a situation that we should recover from.
537     return ParsedType();
538   }
539 
540   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
541 
542   // Build type location information.  We synthesized the qualifier, so we have
543   // to build a fake NestedNameSpecifierLoc.
544   NestedNameSpecifierLocBuilder NNSLocBuilder;
545   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
546   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
547 
548   TypeLocBuilder Builder;
549   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
550   DepTL.setNameLoc(NameLoc);
551   DepTL.setElaboratedKeywordLoc(SourceLocation());
552   DepTL.setQualifierLoc(QualifierLoc);
553   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
554 }
555 
556 /// isTagName() - This method is called *for error recovery purposes only*
557 /// to determine if the specified name is a valid tag name ("struct foo").  If
558 /// so, this returns the TST for the tag corresponding to it (TST_enum,
559 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
560 /// cases in C where the user forgot to specify the tag.
561 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
562   // Do a tag name lookup in this scope.
563   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
564   LookupName(R, S, false);
565   R.suppressDiagnostics();
566   if (R.getResultKind() == LookupResult::Found)
567     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
568       switch (TD->getTagKind()) {
569       case TTK_Struct: return DeclSpec::TST_struct;
570       case TTK_Interface: return DeclSpec::TST_interface;
571       case TTK_Union:  return DeclSpec::TST_union;
572       case TTK_Class:  return DeclSpec::TST_class;
573       case TTK_Enum:   return DeclSpec::TST_enum;
574       }
575     }
576 
577   return DeclSpec::TST_unspecified;
578 }
579 
580 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
581 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
582 /// then downgrade the missing typename error to a warning.
583 /// This is needed for MSVC compatibility; Example:
584 /// @code
585 /// template<class T> class A {
586 /// public:
587 ///   typedef int TYPE;
588 /// };
589 /// template<class T> class B : public A<T> {
590 /// public:
591 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
592 /// };
593 /// @endcode
594 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
595   if (CurContext->isRecord()) {
596     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
597       return true;
598 
599     const Type *Ty = SS->getScopeRep()->getAsType();
600 
601     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
602     for (const auto &Base : RD->bases())
603       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
604         return true;
605     return S->isFunctionPrototypeScope();
606   }
607   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
608 }
609 
610 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
611                                    SourceLocation IILoc,
612                                    Scope *S,
613                                    CXXScopeSpec *SS,
614                                    ParsedType &SuggestedType,
615                                    bool AllowClassTemplates) {
616   // We don't have anything to suggest (yet).
617   SuggestedType = nullptr;
618 
619   // There may have been a typo in the name of the type. Look up typo
620   // results, in case we have something that we can suggest.
621   if (TypoCorrection Corrected =
622           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
623                       llvm::make_unique<TypeNameValidatorCCC>(
624                           false, false, AllowClassTemplates),
625                       CTK_ErrorRecovery)) {
626     if (Corrected.isKeyword()) {
627       // We corrected to a keyword.
628       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
629       II = Corrected.getCorrectionAsIdentifierInfo();
630     } else {
631       // We found a similarly-named type or interface; suggest that.
632       if (!SS || !SS->isSet()) {
633         diagnoseTypo(Corrected,
634                      PDiag(diag::err_unknown_typename_suggest) << II);
635       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
636         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
637         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
638                                 II->getName().equals(CorrectedStr);
639         diagnoseTypo(Corrected,
640                      PDiag(diag::err_unknown_nested_typename_suggest)
641                        << II << DC << DroppedSpecifier << SS->getRange());
642       } else {
643         llvm_unreachable("could not have corrected a typo here");
644       }
645 
646       CXXScopeSpec tmpSS;
647       if (Corrected.getCorrectionSpecifier())
648         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
649                           SourceRange(IILoc));
650       SuggestedType =
651           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
652                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
653                       /*IsCtorOrDtorName=*/false,
654                       /*NonTrivialTypeSourceInfo=*/true);
655     }
656     return;
657   }
658 
659   if (getLangOpts().CPlusPlus) {
660     // See if II is a class template that the user forgot to pass arguments to.
661     UnqualifiedId Name;
662     Name.setIdentifier(II, IILoc);
663     CXXScopeSpec EmptySS;
664     TemplateTy TemplateResult;
665     bool MemberOfUnknownSpecialization;
666     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
667                        Name, nullptr, true, TemplateResult,
668                        MemberOfUnknownSpecialization) == TNK_Type_template) {
669       TemplateName TplName = TemplateResult.get();
670       Diag(IILoc, diag::err_template_missing_args)
671         << (int)getTemplateNameKindForDiagnostics(TplName) << TplName;
672       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
673         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
674           << TplDecl->getTemplateParameters()->getSourceRange();
675       }
676       return;
677     }
678   }
679 
680   // FIXME: Should we move the logic that tries to recover from a missing tag
681   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
682 
683   if (!SS || (!SS->isSet() && !SS->isInvalid()))
684     Diag(IILoc, diag::err_unknown_typename) << II;
685   else if (DeclContext *DC = computeDeclContext(*SS, false))
686     Diag(IILoc, diag::err_typename_nested_not_found)
687       << II << DC << SS->getRange();
688   else if (isDependentScopeSpecifier(*SS)) {
689     unsigned DiagID = diag::err_typename_missing;
690     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
691       DiagID = diag::ext_typename_missing;
692 
693     Diag(SS->getRange().getBegin(), DiagID)
694       << SS->getScopeRep() << II->getName()
695       << SourceRange(SS->getRange().getBegin(), IILoc)
696       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
697     SuggestedType = ActOnTypenameType(S, SourceLocation(),
698                                       *SS, *II, IILoc).get();
699   } else {
700     assert(SS && SS->isInvalid() &&
701            "Invalid scope specifier has already been diagnosed");
702   }
703 }
704 
705 /// \brief Determine whether the given result set contains either a type name
706 /// or
707 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
708   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
709                        NextToken.is(tok::less);
710 
711   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
712     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
713       return true;
714 
715     if (CheckTemplate && isa<TemplateDecl>(*I))
716       return true;
717   }
718 
719   return false;
720 }
721 
722 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
723                                     Scope *S, CXXScopeSpec &SS,
724                                     IdentifierInfo *&Name,
725                                     SourceLocation NameLoc) {
726   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
727   SemaRef.LookupParsedName(R, S, &SS);
728   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
729     StringRef FixItTagName;
730     switch (Tag->getTagKind()) {
731       case TTK_Class:
732         FixItTagName = "class ";
733         break;
734 
735       case TTK_Enum:
736         FixItTagName = "enum ";
737         break;
738 
739       case TTK_Struct:
740         FixItTagName = "struct ";
741         break;
742 
743       case TTK_Interface:
744         FixItTagName = "__interface ";
745         break;
746 
747       case TTK_Union:
748         FixItTagName = "union ";
749         break;
750     }
751 
752     StringRef TagName = FixItTagName.drop_back();
753     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
754       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
755       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
756 
757     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
758          I != IEnd; ++I)
759       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
760         << Name << TagName;
761 
762     // Replace lookup results with just the tag decl.
763     Result.clear(Sema::LookupTagName);
764     SemaRef.LookupParsedName(Result, S, &SS);
765     return true;
766   }
767 
768   return false;
769 }
770 
771 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
772 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
773                                   QualType T, SourceLocation NameLoc) {
774   ASTContext &Context = S.Context;
775 
776   TypeLocBuilder Builder;
777   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
778 
779   T = S.getElaboratedType(ETK_None, SS, T);
780   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
781   ElabTL.setElaboratedKeywordLoc(SourceLocation());
782   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
783   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
784 }
785 
786 Sema::NameClassification
787 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
788                    SourceLocation NameLoc, const Token &NextToken,
789                    bool IsAddressOfOperand,
790                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
791   DeclarationNameInfo NameInfo(Name, NameLoc);
792   ObjCMethodDecl *CurMethod = getCurMethodDecl();
793 
794   if (NextToken.is(tok::coloncolon)) {
795     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
796     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
797   } else if (getLangOpts().CPlusPlus && SS.isSet() &&
798              isCurrentClassName(*Name, S, &SS)) {
799     // Per [class.qual]p2, this names the constructors of SS, not the
800     // injected-class-name. We don't have a classification for that.
801     // There's not much point caching this result, since the parser
802     // will reject it later.
803     return NameClassification::Unknown();
804   }
805 
806   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
807   LookupParsedName(Result, S, &SS, !CurMethod);
808 
809   // For unqualified lookup in a class template in MSVC mode, look into
810   // dependent base classes where the primary class template is known.
811   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
812     if (ParsedType TypeInBase =
813             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
814       return TypeInBase;
815   }
816 
817   // Perform lookup for Objective-C instance variables (including automatically
818   // synthesized instance variables), if we're in an Objective-C method.
819   // FIXME: This lookup really, really needs to be folded in to the normal
820   // unqualified lookup mechanism.
821   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
822     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
823     if (E.get() || E.isInvalid())
824       return E;
825   }
826 
827   bool SecondTry = false;
828   bool IsFilteredTemplateName = false;
829 
830 Corrected:
831   switch (Result.getResultKind()) {
832   case LookupResult::NotFound:
833     // If an unqualified-id is followed by a '(', then we have a function
834     // call.
835     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
836       // In C++, this is an ADL-only call.
837       // FIXME: Reference?
838       if (getLangOpts().CPlusPlus)
839         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
840 
841       // C90 6.3.2.2:
842       //   If the expression that precedes the parenthesized argument list in a
843       //   function call consists solely of an identifier, and if no
844       //   declaration is visible for this identifier, the identifier is
845       //   implicitly declared exactly as if, in the innermost block containing
846       //   the function call, the declaration
847       //
848       //     extern int identifier ();
849       //
850       //   appeared.
851       //
852       // We also allow this in C99 as an extension.
853       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
854         Result.addDecl(D);
855         Result.resolveKind();
856         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
857       }
858     }
859 
860     // In C, we first see whether there is a tag type by the same name, in
861     // which case it's likely that the user just forgot to write "enum",
862     // "struct", or "union".
863     if (!getLangOpts().CPlusPlus && !SecondTry &&
864         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
865       break;
866     }
867 
868     // Perform typo correction to determine if there is another name that is
869     // close to this name.
870     if (!SecondTry && CCC) {
871       SecondTry = true;
872       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
873                                                  Result.getLookupKind(), S,
874                                                  &SS, std::move(CCC),
875                                                  CTK_ErrorRecovery)) {
876         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
877         unsigned QualifiedDiag = diag::err_no_member_suggest;
878 
879         NamedDecl *FirstDecl = Corrected.getFoundDecl();
880         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
881         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
882             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
883           UnqualifiedDiag = diag::err_no_template_suggest;
884           QualifiedDiag = diag::err_no_member_template_suggest;
885         } else if (UnderlyingFirstDecl &&
886                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
887                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
888                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
889           UnqualifiedDiag = diag::err_unknown_typename_suggest;
890           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
891         }
892 
893         if (SS.isEmpty()) {
894           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
895         } else {// FIXME: is this even reachable? Test it.
896           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
897           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
898                                   Name->getName().equals(CorrectedStr);
899           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
900                                     << Name << computeDeclContext(SS, false)
901                                     << DroppedSpecifier << SS.getRange());
902         }
903 
904         // Update the name, so that the caller has the new name.
905         Name = Corrected.getCorrectionAsIdentifierInfo();
906 
907         // Typo correction corrected to a keyword.
908         if (Corrected.isKeyword())
909           return Name;
910 
911         // Also update the LookupResult...
912         // FIXME: This should probably go away at some point
913         Result.clear();
914         Result.setLookupName(Corrected.getCorrection());
915         if (FirstDecl)
916           Result.addDecl(FirstDecl);
917 
918         // If we found an Objective-C instance variable, let
919         // LookupInObjCMethod build the appropriate expression to
920         // reference the ivar.
921         // FIXME: This is a gross hack.
922         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
923           Result.clear();
924           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
925           return E;
926         }
927 
928         goto Corrected;
929       }
930     }
931 
932     // We failed to correct; just fall through and let the parser deal with it.
933     Result.suppressDiagnostics();
934     return NameClassification::Unknown();
935 
936   case LookupResult::NotFoundInCurrentInstantiation: {
937     // We performed name lookup into the current instantiation, and there were
938     // dependent bases, so we treat this result the same way as any other
939     // dependent nested-name-specifier.
940 
941     // C++ [temp.res]p2:
942     //   A name used in a template declaration or definition and that is
943     //   dependent on a template-parameter is assumed not to name a type
944     //   unless the applicable name lookup finds a type name or the name is
945     //   qualified by the keyword typename.
946     //
947     // FIXME: If the next token is '<', we might want to ask the parser to
948     // perform some heroics to see if we actually have a
949     // template-argument-list, which would indicate a missing 'template'
950     // keyword here.
951     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
952                                       NameInfo, IsAddressOfOperand,
953                                       /*TemplateArgs=*/nullptr);
954   }
955 
956   case LookupResult::Found:
957   case LookupResult::FoundOverloaded:
958   case LookupResult::FoundUnresolvedValue:
959     break;
960 
961   case LookupResult::Ambiguous:
962     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
963         hasAnyAcceptableTemplateNames(Result)) {
964       // C++ [temp.local]p3:
965       //   A lookup that finds an injected-class-name (10.2) can result in an
966       //   ambiguity in certain cases (for example, if it is found in more than
967       //   one base class). If all of the injected-class-names that are found
968       //   refer to specializations of the same class template, and if the name
969       //   is followed by a template-argument-list, the reference refers to the
970       //   class template itself and not a specialization thereof, and is not
971       //   ambiguous.
972       //
973       // This filtering can make an ambiguous result into an unambiguous one,
974       // so try again after filtering out template names.
975       FilterAcceptableTemplateNames(Result);
976       if (!Result.isAmbiguous()) {
977         IsFilteredTemplateName = true;
978         break;
979       }
980     }
981 
982     // Diagnose the ambiguity and return an error.
983     return NameClassification::Error();
984   }
985 
986   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
987       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
988     // C++ [temp.names]p3:
989     //   After name lookup (3.4) finds that a name is a template-name or that
990     //   an operator-function-id or a literal- operator-id refers to a set of
991     //   overloaded functions any member of which is a function template if
992     //   this is followed by a <, the < is always taken as the delimiter of a
993     //   template-argument-list and never as the less-than operator.
994     if (!IsFilteredTemplateName)
995       FilterAcceptableTemplateNames(Result);
996 
997     if (!Result.empty()) {
998       bool IsFunctionTemplate;
999       bool IsVarTemplate;
1000       TemplateName Template;
1001       if (Result.end() - Result.begin() > 1) {
1002         IsFunctionTemplate = true;
1003         Template = Context.getOverloadedTemplateName(Result.begin(),
1004                                                      Result.end());
1005       } else {
1006         TemplateDecl *TD
1007           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
1008         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1009         IsVarTemplate = isa<VarTemplateDecl>(TD);
1010 
1011         if (SS.isSet() && !SS.isInvalid())
1012           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
1013                                                     /*TemplateKeyword=*/false,
1014                                                       TD);
1015         else
1016           Template = TemplateName(TD);
1017       }
1018 
1019       if (IsFunctionTemplate) {
1020         // Function templates always go through overload resolution, at which
1021         // point we'll perform the various checks (e.g., accessibility) we need
1022         // to based on which function we selected.
1023         Result.suppressDiagnostics();
1024 
1025         return NameClassification::FunctionTemplate(Template);
1026       }
1027 
1028       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1029                            : NameClassification::TypeTemplate(Template);
1030     }
1031   }
1032 
1033   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1034   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1035     DiagnoseUseOfDecl(Type, NameLoc);
1036     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1037     QualType T = Context.getTypeDeclType(Type);
1038     if (SS.isNotEmpty())
1039       return buildNestedType(*this, SS, T, NameLoc);
1040     return ParsedType::make(T);
1041   }
1042 
1043   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1044   if (!Class) {
1045     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1046     if (ObjCCompatibleAliasDecl *Alias =
1047             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1048       Class = Alias->getClassInterface();
1049   }
1050 
1051   if (Class) {
1052     DiagnoseUseOfDecl(Class, NameLoc);
1053 
1054     if (NextToken.is(tok::period)) {
1055       // Interface. <something> is parsed as a property reference expression.
1056       // Just return "unknown" as a fall-through for now.
1057       Result.suppressDiagnostics();
1058       return NameClassification::Unknown();
1059     }
1060 
1061     QualType T = Context.getObjCInterfaceType(Class);
1062     return ParsedType::make(T);
1063   }
1064 
1065   // We can have a type template here if we're classifying a template argument.
1066   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1067       !isa<VarTemplateDecl>(FirstDecl))
1068     return NameClassification::TypeTemplate(
1069         TemplateName(cast<TemplateDecl>(FirstDecl)));
1070 
1071   // Check for a tag type hidden by a non-type decl in a few cases where it
1072   // seems likely a type is wanted instead of the non-type that was found.
1073   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1074   if ((NextToken.is(tok::identifier) ||
1075        (NextIsOp &&
1076         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1077       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1078     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1079     DiagnoseUseOfDecl(Type, NameLoc);
1080     QualType T = Context.getTypeDeclType(Type);
1081     if (SS.isNotEmpty())
1082       return buildNestedType(*this, SS, T, NameLoc);
1083     return ParsedType::make(T);
1084   }
1085 
1086   if (FirstDecl->isCXXClassMember())
1087     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1088                                            nullptr, S);
1089 
1090   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1091   return BuildDeclarationNameExpr(SS, Result, ADL);
1092 }
1093 
1094 Sema::TemplateNameKindForDiagnostics
1095 Sema::getTemplateNameKindForDiagnostics(TemplateName Name) {
1096   auto *TD = Name.getAsTemplateDecl();
1097   if (!TD)
1098     return TemplateNameKindForDiagnostics::DependentTemplate;
1099   if (isa<ClassTemplateDecl>(TD))
1100     return TemplateNameKindForDiagnostics::ClassTemplate;
1101   if (isa<FunctionTemplateDecl>(TD))
1102     return TemplateNameKindForDiagnostics::FunctionTemplate;
1103   if (isa<VarTemplateDecl>(TD))
1104     return TemplateNameKindForDiagnostics::VarTemplate;
1105   if (isa<TypeAliasTemplateDecl>(TD))
1106     return TemplateNameKindForDiagnostics::AliasTemplate;
1107   if (isa<TemplateTemplateParmDecl>(TD))
1108     return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1109   return TemplateNameKindForDiagnostics::DependentTemplate;
1110 }
1111 
1112 // Determines the context to return to after temporarily entering a
1113 // context.  This depends in an unnecessarily complicated way on the
1114 // exact ordering of callbacks from the parser.
1115 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1116 
1117   // Functions defined inline within classes aren't parsed until we've
1118   // finished parsing the top-level class, so the top-level class is
1119   // the context we'll need to return to.
1120   // A Lambda call operator whose parent is a class must not be treated
1121   // as an inline member function.  A Lambda can be used legally
1122   // either as an in-class member initializer or a default argument.  These
1123   // are parsed once the class has been marked complete and so the containing
1124   // context would be the nested class (when the lambda is defined in one);
1125   // If the class is not complete, then the lambda is being used in an
1126   // ill-formed fashion (such as to specify the width of a bit-field, or
1127   // in an array-bound) - in which case we still want to return the
1128   // lexically containing DC (which could be a nested class).
1129   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1130     DC = DC->getLexicalParent();
1131 
1132     // A function not defined within a class will always return to its
1133     // lexical context.
1134     if (!isa<CXXRecordDecl>(DC))
1135       return DC;
1136 
1137     // A C++ inline method/friend is parsed *after* the topmost class
1138     // it was declared in is fully parsed ("complete");  the topmost
1139     // class is the context we need to return to.
1140     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1141       DC = RD;
1142 
1143     // Return the declaration context of the topmost class the inline method is
1144     // declared in.
1145     return DC;
1146   }
1147 
1148   return DC->getLexicalParent();
1149 }
1150 
1151 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1152   assert(getContainingDC(DC) == CurContext &&
1153       "The next DeclContext should be lexically contained in the current one.");
1154   CurContext = DC;
1155   S->setEntity(DC);
1156 }
1157 
1158 void Sema::PopDeclContext() {
1159   assert(CurContext && "DeclContext imbalance!");
1160 
1161   CurContext = getContainingDC(CurContext);
1162   assert(CurContext && "Popped translation unit!");
1163 }
1164 
1165 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1166                                                                     Decl *D) {
1167   // Unlike PushDeclContext, the context to which we return is not necessarily
1168   // the containing DC of TD, because the new context will be some pre-existing
1169   // TagDecl definition instead of a fresh one.
1170   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1171   CurContext = cast<TagDecl>(D)->getDefinition();
1172   assert(CurContext && "skipping definition of undefined tag");
1173   // Start lookups from the parent of the current context; we don't want to look
1174   // into the pre-existing complete definition.
1175   S->setEntity(CurContext->getLookupParent());
1176   return Result;
1177 }
1178 
1179 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1180   CurContext = static_cast<decltype(CurContext)>(Context);
1181 }
1182 
1183 /// EnterDeclaratorContext - Used when we must lookup names in the context
1184 /// of a declarator's nested name specifier.
1185 ///
1186 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1187   // C++0x [basic.lookup.unqual]p13:
1188   //   A name used in the definition of a static data member of class
1189   //   X (after the qualified-id of the static member) is looked up as
1190   //   if the name was used in a member function of X.
1191   // C++0x [basic.lookup.unqual]p14:
1192   //   If a variable member of a namespace is defined outside of the
1193   //   scope of its namespace then any name used in the definition of
1194   //   the variable member (after the declarator-id) is looked up as
1195   //   if the definition of the variable member occurred in its
1196   //   namespace.
1197   // Both of these imply that we should push a scope whose context
1198   // is the semantic context of the declaration.  We can't use
1199   // PushDeclContext here because that context is not necessarily
1200   // lexically contained in the current context.  Fortunately,
1201   // the containing scope should have the appropriate information.
1202 
1203   assert(!S->getEntity() && "scope already has entity");
1204 
1205 #ifndef NDEBUG
1206   Scope *Ancestor = S->getParent();
1207   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1208   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1209 #endif
1210 
1211   CurContext = DC;
1212   S->setEntity(DC);
1213 }
1214 
1215 void Sema::ExitDeclaratorContext(Scope *S) {
1216   assert(S->getEntity() == CurContext && "Context imbalance!");
1217 
1218   // Switch back to the lexical context.  The safety of this is
1219   // enforced by an assert in EnterDeclaratorContext.
1220   Scope *Ancestor = S->getParent();
1221   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1222   CurContext = Ancestor->getEntity();
1223 
1224   // We don't need to do anything with the scope, which is going to
1225   // disappear.
1226 }
1227 
1228 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1229   // We assume that the caller has already called
1230   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1231   FunctionDecl *FD = D->getAsFunction();
1232   if (!FD)
1233     return;
1234 
1235   // Same implementation as PushDeclContext, but enters the context
1236   // from the lexical parent, rather than the top-level class.
1237   assert(CurContext == FD->getLexicalParent() &&
1238     "The next DeclContext should be lexically contained in the current one.");
1239   CurContext = FD;
1240   S->setEntity(CurContext);
1241 
1242   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1243     ParmVarDecl *Param = FD->getParamDecl(P);
1244     // If the parameter has an identifier, then add it to the scope
1245     if (Param->getIdentifier()) {
1246       S->AddDecl(Param);
1247       IdResolver.AddDecl(Param);
1248     }
1249   }
1250 }
1251 
1252 void Sema::ActOnExitFunctionContext() {
1253   // Same implementation as PopDeclContext, but returns to the lexical parent,
1254   // rather than the top-level class.
1255   assert(CurContext && "DeclContext imbalance!");
1256   CurContext = CurContext->getLexicalParent();
1257   assert(CurContext && "Popped translation unit!");
1258 }
1259 
1260 /// \brief Determine whether we allow overloading of the function
1261 /// PrevDecl with another declaration.
1262 ///
1263 /// This routine determines whether overloading is possible, not
1264 /// whether some new function is actually an overload. It will return
1265 /// true in C++ (where we can always provide overloads) or, as an
1266 /// extension, in C when the previous function is already an
1267 /// overloaded function declaration or has the "overloadable"
1268 /// attribute.
1269 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1270                                        ASTContext &Context) {
1271   if (Context.getLangOpts().CPlusPlus)
1272     return true;
1273 
1274   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1275     return true;
1276 
1277   return (Previous.getResultKind() == LookupResult::Found
1278           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1279 }
1280 
1281 /// Add this decl to the scope shadowed decl chains.
1282 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1283   // Move up the scope chain until we find the nearest enclosing
1284   // non-transparent context. The declaration will be introduced into this
1285   // scope.
1286   while (S->getEntity() && S->getEntity()->isTransparentContext())
1287     S = S->getParent();
1288 
1289   // Add scoped declarations into their context, so that they can be
1290   // found later. Declarations without a context won't be inserted
1291   // into any context.
1292   if (AddToContext)
1293     CurContext->addDecl(D);
1294 
1295   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1296   // are function-local declarations.
1297   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1298       !D->getDeclContext()->getRedeclContext()->Equals(
1299         D->getLexicalDeclContext()->getRedeclContext()) &&
1300       !D->getLexicalDeclContext()->isFunctionOrMethod())
1301     return;
1302 
1303   // Template instantiations should also not be pushed into scope.
1304   if (isa<FunctionDecl>(D) &&
1305       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1306     return;
1307 
1308   // If this replaces anything in the current scope,
1309   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1310                                IEnd = IdResolver.end();
1311   for (; I != IEnd; ++I) {
1312     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1313       S->RemoveDecl(*I);
1314       IdResolver.RemoveDecl(*I);
1315 
1316       // Should only need to replace one decl.
1317       break;
1318     }
1319   }
1320 
1321   S->AddDecl(D);
1322 
1323   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1324     // Implicitly-generated labels may end up getting generated in an order that
1325     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1326     // the label at the appropriate place in the identifier chain.
1327     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1328       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1329       if (IDC == CurContext) {
1330         if (!S->isDeclScope(*I))
1331           continue;
1332       } else if (IDC->Encloses(CurContext))
1333         break;
1334     }
1335 
1336     IdResolver.InsertDeclAfter(I, D);
1337   } else {
1338     IdResolver.AddDecl(D);
1339   }
1340 }
1341 
1342 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1343   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1344     TUScope->AddDecl(D);
1345 }
1346 
1347 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1348                          bool AllowInlineNamespace) {
1349   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1350 }
1351 
1352 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1353   DeclContext *TargetDC = DC->getPrimaryContext();
1354   do {
1355     if (DeclContext *ScopeDC = S->getEntity())
1356       if (ScopeDC->getPrimaryContext() == TargetDC)
1357         return S;
1358   } while ((S = S->getParent()));
1359 
1360   return nullptr;
1361 }
1362 
1363 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1364                                             DeclContext*,
1365                                             ASTContext&);
1366 
1367 /// Filters out lookup results that don't fall within the given scope
1368 /// as determined by isDeclInScope.
1369 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1370                                 bool ConsiderLinkage,
1371                                 bool AllowInlineNamespace) {
1372   LookupResult::Filter F = R.makeFilter();
1373   while (F.hasNext()) {
1374     NamedDecl *D = F.next();
1375 
1376     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1377       continue;
1378 
1379     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1380       continue;
1381 
1382     F.erase();
1383   }
1384 
1385   F.done();
1386 }
1387 
1388 static bool isUsingDecl(NamedDecl *D) {
1389   return isa<UsingShadowDecl>(D) ||
1390          isa<UnresolvedUsingTypenameDecl>(D) ||
1391          isa<UnresolvedUsingValueDecl>(D);
1392 }
1393 
1394 /// Removes using shadow declarations from the lookup results.
1395 static void RemoveUsingDecls(LookupResult &R) {
1396   LookupResult::Filter F = R.makeFilter();
1397   while (F.hasNext())
1398     if (isUsingDecl(F.next()))
1399       F.erase();
1400 
1401   F.done();
1402 }
1403 
1404 /// \brief Check for this common pattern:
1405 /// @code
1406 /// class S {
1407 ///   S(const S&); // DO NOT IMPLEMENT
1408 ///   void operator=(const S&); // DO NOT IMPLEMENT
1409 /// };
1410 /// @endcode
1411 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1412   // FIXME: Should check for private access too but access is set after we get
1413   // the decl here.
1414   if (D->doesThisDeclarationHaveABody())
1415     return false;
1416 
1417   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1418     return CD->isCopyConstructor();
1419   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1420     return Method->isCopyAssignmentOperator();
1421   return false;
1422 }
1423 
1424 // We need this to handle
1425 //
1426 // typedef struct {
1427 //   void *foo() { return 0; }
1428 // } A;
1429 //
1430 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1431 // for example. If 'A', foo will have external linkage. If we have '*A',
1432 // foo will have no linkage. Since we can't know until we get to the end
1433 // of the typedef, this function finds out if D might have non-external linkage.
1434 // Callers should verify at the end of the TU if it D has external linkage or
1435 // not.
1436 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1437   const DeclContext *DC = D->getDeclContext();
1438   while (!DC->isTranslationUnit()) {
1439     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1440       if (!RD->hasNameForLinkage())
1441         return true;
1442     }
1443     DC = DC->getParent();
1444   }
1445 
1446   return !D->isExternallyVisible();
1447 }
1448 
1449 // FIXME: This needs to be refactored; some other isInMainFile users want
1450 // these semantics.
1451 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1452   if (S.TUKind != TU_Complete)
1453     return false;
1454   return S.SourceMgr.isInMainFile(Loc);
1455 }
1456 
1457 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1458   assert(D);
1459 
1460   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1461     return false;
1462 
1463   // Ignore all entities declared within templates, and out-of-line definitions
1464   // of members of class templates.
1465   if (D->getDeclContext()->isDependentContext() ||
1466       D->getLexicalDeclContext()->isDependentContext())
1467     return false;
1468 
1469   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1470     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1471       return false;
1472 
1473     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1474       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1475         return false;
1476     } else {
1477       // 'static inline' functions are defined in headers; don't warn.
1478       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1479         return false;
1480     }
1481 
1482     if (FD->doesThisDeclarationHaveABody() &&
1483         Context.DeclMustBeEmitted(FD))
1484       return false;
1485   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1486     // Constants and utility variables are defined in headers with internal
1487     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1488     // like "inline".)
1489     if (!isMainFileLoc(*this, VD->getLocation()))
1490       return false;
1491 
1492     if (Context.DeclMustBeEmitted(VD))
1493       return false;
1494 
1495     if (VD->isStaticDataMember() &&
1496         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1497       return false;
1498 
1499     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1500       return false;
1501   } else {
1502     return false;
1503   }
1504 
1505   // Only warn for unused decls internal to the translation unit.
1506   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1507   // for inline functions defined in the main source file, for instance.
1508   return mightHaveNonExternalLinkage(D);
1509 }
1510 
1511 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1512   if (!D)
1513     return;
1514 
1515   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1516     const FunctionDecl *First = FD->getFirstDecl();
1517     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1518       return; // First should already be in the vector.
1519   }
1520 
1521   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1522     const VarDecl *First = VD->getFirstDecl();
1523     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1524       return; // First should already be in the vector.
1525   }
1526 
1527   if (ShouldWarnIfUnusedFileScopedDecl(D))
1528     UnusedFileScopedDecls.push_back(D);
1529 }
1530 
1531 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1532   if (D->isInvalidDecl())
1533     return false;
1534 
1535   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1536       D->hasAttr<ObjCPreciseLifetimeAttr>())
1537     return false;
1538 
1539   if (isa<LabelDecl>(D))
1540     return true;
1541 
1542   // Except for labels, we only care about unused decls that are local to
1543   // functions.
1544   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1545   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1546     // For dependent types, the diagnostic is deferred.
1547     WithinFunction =
1548         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1549   if (!WithinFunction)
1550     return false;
1551 
1552   if (isa<TypedefNameDecl>(D))
1553     return true;
1554 
1555   // White-list anything that isn't a local variable.
1556   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1557     return false;
1558 
1559   // Types of valid local variables should be complete, so this should succeed.
1560   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1561 
1562     // White-list anything with an __attribute__((unused)) type.
1563     const auto *Ty = VD->getType().getTypePtr();
1564 
1565     // Only look at the outermost level of typedef.
1566     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1567       if (TT->getDecl()->hasAttr<UnusedAttr>())
1568         return false;
1569     }
1570 
1571     // If we failed to complete the type for some reason, or if the type is
1572     // dependent, don't diagnose the variable.
1573     if (Ty->isIncompleteType() || Ty->isDependentType())
1574       return false;
1575 
1576     // Look at the element type to ensure that the warning behaviour is
1577     // consistent for both scalars and arrays.
1578     Ty = Ty->getBaseElementTypeUnsafe();
1579 
1580     if (const TagType *TT = Ty->getAs<TagType>()) {
1581       const TagDecl *Tag = TT->getDecl();
1582       if (Tag->hasAttr<UnusedAttr>())
1583         return false;
1584 
1585       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1586         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1587           return false;
1588 
1589         if (const Expr *Init = VD->getInit()) {
1590           if (const ExprWithCleanups *Cleanups =
1591                   dyn_cast<ExprWithCleanups>(Init))
1592             Init = Cleanups->getSubExpr();
1593           const CXXConstructExpr *Construct =
1594             dyn_cast<CXXConstructExpr>(Init);
1595           if (Construct && !Construct->isElidable()) {
1596             CXXConstructorDecl *CD = Construct->getConstructor();
1597             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1598               return false;
1599           }
1600         }
1601       }
1602     }
1603 
1604     // TODO: __attribute__((unused)) templates?
1605   }
1606 
1607   return true;
1608 }
1609 
1610 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1611                                      FixItHint &Hint) {
1612   if (isa<LabelDecl>(D)) {
1613     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1614                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1615     if (AfterColon.isInvalid())
1616       return;
1617     Hint = FixItHint::CreateRemoval(CharSourceRange::
1618                                     getCharRange(D->getLocStart(), AfterColon));
1619   }
1620 }
1621 
1622 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1623   if (D->getTypeForDecl()->isDependentType())
1624     return;
1625 
1626   for (auto *TmpD : D->decls()) {
1627     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1628       DiagnoseUnusedDecl(T);
1629     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1630       DiagnoseUnusedNestedTypedefs(R);
1631   }
1632 }
1633 
1634 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1635 /// unless they are marked attr(unused).
1636 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1637   if (!ShouldDiagnoseUnusedDecl(D))
1638     return;
1639 
1640   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1641     // typedefs can be referenced later on, so the diagnostics are emitted
1642     // at end-of-translation-unit.
1643     UnusedLocalTypedefNameCandidates.insert(TD);
1644     return;
1645   }
1646 
1647   FixItHint Hint;
1648   GenerateFixForUnusedDecl(D, Context, Hint);
1649 
1650   unsigned DiagID;
1651   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1652     DiagID = diag::warn_unused_exception_param;
1653   else if (isa<LabelDecl>(D))
1654     DiagID = diag::warn_unused_label;
1655   else
1656     DiagID = diag::warn_unused_variable;
1657 
1658   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1659 }
1660 
1661 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1662   // Verify that we have no forward references left.  If so, there was a goto
1663   // or address of a label taken, but no definition of it.  Label fwd
1664   // definitions are indicated with a null substmt which is also not a resolved
1665   // MS inline assembly label name.
1666   bool Diagnose = false;
1667   if (L->isMSAsmLabel())
1668     Diagnose = !L->isResolvedMSAsmLabel();
1669   else
1670     Diagnose = L->getStmt() == nullptr;
1671   if (Diagnose)
1672     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1673 }
1674 
1675 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1676   S->mergeNRVOIntoParent();
1677 
1678   if (S->decl_empty()) return;
1679   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1680          "Scope shouldn't contain decls!");
1681 
1682   for (auto *TmpD : S->decls()) {
1683     assert(TmpD && "This decl didn't get pushed??");
1684 
1685     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1686     NamedDecl *D = cast<NamedDecl>(TmpD);
1687 
1688     if (!D->getDeclName()) continue;
1689 
1690     // Diagnose unused variables in this scope.
1691     if (!S->hasUnrecoverableErrorOccurred()) {
1692       DiagnoseUnusedDecl(D);
1693       if (const auto *RD = dyn_cast<RecordDecl>(D))
1694         DiagnoseUnusedNestedTypedefs(RD);
1695     }
1696 
1697     // If this was a forward reference to a label, verify it was defined.
1698     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1699       CheckPoppedLabel(LD, *this);
1700 
1701     // Remove this name from our lexical scope, and warn on it if we haven't
1702     // already.
1703     IdResolver.RemoveDecl(D);
1704     auto ShadowI = ShadowingDecls.find(D);
1705     if (ShadowI != ShadowingDecls.end()) {
1706       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1707         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1708             << D << FD << FD->getParent();
1709         Diag(FD->getLocation(), diag::note_previous_declaration);
1710       }
1711       ShadowingDecls.erase(ShadowI);
1712     }
1713   }
1714 }
1715 
1716 /// \brief Look for an Objective-C class in the translation unit.
1717 ///
1718 /// \param Id The name of the Objective-C class we're looking for. If
1719 /// typo-correction fixes this name, the Id will be updated
1720 /// to the fixed name.
1721 ///
1722 /// \param IdLoc The location of the name in the translation unit.
1723 ///
1724 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1725 /// if there is no class with the given name.
1726 ///
1727 /// \returns The declaration of the named Objective-C class, or NULL if the
1728 /// class could not be found.
1729 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1730                                               SourceLocation IdLoc,
1731                                               bool DoTypoCorrection) {
1732   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1733   // creation from this context.
1734   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1735 
1736   if (!IDecl && DoTypoCorrection) {
1737     // Perform typo correction at the given location, but only if we
1738     // find an Objective-C class name.
1739     if (TypoCorrection C = CorrectTypo(
1740             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1741             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1742             CTK_ErrorRecovery)) {
1743       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1744       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1745       Id = IDecl->getIdentifier();
1746     }
1747   }
1748   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1749   // This routine must always return a class definition, if any.
1750   if (Def && Def->getDefinition())
1751       Def = Def->getDefinition();
1752   return Def;
1753 }
1754 
1755 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1756 /// from S, where a non-field would be declared. This routine copes
1757 /// with the difference between C and C++ scoping rules in structs and
1758 /// unions. For example, the following code is well-formed in C but
1759 /// ill-formed in C++:
1760 /// @code
1761 /// struct S6 {
1762 ///   enum { BAR } e;
1763 /// };
1764 ///
1765 /// void test_S6() {
1766 ///   struct S6 a;
1767 ///   a.e = BAR;
1768 /// }
1769 /// @endcode
1770 /// For the declaration of BAR, this routine will return a different
1771 /// scope. The scope S will be the scope of the unnamed enumeration
1772 /// within S6. In C++, this routine will return the scope associated
1773 /// with S6, because the enumeration's scope is a transparent
1774 /// context but structures can contain non-field names. In C, this
1775 /// routine will return the translation unit scope, since the
1776 /// enumeration's scope is a transparent context and structures cannot
1777 /// contain non-field names.
1778 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1779   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1780          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1781          (S->isClassScope() && !getLangOpts().CPlusPlus))
1782     S = S->getParent();
1783   return S;
1784 }
1785 
1786 /// \brief Looks up the declaration of "struct objc_super" and
1787 /// saves it for later use in building builtin declaration of
1788 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1789 /// pre-existing declaration exists no action takes place.
1790 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1791                                         IdentifierInfo *II) {
1792   if (!II->isStr("objc_msgSendSuper"))
1793     return;
1794   ASTContext &Context = ThisSema.Context;
1795 
1796   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1797                       SourceLocation(), Sema::LookupTagName);
1798   ThisSema.LookupName(Result, S);
1799   if (Result.getResultKind() == LookupResult::Found)
1800     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1801       Context.setObjCSuperType(Context.getTagDeclType(TD));
1802 }
1803 
1804 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1805   switch (Error) {
1806   case ASTContext::GE_None:
1807     return "";
1808   case ASTContext::GE_Missing_stdio:
1809     return "stdio.h";
1810   case ASTContext::GE_Missing_setjmp:
1811     return "setjmp.h";
1812   case ASTContext::GE_Missing_ucontext:
1813     return "ucontext.h";
1814   }
1815   llvm_unreachable("unhandled error kind");
1816 }
1817 
1818 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1819 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1820 /// if we're creating this built-in in anticipation of redeclaring the
1821 /// built-in.
1822 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1823                                      Scope *S, bool ForRedeclaration,
1824                                      SourceLocation Loc) {
1825   LookupPredefedObjCSuperType(*this, S, II);
1826 
1827   ASTContext::GetBuiltinTypeError Error;
1828   QualType R = Context.GetBuiltinType(ID, Error);
1829   if (Error) {
1830     if (ForRedeclaration)
1831       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1832           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1833     return nullptr;
1834   }
1835 
1836   if (!ForRedeclaration &&
1837       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1838        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1839     Diag(Loc, diag::ext_implicit_lib_function_decl)
1840         << Context.BuiltinInfo.getName(ID) << R;
1841     if (Context.BuiltinInfo.getHeaderName(ID) &&
1842         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1843       Diag(Loc, diag::note_include_header_or_declare)
1844           << Context.BuiltinInfo.getHeaderName(ID)
1845           << Context.BuiltinInfo.getName(ID);
1846   }
1847 
1848   if (R.isNull())
1849     return nullptr;
1850 
1851   DeclContext *Parent = Context.getTranslationUnitDecl();
1852   if (getLangOpts().CPlusPlus) {
1853     LinkageSpecDecl *CLinkageDecl =
1854         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1855                                 LinkageSpecDecl::lang_c, false);
1856     CLinkageDecl->setImplicit();
1857     Parent->addDecl(CLinkageDecl);
1858     Parent = CLinkageDecl;
1859   }
1860 
1861   FunctionDecl *New = FunctionDecl::Create(Context,
1862                                            Parent,
1863                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1864                                            SC_Extern,
1865                                            false,
1866                                            R->isFunctionProtoType());
1867   New->setImplicit();
1868 
1869   // Create Decl objects for each parameter, adding them to the
1870   // FunctionDecl.
1871   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1872     SmallVector<ParmVarDecl*, 16> Params;
1873     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1874       ParmVarDecl *parm =
1875           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1876                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1877                               SC_None, nullptr);
1878       parm->setScopeInfo(0, i);
1879       Params.push_back(parm);
1880     }
1881     New->setParams(Params);
1882   }
1883 
1884   AddKnownFunctionAttributes(New);
1885   RegisterLocallyScopedExternCDecl(New, S);
1886 
1887   // TUScope is the translation-unit scope to insert this function into.
1888   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1889   // relate Scopes to DeclContexts, and probably eliminate CurContext
1890   // entirely, but we're not there yet.
1891   DeclContext *SavedContext = CurContext;
1892   CurContext = Parent;
1893   PushOnScopeChains(New, TUScope);
1894   CurContext = SavedContext;
1895   return New;
1896 }
1897 
1898 /// Typedef declarations don't have linkage, but they still denote the same
1899 /// entity if their types are the same.
1900 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1901 /// isSameEntity.
1902 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1903                                                      TypedefNameDecl *Decl,
1904                                                      LookupResult &Previous) {
1905   // This is only interesting when modules are enabled.
1906   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1907     return;
1908 
1909   // Empty sets are uninteresting.
1910   if (Previous.empty())
1911     return;
1912 
1913   LookupResult::Filter Filter = Previous.makeFilter();
1914   while (Filter.hasNext()) {
1915     NamedDecl *Old = Filter.next();
1916 
1917     // Non-hidden declarations are never ignored.
1918     if (S.isVisible(Old))
1919       continue;
1920 
1921     // Declarations of the same entity are not ignored, even if they have
1922     // different linkages.
1923     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1924       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1925                                 Decl->getUnderlyingType()))
1926         continue;
1927 
1928       // If both declarations give a tag declaration a typedef name for linkage
1929       // purposes, then they declare the same entity.
1930       if (S.getLangOpts().CPlusPlus &&
1931           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1932           Decl->getAnonDeclWithTypedefName())
1933         continue;
1934     }
1935 
1936     Filter.erase();
1937   }
1938 
1939   Filter.done();
1940 }
1941 
1942 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1943   QualType OldType;
1944   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1945     OldType = OldTypedef->getUnderlyingType();
1946   else
1947     OldType = Context.getTypeDeclType(Old);
1948   QualType NewType = New->getUnderlyingType();
1949 
1950   if (NewType->isVariablyModifiedType()) {
1951     // Must not redefine a typedef with a variably-modified type.
1952     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1953     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1954       << Kind << NewType;
1955     if (Old->getLocation().isValid())
1956       Diag(Old->getLocation(), diag::note_previous_definition);
1957     New->setInvalidDecl();
1958     return true;
1959   }
1960 
1961   if (OldType != NewType &&
1962       !OldType->isDependentType() &&
1963       !NewType->isDependentType() &&
1964       !Context.hasSameType(OldType, NewType)) {
1965     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1966     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1967       << Kind << NewType << OldType;
1968     if (Old->getLocation().isValid())
1969       Diag(Old->getLocation(), diag::note_previous_definition);
1970     New->setInvalidDecl();
1971     return true;
1972   }
1973   return false;
1974 }
1975 
1976 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1977 /// same name and scope as a previous declaration 'Old'.  Figure out
1978 /// how to resolve this situation, merging decls or emitting
1979 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1980 ///
1981 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
1982                                 LookupResult &OldDecls) {
1983   // If the new decl is known invalid already, don't bother doing any
1984   // merging checks.
1985   if (New->isInvalidDecl()) return;
1986 
1987   // Allow multiple definitions for ObjC built-in typedefs.
1988   // FIXME: Verify the underlying types are equivalent!
1989   if (getLangOpts().ObjC1) {
1990     const IdentifierInfo *TypeID = New->getIdentifier();
1991     switch (TypeID->getLength()) {
1992     default: break;
1993     case 2:
1994       {
1995         if (!TypeID->isStr("id"))
1996           break;
1997         QualType T = New->getUnderlyingType();
1998         if (!T->isPointerType())
1999           break;
2000         if (!T->isVoidPointerType()) {
2001           QualType PT = T->getAs<PointerType>()->getPointeeType();
2002           if (!PT->isStructureType())
2003             break;
2004         }
2005         Context.setObjCIdRedefinitionType(T);
2006         // Install the built-in type for 'id', ignoring the current definition.
2007         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2008         return;
2009       }
2010     case 5:
2011       if (!TypeID->isStr("Class"))
2012         break;
2013       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
2014       // Install the built-in type for 'Class', ignoring the current definition.
2015       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2016       return;
2017     case 3:
2018       if (!TypeID->isStr("SEL"))
2019         break;
2020       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
2021       // Install the built-in type for 'SEL', ignoring the current definition.
2022       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2023       return;
2024     }
2025     // Fall through - the typedef name was not a builtin type.
2026   }
2027 
2028   // Verify the old decl was also a type.
2029   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2030   if (!Old) {
2031     Diag(New->getLocation(), diag::err_redefinition_different_kind)
2032       << New->getDeclName();
2033 
2034     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2035     if (OldD->getLocation().isValid())
2036       Diag(OldD->getLocation(), diag::note_previous_definition);
2037 
2038     return New->setInvalidDecl();
2039   }
2040 
2041   // If the old declaration is invalid, just give up here.
2042   if (Old->isInvalidDecl())
2043     return New->setInvalidDecl();
2044 
2045   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2046     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2047     auto *NewTag = New->getAnonDeclWithTypedefName();
2048     NamedDecl *Hidden = nullptr;
2049     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
2050         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2051         !hasVisibleDefinition(OldTag, &Hidden)) {
2052       // There is a definition of this tag, but it is not visible. Use it
2053       // instead of our tag.
2054       New->setTypeForDecl(OldTD->getTypeForDecl());
2055       if (OldTD->isModed())
2056         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2057                                     OldTD->getUnderlyingType());
2058       else
2059         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2060 
2061       // Make the old tag definition visible.
2062       makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
2063 
2064       // If this was an unscoped enumeration, yank all of its enumerators
2065       // out of the scope.
2066       if (isa<EnumDecl>(NewTag)) {
2067         Scope *EnumScope = getNonFieldDeclScope(S);
2068         for (auto *D : NewTag->decls()) {
2069           auto *ED = cast<EnumConstantDecl>(D);
2070           assert(EnumScope->isDeclScope(ED));
2071           EnumScope->RemoveDecl(ED);
2072           IdResolver.RemoveDecl(ED);
2073           ED->getLexicalDeclContext()->removeDecl(ED);
2074         }
2075       }
2076     }
2077   }
2078 
2079   // If the typedef types are not identical, reject them in all languages and
2080   // with any extensions enabled.
2081   if (isIncompatibleTypedef(Old, New))
2082     return;
2083 
2084   // The types match.  Link up the redeclaration chain and merge attributes if
2085   // the old declaration was a typedef.
2086   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2087     New->setPreviousDecl(Typedef);
2088     mergeDeclAttributes(New, Old);
2089   }
2090 
2091   if (getLangOpts().MicrosoftExt)
2092     return;
2093 
2094   if (getLangOpts().CPlusPlus) {
2095     // C++ [dcl.typedef]p2:
2096     //   In a given non-class scope, a typedef specifier can be used to
2097     //   redefine the name of any type declared in that scope to refer
2098     //   to the type to which it already refers.
2099     if (!isa<CXXRecordDecl>(CurContext))
2100       return;
2101 
2102     // C++0x [dcl.typedef]p4:
2103     //   In a given class scope, a typedef specifier can be used to redefine
2104     //   any class-name declared in that scope that is not also a typedef-name
2105     //   to refer to the type to which it already refers.
2106     //
2107     // This wording came in via DR424, which was a correction to the
2108     // wording in DR56, which accidentally banned code like:
2109     //
2110     //   struct S {
2111     //     typedef struct A { } A;
2112     //   };
2113     //
2114     // in the C++03 standard. We implement the C++0x semantics, which
2115     // allow the above but disallow
2116     //
2117     //   struct S {
2118     //     typedef int I;
2119     //     typedef int I;
2120     //   };
2121     //
2122     // since that was the intent of DR56.
2123     if (!isa<TypedefNameDecl>(Old))
2124       return;
2125 
2126     Diag(New->getLocation(), diag::err_redefinition)
2127       << New->getDeclName();
2128     Diag(Old->getLocation(), diag::note_previous_definition);
2129     return New->setInvalidDecl();
2130   }
2131 
2132   // Modules always permit redefinition of typedefs, as does C11.
2133   if (getLangOpts().Modules || getLangOpts().C11)
2134     return;
2135 
2136   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2137   // is normally mapped to an error, but can be controlled with
2138   // -Wtypedef-redefinition.  If either the original or the redefinition is
2139   // in a system header, don't emit this for compatibility with GCC.
2140   if (getDiagnostics().getSuppressSystemWarnings() &&
2141       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2142        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2143     return;
2144 
2145   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2146     << New->getDeclName();
2147   Diag(Old->getLocation(), diag::note_previous_definition);
2148 }
2149 
2150 /// DeclhasAttr - returns true if decl Declaration already has the target
2151 /// attribute.
2152 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2153   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2154   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2155   for (const auto *i : D->attrs())
2156     if (i->getKind() == A->getKind()) {
2157       if (Ann) {
2158         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2159           return true;
2160         continue;
2161       }
2162       // FIXME: Don't hardcode this check
2163       if (OA && isa<OwnershipAttr>(i))
2164         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2165       return true;
2166     }
2167 
2168   return false;
2169 }
2170 
2171 static bool isAttributeTargetADefinition(Decl *D) {
2172   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2173     return VD->isThisDeclarationADefinition();
2174   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2175     return TD->isCompleteDefinition() || TD->isBeingDefined();
2176   return true;
2177 }
2178 
2179 /// Merge alignment attributes from \p Old to \p New, taking into account the
2180 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2181 ///
2182 /// \return \c true if any attributes were added to \p New.
2183 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2184   // Look for alignas attributes on Old, and pick out whichever attribute
2185   // specifies the strictest alignment requirement.
2186   AlignedAttr *OldAlignasAttr = nullptr;
2187   AlignedAttr *OldStrictestAlignAttr = nullptr;
2188   unsigned OldAlign = 0;
2189   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2190     // FIXME: We have no way of representing inherited dependent alignments
2191     // in a case like:
2192     //   template<int A, int B> struct alignas(A) X;
2193     //   template<int A, int B> struct alignas(B) X {};
2194     // For now, we just ignore any alignas attributes which are not on the
2195     // definition in such a case.
2196     if (I->isAlignmentDependent())
2197       return false;
2198 
2199     if (I->isAlignas())
2200       OldAlignasAttr = I;
2201 
2202     unsigned Align = I->getAlignment(S.Context);
2203     if (Align > OldAlign) {
2204       OldAlign = Align;
2205       OldStrictestAlignAttr = I;
2206     }
2207   }
2208 
2209   // Look for alignas attributes on New.
2210   AlignedAttr *NewAlignasAttr = nullptr;
2211   unsigned NewAlign = 0;
2212   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2213     if (I->isAlignmentDependent())
2214       return false;
2215 
2216     if (I->isAlignas())
2217       NewAlignasAttr = I;
2218 
2219     unsigned Align = I->getAlignment(S.Context);
2220     if (Align > NewAlign)
2221       NewAlign = Align;
2222   }
2223 
2224   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2225     // Both declarations have 'alignas' attributes. We require them to match.
2226     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2227     // fall short. (If two declarations both have alignas, they must both match
2228     // every definition, and so must match each other if there is a definition.)
2229 
2230     // If either declaration only contains 'alignas(0)' specifiers, then it
2231     // specifies the natural alignment for the type.
2232     if (OldAlign == 0 || NewAlign == 0) {
2233       QualType Ty;
2234       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2235         Ty = VD->getType();
2236       else
2237         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2238 
2239       if (OldAlign == 0)
2240         OldAlign = S.Context.getTypeAlign(Ty);
2241       if (NewAlign == 0)
2242         NewAlign = S.Context.getTypeAlign(Ty);
2243     }
2244 
2245     if (OldAlign != NewAlign) {
2246       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2247         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2248         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2249       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2250     }
2251   }
2252 
2253   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2254     // C++11 [dcl.align]p6:
2255     //   if any declaration of an entity has an alignment-specifier,
2256     //   every defining declaration of that entity shall specify an
2257     //   equivalent alignment.
2258     // C11 6.7.5/7:
2259     //   If the definition of an object does not have an alignment
2260     //   specifier, any other declaration of that object shall also
2261     //   have no alignment specifier.
2262     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2263       << OldAlignasAttr;
2264     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2265       << OldAlignasAttr;
2266   }
2267 
2268   bool AnyAdded = false;
2269 
2270   // Ensure we have an attribute representing the strictest alignment.
2271   if (OldAlign > NewAlign) {
2272     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2273     Clone->setInherited(true);
2274     New->addAttr(Clone);
2275     AnyAdded = true;
2276   }
2277 
2278   // Ensure we have an alignas attribute if the old declaration had one.
2279   if (OldAlignasAttr && !NewAlignasAttr &&
2280       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2281     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2282     Clone->setInherited(true);
2283     New->addAttr(Clone);
2284     AnyAdded = true;
2285   }
2286 
2287   return AnyAdded;
2288 }
2289 
2290 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2291                                const InheritableAttr *Attr,
2292                                Sema::AvailabilityMergeKind AMK) {
2293   // This function copies an attribute Attr from a previous declaration to the
2294   // new declaration D if the new declaration doesn't itself have that attribute
2295   // yet or if that attribute allows duplicates.
2296   // If you're adding a new attribute that requires logic different from
2297   // "use explicit attribute on decl if present, else use attribute from
2298   // previous decl", for example if the attribute needs to be consistent
2299   // between redeclarations, you need to call a custom merge function here.
2300   InheritableAttr *NewAttr = nullptr;
2301   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2302   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2303     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2304                                       AA->isImplicit(), AA->getIntroduced(),
2305                                       AA->getDeprecated(),
2306                                       AA->getObsoleted(), AA->getUnavailable(),
2307                                       AA->getMessage(), AA->getStrict(),
2308                                       AA->getReplacement(), AMK,
2309                                       AttrSpellingListIndex);
2310   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2311     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2312                                     AttrSpellingListIndex);
2313   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2314     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2315                                         AttrSpellingListIndex);
2316   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2317     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2318                                    AttrSpellingListIndex);
2319   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2320     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2321                                    AttrSpellingListIndex);
2322   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2323     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2324                                 FA->getFormatIdx(), FA->getFirstArg(),
2325                                 AttrSpellingListIndex);
2326   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2327     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2328                                  AttrSpellingListIndex);
2329   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2330     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2331                                        AttrSpellingListIndex,
2332                                        IA->getSemanticSpelling());
2333   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2334     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2335                                       &S.Context.Idents.get(AA->getSpelling()),
2336                                       AttrSpellingListIndex);
2337   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2338            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2339             isa<CUDAGlobalAttr>(Attr))) {
2340     // CUDA target attributes are part of function signature for
2341     // overloading purposes and must not be merged.
2342     return false;
2343   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2344     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2345   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2346     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2347   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2348     NewAttr = S.mergeInternalLinkageAttr(
2349         D, InternalLinkageA->getRange(),
2350         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2351         AttrSpellingListIndex);
2352   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2353     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2354                                 &S.Context.Idents.get(CommonA->getSpelling()),
2355                                 AttrSpellingListIndex);
2356   else if (isa<AlignedAttr>(Attr))
2357     // AlignedAttrs are handled separately, because we need to handle all
2358     // such attributes on a declaration at the same time.
2359     NewAttr = nullptr;
2360   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2361            (AMK == Sema::AMK_Override ||
2362             AMK == Sema::AMK_ProtocolImplementation))
2363     NewAttr = nullptr;
2364   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2365     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2366                               UA->getGuid());
2367   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2368     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2369 
2370   if (NewAttr) {
2371     NewAttr->setInherited(true);
2372     D->addAttr(NewAttr);
2373     if (isa<MSInheritanceAttr>(NewAttr))
2374       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2375     return true;
2376   }
2377 
2378   return false;
2379 }
2380 
2381 static const Decl *getDefinition(const Decl *D) {
2382   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2383     return TD->getDefinition();
2384   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2385     const VarDecl *Def = VD->getDefinition();
2386     if (Def)
2387       return Def;
2388     return VD->getActingDefinition();
2389   }
2390   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2391     return FD->getDefinition();
2392   return nullptr;
2393 }
2394 
2395 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2396   for (const auto *Attribute : D->attrs())
2397     if (Attribute->getKind() == Kind)
2398       return true;
2399   return false;
2400 }
2401 
2402 /// checkNewAttributesAfterDef - If we already have a definition, check that
2403 /// there are no new attributes in this declaration.
2404 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2405   if (!New->hasAttrs())
2406     return;
2407 
2408   const Decl *Def = getDefinition(Old);
2409   if (!Def || Def == New)
2410     return;
2411 
2412   AttrVec &NewAttributes = New->getAttrs();
2413   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2414     const Attr *NewAttribute = NewAttributes[I];
2415 
2416     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2417       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2418         Sema::SkipBodyInfo SkipBody;
2419         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2420 
2421         // If we're skipping this definition, drop the "alias" attribute.
2422         if (SkipBody.ShouldSkip) {
2423           NewAttributes.erase(NewAttributes.begin() + I);
2424           --E;
2425           continue;
2426         }
2427       } else {
2428         VarDecl *VD = cast<VarDecl>(New);
2429         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2430                                 VarDecl::TentativeDefinition
2431                             ? diag::err_alias_after_tentative
2432                             : diag::err_redefinition;
2433         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2434         S.Diag(Def->getLocation(), diag::note_previous_definition);
2435         VD->setInvalidDecl();
2436       }
2437       ++I;
2438       continue;
2439     }
2440 
2441     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2442       // Tentative definitions are only interesting for the alias check above.
2443       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2444         ++I;
2445         continue;
2446       }
2447     }
2448 
2449     if (hasAttribute(Def, NewAttribute->getKind())) {
2450       ++I;
2451       continue; // regular attr merging will take care of validating this.
2452     }
2453 
2454     if (isa<C11NoReturnAttr>(NewAttribute)) {
2455       // C's _Noreturn is allowed to be added to a function after it is defined.
2456       ++I;
2457       continue;
2458     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2459       if (AA->isAlignas()) {
2460         // C++11 [dcl.align]p6:
2461         //   if any declaration of an entity has an alignment-specifier,
2462         //   every defining declaration of that entity shall specify an
2463         //   equivalent alignment.
2464         // C11 6.7.5/7:
2465         //   If the definition of an object does not have an alignment
2466         //   specifier, any other declaration of that object shall also
2467         //   have no alignment specifier.
2468         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2469           << AA;
2470         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2471           << AA;
2472         NewAttributes.erase(NewAttributes.begin() + I);
2473         --E;
2474         continue;
2475       }
2476     }
2477 
2478     S.Diag(NewAttribute->getLocation(),
2479            diag::warn_attribute_precede_definition);
2480     S.Diag(Def->getLocation(), diag::note_previous_definition);
2481     NewAttributes.erase(NewAttributes.begin() + I);
2482     --E;
2483   }
2484 }
2485 
2486 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2487 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2488                                AvailabilityMergeKind AMK) {
2489   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2490     UsedAttr *NewAttr = OldAttr->clone(Context);
2491     NewAttr->setInherited(true);
2492     New->addAttr(NewAttr);
2493   }
2494 
2495   if (!Old->hasAttrs() && !New->hasAttrs())
2496     return;
2497 
2498   // Attributes declared post-definition are currently ignored.
2499   checkNewAttributesAfterDef(*this, New, Old);
2500 
2501   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2502     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2503       if (OldA->getLabel() != NewA->getLabel()) {
2504         // This redeclaration changes __asm__ label.
2505         Diag(New->getLocation(), diag::err_different_asm_label);
2506         Diag(OldA->getLocation(), diag::note_previous_declaration);
2507       }
2508     } else if (Old->isUsed()) {
2509       // This redeclaration adds an __asm__ label to a declaration that has
2510       // already been ODR-used.
2511       Diag(New->getLocation(), diag::err_late_asm_label_name)
2512         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2513     }
2514   }
2515 
2516   // Re-declaration cannot add abi_tag's.
2517   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2518     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2519       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2520         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2521                       NewTag) == OldAbiTagAttr->tags_end()) {
2522           Diag(NewAbiTagAttr->getLocation(),
2523                diag::err_new_abi_tag_on_redeclaration)
2524               << NewTag;
2525           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2526         }
2527       }
2528     } else {
2529       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2530       Diag(Old->getLocation(), diag::note_previous_declaration);
2531     }
2532   }
2533 
2534   if (!Old->hasAttrs())
2535     return;
2536 
2537   bool foundAny = New->hasAttrs();
2538 
2539   // Ensure that any moving of objects within the allocated map is done before
2540   // we process them.
2541   if (!foundAny) New->setAttrs(AttrVec());
2542 
2543   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2544     // Ignore deprecated/unavailable/availability attributes if requested.
2545     AvailabilityMergeKind LocalAMK = AMK_None;
2546     if (isa<DeprecatedAttr>(I) ||
2547         isa<UnavailableAttr>(I) ||
2548         isa<AvailabilityAttr>(I)) {
2549       switch (AMK) {
2550       case AMK_None:
2551         continue;
2552 
2553       case AMK_Redeclaration:
2554       case AMK_Override:
2555       case AMK_ProtocolImplementation:
2556         LocalAMK = AMK;
2557         break;
2558       }
2559     }
2560 
2561     // Already handled.
2562     if (isa<UsedAttr>(I))
2563       continue;
2564 
2565     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2566       foundAny = true;
2567   }
2568 
2569   if (mergeAlignedAttrs(*this, New, Old))
2570     foundAny = true;
2571 
2572   if (!foundAny) New->dropAttrs();
2573 }
2574 
2575 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2576 /// to the new one.
2577 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2578                                      const ParmVarDecl *oldDecl,
2579                                      Sema &S) {
2580   // C++11 [dcl.attr.depend]p2:
2581   //   The first declaration of a function shall specify the
2582   //   carries_dependency attribute for its declarator-id if any declaration
2583   //   of the function specifies the carries_dependency attribute.
2584   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2585   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2586     S.Diag(CDA->getLocation(),
2587            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2588     // Find the first declaration of the parameter.
2589     // FIXME: Should we build redeclaration chains for function parameters?
2590     const FunctionDecl *FirstFD =
2591       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2592     const ParmVarDecl *FirstVD =
2593       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2594     S.Diag(FirstVD->getLocation(),
2595            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2596   }
2597 
2598   if (!oldDecl->hasAttrs())
2599     return;
2600 
2601   bool foundAny = newDecl->hasAttrs();
2602 
2603   // Ensure that any moving of objects within the allocated map is
2604   // done before we process them.
2605   if (!foundAny) newDecl->setAttrs(AttrVec());
2606 
2607   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2608     if (!DeclHasAttr(newDecl, I)) {
2609       InheritableAttr *newAttr =
2610         cast<InheritableParamAttr>(I->clone(S.Context));
2611       newAttr->setInherited(true);
2612       newDecl->addAttr(newAttr);
2613       foundAny = true;
2614     }
2615   }
2616 
2617   if (!foundAny) newDecl->dropAttrs();
2618 }
2619 
2620 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2621                                 const ParmVarDecl *OldParam,
2622                                 Sema &S) {
2623   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2624     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2625       if (*Oldnullability != *Newnullability) {
2626         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2627           << DiagNullabilityKind(
2628                *Newnullability,
2629                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2630                 != 0))
2631           << DiagNullabilityKind(
2632                *Oldnullability,
2633                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2634                 != 0));
2635         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2636       }
2637     } else {
2638       QualType NewT = NewParam->getType();
2639       NewT = S.Context.getAttributedType(
2640                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2641                          NewT, NewT);
2642       NewParam->setType(NewT);
2643     }
2644   }
2645 }
2646 
2647 namespace {
2648 
2649 /// Used in MergeFunctionDecl to keep track of function parameters in
2650 /// C.
2651 struct GNUCompatibleParamWarning {
2652   ParmVarDecl *OldParm;
2653   ParmVarDecl *NewParm;
2654   QualType PromotedType;
2655 };
2656 
2657 } // end anonymous namespace
2658 
2659 /// getSpecialMember - get the special member enum for a method.
2660 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2661   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2662     if (Ctor->isDefaultConstructor())
2663       return Sema::CXXDefaultConstructor;
2664 
2665     if (Ctor->isCopyConstructor())
2666       return Sema::CXXCopyConstructor;
2667 
2668     if (Ctor->isMoveConstructor())
2669       return Sema::CXXMoveConstructor;
2670   } else if (isa<CXXDestructorDecl>(MD)) {
2671     return Sema::CXXDestructor;
2672   } else if (MD->isCopyAssignmentOperator()) {
2673     return Sema::CXXCopyAssignment;
2674   } else if (MD->isMoveAssignmentOperator()) {
2675     return Sema::CXXMoveAssignment;
2676   }
2677 
2678   return Sema::CXXInvalid;
2679 }
2680 
2681 // Determine whether the previous declaration was a definition, implicit
2682 // declaration, or a declaration.
2683 template <typename T>
2684 static std::pair<diag::kind, SourceLocation>
2685 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2686   diag::kind PrevDiag;
2687   SourceLocation OldLocation = Old->getLocation();
2688   if (Old->isThisDeclarationADefinition())
2689     PrevDiag = diag::note_previous_definition;
2690   else if (Old->isImplicit()) {
2691     PrevDiag = diag::note_previous_implicit_declaration;
2692     if (OldLocation.isInvalid())
2693       OldLocation = New->getLocation();
2694   } else
2695     PrevDiag = diag::note_previous_declaration;
2696   return std::make_pair(PrevDiag, OldLocation);
2697 }
2698 
2699 /// canRedefineFunction - checks if a function can be redefined. Currently,
2700 /// only extern inline functions can be redefined, and even then only in
2701 /// GNU89 mode.
2702 static bool canRedefineFunction(const FunctionDecl *FD,
2703                                 const LangOptions& LangOpts) {
2704   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2705           !LangOpts.CPlusPlus &&
2706           FD->isInlineSpecified() &&
2707           FD->getStorageClass() == SC_Extern);
2708 }
2709 
2710 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2711   const AttributedType *AT = T->getAs<AttributedType>();
2712   while (AT && !AT->isCallingConv())
2713     AT = AT->getModifiedType()->getAs<AttributedType>();
2714   return AT;
2715 }
2716 
2717 template <typename T>
2718 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2719   const DeclContext *DC = Old->getDeclContext();
2720   if (DC->isRecord())
2721     return false;
2722 
2723   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2724   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2725     return true;
2726   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2727     return true;
2728   return false;
2729 }
2730 
2731 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2732 static bool isExternC(VarTemplateDecl *) { return false; }
2733 
2734 /// \brief Check whether a redeclaration of an entity introduced by a
2735 /// using-declaration is valid, given that we know it's not an overload
2736 /// (nor a hidden tag declaration).
2737 template<typename ExpectedDecl>
2738 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2739                                    ExpectedDecl *New) {
2740   // C++11 [basic.scope.declarative]p4:
2741   //   Given a set of declarations in a single declarative region, each of
2742   //   which specifies the same unqualified name,
2743   //   -- they shall all refer to the same entity, or all refer to functions
2744   //      and function templates; or
2745   //   -- exactly one declaration shall declare a class name or enumeration
2746   //      name that is not a typedef name and the other declarations shall all
2747   //      refer to the same variable or enumerator, or all refer to functions
2748   //      and function templates; in this case the class name or enumeration
2749   //      name is hidden (3.3.10).
2750 
2751   // C++11 [namespace.udecl]p14:
2752   //   If a function declaration in namespace scope or block scope has the
2753   //   same name and the same parameter-type-list as a function introduced
2754   //   by a using-declaration, and the declarations do not declare the same
2755   //   function, the program is ill-formed.
2756 
2757   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2758   if (Old &&
2759       !Old->getDeclContext()->getRedeclContext()->Equals(
2760           New->getDeclContext()->getRedeclContext()) &&
2761       !(isExternC(Old) && isExternC(New)))
2762     Old = nullptr;
2763 
2764   if (!Old) {
2765     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2766     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2767     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2768     return true;
2769   }
2770   return false;
2771 }
2772 
2773 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2774                                             const FunctionDecl *B) {
2775   assert(A->getNumParams() == B->getNumParams());
2776 
2777   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2778     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2779     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2780     if (AttrA == AttrB)
2781       return true;
2782     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2783   };
2784 
2785   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2786 }
2787 
2788 /// MergeFunctionDecl - We just parsed a function 'New' from
2789 /// declarator D which has the same name and scope as a previous
2790 /// declaration 'Old'.  Figure out how to resolve this situation,
2791 /// merging decls or emitting diagnostics as appropriate.
2792 ///
2793 /// In C++, New and Old must be declarations that are not
2794 /// overloaded. Use IsOverload to determine whether New and Old are
2795 /// overloaded, and to select the Old declaration that New should be
2796 /// merged with.
2797 ///
2798 /// Returns true if there was an error, false otherwise.
2799 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2800                              Scope *S, bool MergeTypeWithOld) {
2801   // Verify the old decl was also a function.
2802   FunctionDecl *Old = OldD->getAsFunction();
2803   if (!Old) {
2804     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2805       if (New->getFriendObjectKind()) {
2806         Diag(New->getLocation(), diag::err_using_decl_friend);
2807         Diag(Shadow->getTargetDecl()->getLocation(),
2808              diag::note_using_decl_target);
2809         Diag(Shadow->getUsingDecl()->getLocation(),
2810              diag::note_using_decl) << 0;
2811         return true;
2812       }
2813 
2814       // Check whether the two declarations might declare the same function.
2815       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2816         return true;
2817       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2818     } else {
2819       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2820         << New->getDeclName();
2821       Diag(OldD->getLocation(), diag::note_previous_definition);
2822       return true;
2823     }
2824   }
2825 
2826   // If the old declaration is invalid, just give up here.
2827   if (Old->isInvalidDecl())
2828     return true;
2829 
2830   diag::kind PrevDiag;
2831   SourceLocation OldLocation;
2832   std::tie(PrevDiag, OldLocation) =
2833       getNoteDiagForInvalidRedeclaration(Old, New);
2834 
2835   // Don't complain about this if we're in GNU89 mode and the old function
2836   // is an extern inline function.
2837   // Don't complain about specializations. They are not supposed to have
2838   // storage classes.
2839   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2840       New->getStorageClass() == SC_Static &&
2841       Old->hasExternalFormalLinkage() &&
2842       !New->getTemplateSpecializationInfo() &&
2843       !canRedefineFunction(Old, getLangOpts())) {
2844     if (getLangOpts().MicrosoftExt) {
2845       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2846       Diag(OldLocation, PrevDiag);
2847     } else {
2848       Diag(New->getLocation(), diag::err_static_non_static) << New;
2849       Diag(OldLocation, PrevDiag);
2850       return true;
2851     }
2852   }
2853 
2854   if (New->hasAttr<InternalLinkageAttr>() &&
2855       !Old->hasAttr<InternalLinkageAttr>()) {
2856     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2857         << New->getDeclName();
2858     Diag(Old->getLocation(), diag::note_previous_definition);
2859     New->dropAttr<InternalLinkageAttr>();
2860   }
2861 
2862   // If a function is first declared with a calling convention, but is later
2863   // declared or defined without one, all following decls assume the calling
2864   // convention of the first.
2865   //
2866   // It's OK if a function is first declared without a calling convention,
2867   // but is later declared or defined with the default calling convention.
2868   //
2869   // To test if either decl has an explicit calling convention, we look for
2870   // AttributedType sugar nodes on the type as written.  If they are missing or
2871   // were canonicalized away, we assume the calling convention was implicit.
2872   //
2873   // Note also that we DO NOT return at this point, because we still have
2874   // other tests to run.
2875   QualType OldQType = Context.getCanonicalType(Old->getType());
2876   QualType NewQType = Context.getCanonicalType(New->getType());
2877   const FunctionType *OldType = cast<FunctionType>(OldQType);
2878   const FunctionType *NewType = cast<FunctionType>(NewQType);
2879   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2880   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2881   bool RequiresAdjustment = false;
2882 
2883   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2884     FunctionDecl *First = Old->getFirstDecl();
2885     const FunctionType *FT =
2886         First->getType().getCanonicalType()->castAs<FunctionType>();
2887     FunctionType::ExtInfo FI = FT->getExtInfo();
2888     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2889     if (!NewCCExplicit) {
2890       // Inherit the CC from the previous declaration if it was specified
2891       // there but not here.
2892       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2893       RequiresAdjustment = true;
2894     } else {
2895       // Calling conventions aren't compatible, so complain.
2896       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2897       Diag(New->getLocation(), diag::err_cconv_change)
2898         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2899         << !FirstCCExplicit
2900         << (!FirstCCExplicit ? "" :
2901             FunctionType::getNameForCallConv(FI.getCC()));
2902 
2903       // Put the note on the first decl, since it is the one that matters.
2904       Diag(First->getLocation(), diag::note_previous_declaration);
2905       return true;
2906     }
2907   }
2908 
2909   // FIXME: diagnose the other way around?
2910   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2911     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2912     RequiresAdjustment = true;
2913   }
2914 
2915   // Merge regparm attribute.
2916   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2917       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2918     if (NewTypeInfo.getHasRegParm()) {
2919       Diag(New->getLocation(), diag::err_regparm_mismatch)
2920         << NewType->getRegParmType()
2921         << OldType->getRegParmType();
2922       Diag(OldLocation, diag::note_previous_declaration);
2923       return true;
2924     }
2925 
2926     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2927     RequiresAdjustment = true;
2928   }
2929 
2930   // Merge ns_returns_retained attribute.
2931   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2932     if (NewTypeInfo.getProducesResult()) {
2933       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2934       Diag(OldLocation, diag::note_previous_declaration);
2935       return true;
2936     }
2937 
2938     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2939     RequiresAdjustment = true;
2940   }
2941 
2942   if (RequiresAdjustment) {
2943     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2944     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2945     New->setType(QualType(AdjustedType, 0));
2946     NewQType = Context.getCanonicalType(New->getType());
2947     NewType = cast<FunctionType>(NewQType);
2948   }
2949 
2950   // If this redeclaration makes the function inline, we may need to add it to
2951   // UndefinedButUsed.
2952   if (!Old->isInlined() && New->isInlined() &&
2953       !New->hasAttr<GNUInlineAttr>() &&
2954       !getLangOpts().GNUInline &&
2955       Old->isUsed(false) &&
2956       !Old->isDefined() && !New->isThisDeclarationADefinition())
2957     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2958                                            SourceLocation()));
2959 
2960   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2961   // about it.
2962   if (New->hasAttr<GNUInlineAttr>() &&
2963       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2964     UndefinedButUsed.erase(Old->getCanonicalDecl());
2965   }
2966 
2967   // If pass_object_size params don't match up perfectly, this isn't a valid
2968   // redeclaration.
2969   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
2970       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
2971     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
2972         << New->getDeclName();
2973     Diag(OldLocation, PrevDiag) << Old << Old->getType();
2974     return true;
2975   }
2976 
2977   if (getLangOpts().CPlusPlus) {
2978     // C++1z [over.load]p2
2979     //   Certain function declarations cannot be overloaded:
2980     //     -- Function declarations that differ only in the return type,
2981     //        the exception specification, or both cannot be overloaded.
2982 
2983     // Check the exception specifications match. This may recompute the type of
2984     // both Old and New if it resolved exception specifications, so grab the
2985     // types again after this. Because this updates the type, we do this before
2986     // any of the other checks below, which may update the "de facto" NewQType
2987     // but do not necessarily update the type of New.
2988     if (CheckEquivalentExceptionSpec(Old, New))
2989       return true;
2990     OldQType = Context.getCanonicalType(Old->getType());
2991     NewQType = Context.getCanonicalType(New->getType());
2992 
2993     // Go back to the type source info to compare the declared return types,
2994     // per C++1y [dcl.type.auto]p13:
2995     //   Redeclarations or specializations of a function or function template
2996     //   with a declared return type that uses a placeholder type shall also
2997     //   use that placeholder, not a deduced type.
2998     QualType OldDeclaredReturnType =
2999         (Old->getTypeSourceInfo()
3000              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3001              : OldType)->getReturnType();
3002     QualType NewDeclaredReturnType =
3003         (New->getTypeSourceInfo()
3004              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
3005              : NewType)->getReturnType();
3006     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3007         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
3008           New->isLocalExternDecl())) {
3009       QualType ResQT;
3010       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3011           OldDeclaredReturnType->isObjCObjectPointerType())
3012         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3013       if (ResQT.isNull()) {
3014         if (New->isCXXClassMember() && New->isOutOfLine())
3015           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3016               << New << New->getReturnTypeSourceRange();
3017         else
3018           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3019               << New->getReturnTypeSourceRange();
3020         Diag(OldLocation, PrevDiag) << Old << Old->getType()
3021                                     << Old->getReturnTypeSourceRange();
3022         return true;
3023       }
3024       else
3025         NewQType = ResQT;
3026     }
3027 
3028     QualType OldReturnType = OldType->getReturnType();
3029     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3030     if (OldReturnType != NewReturnType) {
3031       // If this function has a deduced return type and has already been
3032       // defined, copy the deduced value from the old declaration.
3033       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3034       if (OldAT && OldAT->isDeduced()) {
3035         New->setType(
3036             SubstAutoType(New->getType(),
3037                           OldAT->isDependentType() ? Context.DependentTy
3038                                                    : OldAT->getDeducedType()));
3039         NewQType = Context.getCanonicalType(
3040             SubstAutoType(NewQType,
3041                           OldAT->isDependentType() ? Context.DependentTy
3042                                                    : OldAT->getDeducedType()));
3043       }
3044     }
3045 
3046     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3047     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3048     if (OldMethod && NewMethod) {
3049       // Preserve triviality.
3050       NewMethod->setTrivial(OldMethod->isTrivial());
3051 
3052       // MSVC allows explicit template specialization at class scope:
3053       // 2 CXXMethodDecls referring to the same function will be injected.
3054       // We don't want a redeclaration error.
3055       bool IsClassScopeExplicitSpecialization =
3056                               OldMethod->isFunctionTemplateSpecialization() &&
3057                               NewMethod->isFunctionTemplateSpecialization();
3058       bool isFriend = NewMethod->getFriendObjectKind();
3059 
3060       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3061           !IsClassScopeExplicitSpecialization) {
3062         //    -- Member function declarations with the same name and the
3063         //       same parameter types cannot be overloaded if any of them
3064         //       is a static member function declaration.
3065         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3066           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3067           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3068           return true;
3069         }
3070 
3071         // C++ [class.mem]p1:
3072         //   [...] A member shall not be declared twice in the
3073         //   member-specification, except that a nested class or member
3074         //   class template can be declared and then later defined.
3075         if (ActiveTemplateInstantiations.empty()) {
3076           unsigned NewDiag;
3077           if (isa<CXXConstructorDecl>(OldMethod))
3078             NewDiag = diag::err_constructor_redeclared;
3079           else if (isa<CXXDestructorDecl>(NewMethod))
3080             NewDiag = diag::err_destructor_redeclared;
3081           else if (isa<CXXConversionDecl>(NewMethod))
3082             NewDiag = diag::err_conv_function_redeclared;
3083           else
3084             NewDiag = diag::err_member_redeclared;
3085 
3086           Diag(New->getLocation(), NewDiag);
3087         } else {
3088           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3089             << New << New->getType();
3090         }
3091         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3092         return true;
3093 
3094       // Complain if this is an explicit declaration of a special
3095       // member that was initially declared implicitly.
3096       //
3097       // As an exception, it's okay to befriend such methods in order
3098       // to permit the implicit constructor/destructor/operator calls.
3099       } else if (OldMethod->isImplicit()) {
3100         if (isFriend) {
3101           NewMethod->setImplicit();
3102         } else {
3103           Diag(NewMethod->getLocation(),
3104                diag::err_definition_of_implicitly_declared_member)
3105             << New << getSpecialMember(OldMethod);
3106           return true;
3107         }
3108       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3109         Diag(NewMethod->getLocation(),
3110              diag::err_definition_of_explicitly_defaulted_member)
3111           << getSpecialMember(OldMethod);
3112         return true;
3113       }
3114     }
3115 
3116     // C++11 [dcl.attr.noreturn]p1:
3117     //   The first declaration of a function shall specify the noreturn
3118     //   attribute if any declaration of that function specifies the noreturn
3119     //   attribute.
3120     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3121     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3122       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3123       Diag(Old->getFirstDecl()->getLocation(),
3124            diag::note_noreturn_missing_first_decl);
3125     }
3126 
3127     // C++11 [dcl.attr.depend]p2:
3128     //   The first declaration of a function shall specify the
3129     //   carries_dependency attribute for its declarator-id if any declaration
3130     //   of the function specifies the carries_dependency attribute.
3131     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3132     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3133       Diag(CDA->getLocation(),
3134            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3135       Diag(Old->getFirstDecl()->getLocation(),
3136            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3137     }
3138 
3139     // (C++98 8.3.5p3):
3140     //   All declarations for a function shall agree exactly in both the
3141     //   return type and the parameter-type-list.
3142     // We also want to respect all the extended bits except noreturn.
3143 
3144     // noreturn should now match unless the old type info didn't have it.
3145     QualType OldQTypeForComparison = OldQType;
3146     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3147       auto *OldType = OldQType->castAs<FunctionProtoType>();
3148       const FunctionType *OldTypeForComparison
3149         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3150       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3151       assert(OldQTypeForComparison.isCanonical());
3152     }
3153 
3154     if (haveIncompatibleLanguageLinkages(Old, New)) {
3155       // As a special case, retain the language linkage from previous
3156       // declarations of a friend function as an extension.
3157       //
3158       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3159       // and is useful because there's otherwise no way to specify language
3160       // linkage within class scope.
3161       //
3162       // Check cautiously as the friend object kind isn't yet complete.
3163       if (New->getFriendObjectKind() != Decl::FOK_None) {
3164         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3165         Diag(OldLocation, PrevDiag);
3166       } else {
3167         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3168         Diag(OldLocation, PrevDiag);
3169         return true;
3170       }
3171     }
3172 
3173     if (OldQTypeForComparison == NewQType)
3174       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3175 
3176     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3177         New->isLocalExternDecl()) {
3178       // It's OK if we couldn't merge types for a local function declaraton
3179       // if either the old or new type is dependent. We'll merge the types
3180       // when we instantiate the function.
3181       return false;
3182     }
3183 
3184     // Fall through for conflicting redeclarations and redefinitions.
3185   }
3186 
3187   // C: Function types need to be compatible, not identical. This handles
3188   // duplicate function decls like "void f(int); void f(enum X);" properly.
3189   if (!getLangOpts().CPlusPlus &&
3190       Context.typesAreCompatible(OldQType, NewQType)) {
3191     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3192     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3193     const FunctionProtoType *OldProto = nullptr;
3194     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3195         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3196       // The old declaration provided a function prototype, but the
3197       // new declaration does not. Merge in the prototype.
3198       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3199       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3200       NewQType =
3201           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3202                                   OldProto->getExtProtoInfo());
3203       New->setType(NewQType);
3204       New->setHasInheritedPrototype();
3205 
3206       // Synthesize parameters with the same types.
3207       SmallVector<ParmVarDecl*, 16> Params;
3208       for (const auto &ParamType : OldProto->param_types()) {
3209         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3210                                                  SourceLocation(), nullptr,
3211                                                  ParamType, /*TInfo=*/nullptr,
3212                                                  SC_None, nullptr);
3213         Param->setScopeInfo(0, Params.size());
3214         Param->setImplicit();
3215         Params.push_back(Param);
3216       }
3217 
3218       New->setParams(Params);
3219     }
3220 
3221     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3222   }
3223 
3224   // GNU C permits a K&R definition to follow a prototype declaration
3225   // if the declared types of the parameters in the K&R definition
3226   // match the types in the prototype declaration, even when the
3227   // promoted types of the parameters from the K&R definition differ
3228   // from the types in the prototype. GCC then keeps the types from
3229   // the prototype.
3230   //
3231   // If a variadic prototype is followed by a non-variadic K&R definition,
3232   // the K&R definition becomes variadic.  This is sort of an edge case, but
3233   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3234   // C99 6.9.1p8.
3235   if (!getLangOpts().CPlusPlus &&
3236       Old->hasPrototype() && !New->hasPrototype() &&
3237       New->getType()->getAs<FunctionProtoType>() &&
3238       Old->getNumParams() == New->getNumParams()) {
3239     SmallVector<QualType, 16> ArgTypes;
3240     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3241     const FunctionProtoType *OldProto
3242       = Old->getType()->getAs<FunctionProtoType>();
3243     const FunctionProtoType *NewProto
3244       = New->getType()->getAs<FunctionProtoType>();
3245 
3246     // Determine whether this is the GNU C extension.
3247     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3248                                                NewProto->getReturnType());
3249     bool LooseCompatible = !MergedReturn.isNull();
3250     for (unsigned Idx = 0, End = Old->getNumParams();
3251          LooseCompatible && Idx != End; ++Idx) {
3252       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3253       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3254       if (Context.typesAreCompatible(OldParm->getType(),
3255                                      NewProto->getParamType(Idx))) {
3256         ArgTypes.push_back(NewParm->getType());
3257       } else if (Context.typesAreCompatible(OldParm->getType(),
3258                                             NewParm->getType(),
3259                                             /*CompareUnqualified=*/true)) {
3260         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3261                                            NewProto->getParamType(Idx) };
3262         Warnings.push_back(Warn);
3263         ArgTypes.push_back(NewParm->getType());
3264       } else
3265         LooseCompatible = false;
3266     }
3267 
3268     if (LooseCompatible) {
3269       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3270         Diag(Warnings[Warn].NewParm->getLocation(),
3271              diag::ext_param_promoted_not_compatible_with_prototype)
3272           << Warnings[Warn].PromotedType
3273           << Warnings[Warn].OldParm->getType();
3274         if (Warnings[Warn].OldParm->getLocation().isValid())
3275           Diag(Warnings[Warn].OldParm->getLocation(),
3276                diag::note_previous_declaration);
3277       }
3278 
3279       if (MergeTypeWithOld)
3280         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3281                                              OldProto->getExtProtoInfo()));
3282       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3283     }
3284 
3285     // Fall through to diagnose conflicting types.
3286   }
3287 
3288   // A function that has already been declared has been redeclared or
3289   // defined with a different type; show an appropriate diagnostic.
3290 
3291   // If the previous declaration was an implicitly-generated builtin
3292   // declaration, then at the very least we should use a specialized note.
3293   unsigned BuiltinID;
3294   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3295     // If it's actually a library-defined builtin function like 'malloc'
3296     // or 'printf', just warn about the incompatible redeclaration.
3297     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3298       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3299       Diag(OldLocation, diag::note_previous_builtin_declaration)
3300         << Old << Old->getType();
3301 
3302       // If this is a global redeclaration, just forget hereafter
3303       // about the "builtin-ness" of the function.
3304       //
3305       // Doing this for local extern declarations is problematic.  If
3306       // the builtin declaration remains visible, a second invalid
3307       // local declaration will produce a hard error; if it doesn't
3308       // remain visible, a single bogus local redeclaration (which is
3309       // actually only a warning) could break all the downstream code.
3310       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3311         New->getIdentifier()->revertBuiltin();
3312 
3313       return false;
3314     }
3315 
3316     PrevDiag = diag::note_previous_builtin_declaration;
3317   }
3318 
3319   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3320   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3321   return true;
3322 }
3323 
3324 /// \brief Completes the merge of two function declarations that are
3325 /// known to be compatible.
3326 ///
3327 /// This routine handles the merging of attributes and other
3328 /// properties of function declarations from the old declaration to
3329 /// the new declaration, once we know that New is in fact a
3330 /// redeclaration of Old.
3331 ///
3332 /// \returns false
3333 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3334                                         Scope *S, bool MergeTypeWithOld) {
3335   // Merge the attributes
3336   mergeDeclAttributes(New, Old);
3337 
3338   // Merge "pure" flag.
3339   if (Old->isPure())
3340     New->setPure();
3341 
3342   // Merge "used" flag.
3343   if (Old->getMostRecentDecl()->isUsed(false))
3344     New->setIsUsed();
3345 
3346   // Merge attributes from the parameters.  These can mismatch with K&R
3347   // declarations.
3348   if (New->getNumParams() == Old->getNumParams())
3349       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3350         ParmVarDecl *NewParam = New->getParamDecl(i);
3351         ParmVarDecl *OldParam = Old->getParamDecl(i);
3352         mergeParamDeclAttributes(NewParam, OldParam, *this);
3353         mergeParamDeclTypes(NewParam, OldParam, *this);
3354       }
3355 
3356   if (getLangOpts().CPlusPlus)
3357     return MergeCXXFunctionDecl(New, Old, S);
3358 
3359   // Merge the function types so the we get the composite types for the return
3360   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3361   // was visible.
3362   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3363   if (!Merged.isNull() && MergeTypeWithOld)
3364     New->setType(Merged);
3365 
3366   return false;
3367 }
3368 
3369 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3370                                 ObjCMethodDecl *oldMethod) {
3371   // Merge the attributes, including deprecated/unavailable
3372   AvailabilityMergeKind MergeKind =
3373     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3374       ? AMK_ProtocolImplementation
3375       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3376                                                        : AMK_Override;
3377 
3378   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3379 
3380   // Merge attributes from the parameters.
3381   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3382                                        oe = oldMethod->param_end();
3383   for (ObjCMethodDecl::param_iterator
3384          ni = newMethod->param_begin(), ne = newMethod->param_end();
3385        ni != ne && oi != oe; ++ni, ++oi)
3386     mergeParamDeclAttributes(*ni, *oi, *this);
3387 
3388   CheckObjCMethodOverride(newMethod, oldMethod);
3389 }
3390 
3391 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3392   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3393 
3394   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3395          ? diag::err_redefinition_different_type
3396          : diag::err_redeclaration_different_type)
3397     << New->getDeclName() << New->getType() << Old->getType();
3398 
3399   diag::kind PrevDiag;
3400   SourceLocation OldLocation;
3401   std::tie(PrevDiag, OldLocation)
3402     = getNoteDiagForInvalidRedeclaration(Old, New);
3403   S.Diag(OldLocation, PrevDiag);
3404   New->setInvalidDecl();
3405 }
3406 
3407 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3408 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3409 /// emitting diagnostics as appropriate.
3410 ///
3411 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3412 /// to here in AddInitializerToDecl. We can't check them before the initializer
3413 /// is attached.
3414 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3415                              bool MergeTypeWithOld) {
3416   if (New->isInvalidDecl() || Old->isInvalidDecl())
3417     return;
3418 
3419   QualType MergedT;
3420   if (getLangOpts().CPlusPlus) {
3421     if (New->getType()->isUndeducedType()) {
3422       // We don't know what the new type is until the initializer is attached.
3423       return;
3424     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3425       // These could still be something that needs exception specs checked.
3426       return MergeVarDeclExceptionSpecs(New, Old);
3427     }
3428     // C++ [basic.link]p10:
3429     //   [...] the types specified by all declarations referring to a given
3430     //   object or function shall be identical, except that declarations for an
3431     //   array object can specify array types that differ by the presence or
3432     //   absence of a major array bound (8.3.4).
3433     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3434       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3435       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3436 
3437       // We are merging a variable declaration New into Old. If it has an array
3438       // bound, and that bound differs from Old's bound, we should diagnose the
3439       // mismatch.
3440       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3441         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3442              PrevVD = PrevVD->getPreviousDecl()) {
3443           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3444           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3445             continue;
3446 
3447           if (!Context.hasSameType(NewArray, PrevVDTy))
3448             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3449         }
3450       }
3451 
3452       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3453         if (Context.hasSameType(OldArray->getElementType(),
3454                                 NewArray->getElementType()))
3455           MergedT = New->getType();
3456       }
3457       // FIXME: Check visibility. New is hidden but has a complete type. If New
3458       // has no array bound, it should not inherit one from Old, if Old is not
3459       // visible.
3460       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3461         if (Context.hasSameType(OldArray->getElementType(),
3462                                 NewArray->getElementType()))
3463           MergedT = Old->getType();
3464       }
3465     }
3466     else if (New->getType()->isObjCObjectPointerType() &&
3467                Old->getType()->isObjCObjectPointerType()) {
3468       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3469                                               Old->getType());
3470     }
3471   } else {
3472     // C 6.2.7p2:
3473     //   All declarations that refer to the same object or function shall have
3474     //   compatible type.
3475     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3476   }
3477   if (MergedT.isNull()) {
3478     // It's OK if we couldn't merge types if either type is dependent, for a
3479     // block-scope variable. In other cases (static data members of class
3480     // templates, variable templates, ...), we require the types to be
3481     // equivalent.
3482     // FIXME: The C++ standard doesn't say anything about this.
3483     if ((New->getType()->isDependentType() ||
3484          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3485       // If the old type was dependent, we can't merge with it, so the new type
3486       // becomes dependent for now. We'll reproduce the original type when we
3487       // instantiate the TypeSourceInfo for the variable.
3488       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3489         New->setType(Context.DependentTy);
3490       return;
3491     }
3492     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3493   }
3494 
3495   // Don't actually update the type on the new declaration if the old
3496   // declaration was an extern declaration in a different scope.
3497   if (MergeTypeWithOld)
3498     New->setType(MergedT);
3499 }
3500 
3501 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3502                                   LookupResult &Previous) {
3503   // C11 6.2.7p4:
3504   //   For an identifier with internal or external linkage declared
3505   //   in a scope in which a prior declaration of that identifier is
3506   //   visible, if the prior declaration specifies internal or
3507   //   external linkage, the type of the identifier at the later
3508   //   declaration becomes the composite type.
3509   //
3510   // If the variable isn't visible, we do not merge with its type.
3511   if (Previous.isShadowed())
3512     return false;
3513 
3514   if (S.getLangOpts().CPlusPlus) {
3515     // C++11 [dcl.array]p3:
3516     //   If there is a preceding declaration of the entity in the same
3517     //   scope in which the bound was specified, an omitted array bound
3518     //   is taken to be the same as in that earlier declaration.
3519     return NewVD->isPreviousDeclInSameBlockScope() ||
3520            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3521             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3522   } else {
3523     // If the old declaration was function-local, don't merge with its
3524     // type unless we're in the same function.
3525     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3526            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3527   }
3528 }
3529 
3530 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3531 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3532 /// situation, merging decls or emitting diagnostics as appropriate.
3533 ///
3534 /// Tentative definition rules (C99 6.9.2p2) are checked by
3535 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3536 /// definitions here, since the initializer hasn't been attached.
3537 ///
3538 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3539   // If the new decl is already invalid, don't do any other checking.
3540   if (New->isInvalidDecl())
3541     return;
3542 
3543   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3544     return;
3545 
3546   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3547 
3548   // Verify the old decl was also a variable or variable template.
3549   VarDecl *Old = nullptr;
3550   VarTemplateDecl *OldTemplate = nullptr;
3551   if (Previous.isSingleResult()) {
3552     if (NewTemplate) {
3553       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3554       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3555 
3556       if (auto *Shadow =
3557               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3558         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3559           return New->setInvalidDecl();
3560     } else {
3561       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3562 
3563       if (auto *Shadow =
3564               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3565         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3566           return New->setInvalidDecl();
3567     }
3568   }
3569   if (!Old) {
3570     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3571       << New->getDeclName();
3572     Diag(Previous.getRepresentativeDecl()->getLocation(),
3573          diag::note_previous_definition);
3574     return New->setInvalidDecl();
3575   }
3576 
3577   // Ensure the template parameters are compatible.
3578   if (NewTemplate &&
3579       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3580                                       OldTemplate->getTemplateParameters(),
3581                                       /*Complain=*/true, TPL_TemplateMatch))
3582     return New->setInvalidDecl();
3583 
3584   // C++ [class.mem]p1:
3585   //   A member shall not be declared twice in the member-specification [...]
3586   //
3587   // Here, we need only consider static data members.
3588   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3589     Diag(New->getLocation(), diag::err_duplicate_member)
3590       << New->getIdentifier();
3591     Diag(Old->getLocation(), diag::note_previous_declaration);
3592     New->setInvalidDecl();
3593   }
3594 
3595   mergeDeclAttributes(New, Old);
3596   // Warn if an already-declared variable is made a weak_import in a subsequent
3597   // declaration
3598   if (New->hasAttr<WeakImportAttr>() &&
3599       Old->getStorageClass() == SC_None &&
3600       !Old->hasAttr<WeakImportAttr>()) {
3601     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3602     Diag(Old->getLocation(), diag::note_previous_definition);
3603     // Remove weak_import attribute on new declaration.
3604     New->dropAttr<WeakImportAttr>();
3605   }
3606 
3607   if (New->hasAttr<InternalLinkageAttr>() &&
3608       !Old->hasAttr<InternalLinkageAttr>()) {
3609     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3610         << New->getDeclName();
3611     Diag(Old->getLocation(), diag::note_previous_definition);
3612     New->dropAttr<InternalLinkageAttr>();
3613   }
3614 
3615   // Merge the types.
3616   VarDecl *MostRecent = Old->getMostRecentDecl();
3617   if (MostRecent != Old) {
3618     MergeVarDeclTypes(New, MostRecent,
3619                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3620     if (New->isInvalidDecl())
3621       return;
3622   }
3623 
3624   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3625   if (New->isInvalidDecl())
3626     return;
3627 
3628   diag::kind PrevDiag;
3629   SourceLocation OldLocation;
3630   std::tie(PrevDiag, OldLocation) =
3631       getNoteDiagForInvalidRedeclaration(Old, New);
3632 
3633   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3634   if (New->getStorageClass() == SC_Static &&
3635       !New->isStaticDataMember() &&
3636       Old->hasExternalFormalLinkage()) {
3637     if (getLangOpts().MicrosoftExt) {
3638       Diag(New->getLocation(), diag::ext_static_non_static)
3639           << New->getDeclName();
3640       Diag(OldLocation, PrevDiag);
3641     } else {
3642       Diag(New->getLocation(), diag::err_static_non_static)
3643           << New->getDeclName();
3644       Diag(OldLocation, PrevDiag);
3645       return New->setInvalidDecl();
3646     }
3647   }
3648   // C99 6.2.2p4:
3649   //   For an identifier declared with the storage-class specifier
3650   //   extern in a scope in which a prior declaration of that
3651   //   identifier is visible,23) if the prior declaration specifies
3652   //   internal or external linkage, the linkage of the identifier at
3653   //   the later declaration is the same as the linkage specified at
3654   //   the prior declaration. If no prior declaration is visible, or
3655   //   if the prior declaration specifies no linkage, then the
3656   //   identifier has external linkage.
3657   if (New->hasExternalStorage() && Old->hasLinkage())
3658     /* Okay */;
3659   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3660            !New->isStaticDataMember() &&
3661            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3662     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3663     Diag(OldLocation, PrevDiag);
3664     return New->setInvalidDecl();
3665   }
3666 
3667   // Check if extern is followed by non-extern and vice-versa.
3668   if (New->hasExternalStorage() &&
3669       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3670     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3671     Diag(OldLocation, PrevDiag);
3672     return New->setInvalidDecl();
3673   }
3674   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3675       !New->hasExternalStorage()) {
3676     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3677     Diag(OldLocation, PrevDiag);
3678     return New->setInvalidDecl();
3679   }
3680 
3681   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3682 
3683   // FIXME: The test for external storage here seems wrong? We still
3684   // need to check for mismatches.
3685   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3686       // Don't complain about out-of-line definitions of static members.
3687       !(Old->getLexicalDeclContext()->isRecord() &&
3688         !New->getLexicalDeclContext()->isRecord())) {
3689     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3690     Diag(OldLocation, PrevDiag);
3691     return New->setInvalidDecl();
3692   }
3693 
3694   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3695     if (VarDecl *Def = Old->getDefinition()) {
3696       // C++1z [dcl.fcn.spec]p4:
3697       //   If the definition of a variable appears in a translation unit before
3698       //   its first declaration as inline, the program is ill-formed.
3699       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3700       Diag(Def->getLocation(), diag::note_previous_definition);
3701     }
3702   }
3703 
3704   // If this redeclaration makes the function inline, we may need to add it to
3705   // UndefinedButUsed.
3706   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3707       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3708     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3709                                            SourceLocation()));
3710 
3711   if (New->getTLSKind() != Old->getTLSKind()) {
3712     if (!Old->getTLSKind()) {
3713       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3714       Diag(OldLocation, PrevDiag);
3715     } else if (!New->getTLSKind()) {
3716       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3717       Diag(OldLocation, PrevDiag);
3718     } else {
3719       // Do not allow redeclaration to change the variable between requiring
3720       // static and dynamic initialization.
3721       // FIXME: GCC allows this, but uses the TLS keyword on the first
3722       // declaration to determine the kind. Do we need to be compatible here?
3723       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3724         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3725       Diag(OldLocation, PrevDiag);
3726     }
3727   }
3728 
3729   // C++ doesn't have tentative definitions, so go right ahead and check here.
3730   if (getLangOpts().CPlusPlus &&
3731       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3732     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3733         Old->getCanonicalDecl()->isConstexpr()) {
3734       // This definition won't be a definition any more once it's been merged.
3735       Diag(New->getLocation(),
3736            diag::warn_deprecated_redundant_constexpr_static_def);
3737     } else if (VarDecl *Def = Old->getDefinition()) {
3738       if (checkVarDeclRedefinition(Def, New))
3739         return;
3740     }
3741   }
3742 
3743   if (haveIncompatibleLanguageLinkages(Old, New)) {
3744     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3745     Diag(OldLocation, PrevDiag);
3746     New->setInvalidDecl();
3747     return;
3748   }
3749 
3750   // Merge "used" flag.
3751   if (Old->getMostRecentDecl()->isUsed(false))
3752     New->setIsUsed();
3753 
3754   // Keep a chain of previous declarations.
3755   New->setPreviousDecl(Old);
3756   if (NewTemplate)
3757     NewTemplate->setPreviousDecl(OldTemplate);
3758 
3759   // Inherit access appropriately.
3760   New->setAccess(Old->getAccess());
3761   if (NewTemplate)
3762     NewTemplate->setAccess(New->getAccess());
3763 
3764   if (Old->isInline())
3765     New->setImplicitlyInline();
3766 }
3767 
3768 /// We've just determined that \p Old and \p New both appear to be definitions
3769 /// of the same variable. Either diagnose or fix the problem.
3770 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
3771   if (!hasVisibleDefinition(Old) &&
3772       (New->getFormalLinkage() == InternalLinkage ||
3773        New->isInline() ||
3774        New->getDescribedVarTemplate() ||
3775        New->getNumTemplateParameterLists() ||
3776        New->getDeclContext()->isDependentContext())) {
3777     // The previous definition is hidden, and multiple definitions are
3778     // permitted (in separate TUs). Demote this to a declaration.
3779     New->demoteThisDefinitionToDeclaration();
3780 
3781     // Make the canonical definition visible.
3782     if (auto *OldTD = Old->getDescribedVarTemplate())
3783       makeMergedDefinitionVisible(OldTD, New->getLocation());
3784     makeMergedDefinitionVisible(Old, New->getLocation());
3785     return false;
3786   } else {
3787     Diag(New->getLocation(), diag::err_redefinition) << New;
3788     Diag(Old->getLocation(), diag::note_previous_definition);
3789     New->setInvalidDecl();
3790     return true;
3791   }
3792 }
3793 
3794 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3795 /// no declarator (e.g. "struct foo;") is parsed.
3796 Decl *
3797 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3798                                  RecordDecl *&AnonRecord) {
3799   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3800                                     AnonRecord);
3801 }
3802 
3803 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3804 // disambiguate entities defined in different scopes.
3805 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3806 // compatibility.
3807 // We will pick our mangling number depending on which version of MSVC is being
3808 // targeted.
3809 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3810   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3811              ? S->getMSCurManglingNumber()
3812              : S->getMSLastManglingNumber();
3813 }
3814 
3815 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3816   if (!Context.getLangOpts().CPlusPlus)
3817     return;
3818 
3819   if (isa<CXXRecordDecl>(Tag->getParent())) {
3820     // If this tag is the direct child of a class, number it if
3821     // it is anonymous.
3822     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3823       return;
3824     MangleNumberingContext &MCtx =
3825         Context.getManglingNumberContext(Tag->getParent());
3826     Context.setManglingNumber(
3827         Tag, MCtx.getManglingNumber(
3828                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3829     return;
3830   }
3831 
3832   // If this tag isn't a direct child of a class, number it if it is local.
3833   Decl *ManglingContextDecl;
3834   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3835           Tag->getDeclContext(), ManglingContextDecl)) {
3836     Context.setManglingNumber(
3837         Tag, MCtx->getManglingNumber(
3838                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3839   }
3840 }
3841 
3842 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3843                                         TypedefNameDecl *NewTD) {
3844   if (TagFromDeclSpec->isInvalidDecl())
3845     return;
3846 
3847   // Do nothing if the tag already has a name for linkage purposes.
3848   if (TagFromDeclSpec->hasNameForLinkage())
3849     return;
3850 
3851   // A well-formed anonymous tag must always be a TUK_Definition.
3852   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3853 
3854   // The type must match the tag exactly;  no qualifiers allowed.
3855   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3856                            Context.getTagDeclType(TagFromDeclSpec))) {
3857     if (getLangOpts().CPlusPlus)
3858       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3859     return;
3860   }
3861 
3862   // If we've already computed linkage for the anonymous tag, then
3863   // adding a typedef name for the anonymous decl can change that
3864   // linkage, which might be a serious problem.  Diagnose this as
3865   // unsupported and ignore the typedef name.  TODO: we should
3866   // pursue this as a language defect and establish a formal rule
3867   // for how to handle it.
3868   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3869     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3870 
3871     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3872     tagLoc = getLocForEndOfToken(tagLoc);
3873 
3874     llvm::SmallString<40> textToInsert;
3875     textToInsert += ' ';
3876     textToInsert += NewTD->getIdentifier()->getName();
3877     Diag(tagLoc, diag::note_typedef_changes_linkage)
3878         << FixItHint::CreateInsertion(tagLoc, textToInsert);
3879     return;
3880   }
3881 
3882   // Otherwise, set this is the anon-decl typedef for the tag.
3883   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3884 }
3885 
3886 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3887   switch (T) {
3888   case DeclSpec::TST_class:
3889     return 0;
3890   case DeclSpec::TST_struct:
3891     return 1;
3892   case DeclSpec::TST_interface:
3893     return 2;
3894   case DeclSpec::TST_union:
3895     return 3;
3896   case DeclSpec::TST_enum:
3897     return 4;
3898   default:
3899     llvm_unreachable("unexpected type specifier");
3900   }
3901 }
3902 
3903 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3904 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3905 /// parameters to cope with template friend declarations.
3906 Decl *
3907 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3908                                  MultiTemplateParamsArg TemplateParams,
3909                                  bool IsExplicitInstantiation,
3910                                  RecordDecl *&AnonRecord) {
3911   Decl *TagD = nullptr;
3912   TagDecl *Tag = nullptr;
3913   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3914       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3915       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3916       DS.getTypeSpecType() == DeclSpec::TST_union ||
3917       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3918     TagD = DS.getRepAsDecl();
3919 
3920     if (!TagD) // We probably had an error
3921       return nullptr;
3922 
3923     // Note that the above type specs guarantee that the
3924     // type rep is a Decl, whereas in many of the others
3925     // it's a Type.
3926     if (isa<TagDecl>(TagD))
3927       Tag = cast<TagDecl>(TagD);
3928     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3929       Tag = CTD->getTemplatedDecl();
3930   }
3931 
3932   if (Tag) {
3933     handleTagNumbering(Tag, S);
3934     Tag->setFreeStanding();
3935     if (Tag->isInvalidDecl())
3936       return Tag;
3937   }
3938 
3939   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3940     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3941     // or incomplete types shall not be restrict-qualified."
3942     if (TypeQuals & DeclSpec::TQ_restrict)
3943       Diag(DS.getRestrictSpecLoc(),
3944            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3945            << DS.getSourceRange();
3946   }
3947 
3948   if (DS.isInlineSpecified())
3949     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
3950         << getLangOpts().CPlusPlus1z;
3951 
3952   if (DS.isConstexprSpecified()) {
3953     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3954     // and definitions of functions and variables.
3955     if (Tag)
3956       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3957           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3958     else
3959       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3960     // Don't emit warnings after this error.
3961     return TagD;
3962   }
3963 
3964   if (DS.isConceptSpecified()) {
3965     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3966     // either a function concept and its definition or a variable concept and
3967     // its initializer.
3968     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3969     return TagD;
3970   }
3971 
3972   DiagnoseFunctionSpecifiers(DS);
3973 
3974   if (DS.isFriendSpecified()) {
3975     // If we're dealing with a decl but not a TagDecl, assume that
3976     // whatever routines created it handled the friendship aspect.
3977     if (TagD && !Tag)
3978       return nullptr;
3979     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3980   }
3981 
3982   const CXXScopeSpec &SS = DS.getTypeSpecScope();
3983   bool IsExplicitSpecialization =
3984     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3985   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3986       !IsExplicitInstantiation && !IsExplicitSpecialization &&
3987       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
3988     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3989     // nested-name-specifier unless it is an explicit instantiation
3990     // or an explicit specialization.
3991     //
3992     // FIXME: We allow class template partial specializations here too, per the
3993     // obvious intent of DR1819.
3994     //
3995     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3996     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3997         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
3998     return nullptr;
3999   }
4000 
4001   // Track whether this decl-specifier declares anything.
4002   bool DeclaresAnything = true;
4003 
4004   // Handle anonymous struct definitions.
4005   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4006     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4007         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
4008       if (getLangOpts().CPlusPlus ||
4009           Record->getDeclContext()->isRecord()) {
4010         // If CurContext is a DeclContext that can contain statements,
4011         // RecursiveASTVisitor won't visit the decls that
4012         // BuildAnonymousStructOrUnion() will put into CurContext.
4013         // Also store them here so that they can be part of the
4014         // DeclStmt that gets created in this case.
4015         // FIXME: Also return the IndirectFieldDecls created by
4016         // BuildAnonymousStructOr union, for the same reason?
4017         if (CurContext->isFunctionOrMethod())
4018           AnonRecord = Record;
4019         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4020                                            Context.getPrintingPolicy());
4021       }
4022 
4023       DeclaresAnything = false;
4024     }
4025   }
4026 
4027   // C11 6.7.2.1p2:
4028   //   A struct-declaration that does not declare an anonymous structure or
4029   //   anonymous union shall contain a struct-declarator-list.
4030   //
4031   // This rule also existed in C89 and C99; the grammar for struct-declaration
4032   // did not permit a struct-declaration without a struct-declarator-list.
4033   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4034       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
4035     // Check for Microsoft C extension: anonymous struct/union member.
4036     // Handle 2 kinds of anonymous struct/union:
4037     //   struct STRUCT;
4038     //   union UNION;
4039     // and
4040     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4041     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4042     if ((Tag && Tag->getDeclName()) ||
4043         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4044       RecordDecl *Record = nullptr;
4045       if (Tag)
4046         Record = dyn_cast<RecordDecl>(Tag);
4047       else if (const RecordType *RT =
4048                    DS.getRepAsType().get()->getAsStructureType())
4049         Record = RT->getDecl();
4050       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4051         Record = UT->getDecl();
4052 
4053       if (Record && getLangOpts().MicrosoftExt) {
4054         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4055           << Record->isUnion() << DS.getSourceRange();
4056         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4057       }
4058 
4059       DeclaresAnything = false;
4060     }
4061   }
4062 
4063   // Skip all the checks below if we have a type error.
4064   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4065       (TagD && TagD->isInvalidDecl()))
4066     return TagD;
4067 
4068   if (getLangOpts().CPlusPlus &&
4069       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4070     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4071       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4072           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4073         DeclaresAnything = false;
4074 
4075   if (!DS.isMissingDeclaratorOk()) {
4076     // Customize diagnostic for a typedef missing a name.
4077     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4078       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4079         << DS.getSourceRange();
4080     else
4081       DeclaresAnything = false;
4082   }
4083 
4084   if (DS.isModulePrivateSpecified() &&
4085       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4086     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4087       << Tag->getTagKind()
4088       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4089 
4090   ActOnDocumentableDecl(TagD);
4091 
4092   // C 6.7/2:
4093   //   A declaration [...] shall declare at least a declarator [...], a tag,
4094   //   or the members of an enumeration.
4095   // C++ [dcl.dcl]p3:
4096   //   [If there are no declarators], and except for the declaration of an
4097   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4098   //   names into the program, or shall redeclare a name introduced by a
4099   //   previous declaration.
4100   if (!DeclaresAnything) {
4101     // In C, we allow this as a (popular) extension / bug. Don't bother
4102     // producing further diagnostics for redundant qualifiers after this.
4103     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4104     return TagD;
4105   }
4106 
4107   // C++ [dcl.stc]p1:
4108   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4109   //   init-declarator-list of the declaration shall not be empty.
4110   // C++ [dcl.fct.spec]p1:
4111   //   If a cv-qualifier appears in a decl-specifier-seq, the
4112   //   init-declarator-list of the declaration shall not be empty.
4113   //
4114   // Spurious qualifiers here appear to be valid in C.
4115   unsigned DiagID = diag::warn_standalone_specifier;
4116   if (getLangOpts().CPlusPlus)
4117     DiagID = diag::ext_standalone_specifier;
4118 
4119   // Note that a linkage-specification sets a storage class, but
4120   // 'extern "C" struct foo;' is actually valid and not theoretically
4121   // useless.
4122   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4123     if (SCS == DeclSpec::SCS_mutable)
4124       // Since mutable is not a viable storage class specifier in C, there is
4125       // no reason to treat it as an extension. Instead, diagnose as an error.
4126       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4127     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4128       Diag(DS.getStorageClassSpecLoc(), DiagID)
4129         << DeclSpec::getSpecifierName(SCS);
4130   }
4131 
4132   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4133     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4134       << DeclSpec::getSpecifierName(TSCS);
4135   if (DS.getTypeQualifiers()) {
4136     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4137       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4138     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4139       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4140     // Restrict is covered above.
4141     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4142       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4143     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4144       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4145   }
4146 
4147   // Warn about ignored type attributes, for example:
4148   // __attribute__((aligned)) struct A;
4149   // Attributes should be placed after tag to apply to type declaration.
4150   if (!DS.getAttributes().empty()) {
4151     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4152     if (TypeSpecType == DeclSpec::TST_class ||
4153         TypeSpecType == DeclSpec::TST_struct ||
4154         TypeSpecType == DeclSpec::TST_interface ||
4155         TypeSpecType == DeclSpec::TST_union ||
4156         TypeSpecType == DeclSpec::TST_enum) {
4157       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4158            attrs = attrs->getNext())
4159         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4160             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4161     }
4162   }
4163 
4164   return TagD;
4165 }
4166 
4167 /// We are trying to inject an anonymous member into the given scope;
4168 /// check if there's an existing declaration that can't be overloaded.
4169 ///
4170 /// \return true if this is a forbidden redeclaration
4171 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4172                                          Scope *S,
4173                                          DeclContext *Owner,
4174                                          DeclarationName Name,
4175                                          SourceLocation NameLoc,
4176                                          bool IsUnion) {
4177   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4178                  Sema::ForRedeclaration);
4179   if (!SemaRef.LookupName(R, S)) return false;
4180 
4181   // Pick a representative declaration.
4182   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4183   assert(PrevDecl && "Expected a non-null Decl");
4184 
4185   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4186     return false;
4187 
4188   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4189     << IsUnion << Name;
4190   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4191 
4192   return true;
4193 }
4194 
4195 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4196 /// anonymous struct or union AnonRecord into the owning context Owner
4197 /// and scope S. This routine will be invoked just after we realize
4198 /// that an unnamed union or struct is actually an anonymous union or
4199 /// struct, e.g.,
4200 ///
4201 /// @code
4202 /// union {
4203 ///   int i;
4204 ///   float f;
4205 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4206 ///    // f into the surrounding scope.x
4207 /// @endcode
4208 ///
4209 /// This routine is recursive, injecting the names of nested anonymous
4210 /// structs/unions into the owning context and scope as well.
4211 static bool
4212 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4213                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4214                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4215   bool Invalid = false;
4216 
4217   // Look every FieldDecl and IndirectFieldDecl with a name.
4218   for (auto *D : AnonRecord->decls()) {
4219     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4220         cast<NamedDecl>(D)->getDeclName()) {
4221       ValueDecl *VD = cast<ValueDecl>(D);
4222       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4223                                        VD->getLocation(),
4224                                        AnonRecord->isUnion())) {
4225         // C++ [class.union]p2:
4226         //   The names of the members of an anonymous union shall be
4227         //   distinct from the names of any other entity in the
4228         //   scope in which the anonymous union is declared.
4229         Invalid = true;
4230       } else {
4231         // C++ [class.union]p2:
4232         //   For the purpose of name lookup, after the anonymous union
4233         //   definition, the members of the anonymous union are
4234         //   considered to have been defined in the scope in which the
4235         //   anonymous union is declared.
4236         unsigned OldChainingSize = Chaining.size();
4237         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4238           Chaining.append(IF->chain_begin(), IF->chain_end());
4239         else
4240           Chaining.push_back(VD);
4241 
4242         assert(Chaining.size() >= 2);
4243         NamedDecl **NamedChain =
4244           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4245         for (unsigned i = 0; i < Chaining.size(); i++)
4246           NamedChain[i] = Chaining[i];
4247 
4248         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4249             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4250             VD->getType(), {NamedChain, Chaining.size()});
4251 
4252         for (const auto *Attr : VD->attrs())
4253           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4254 
4255         IndirectField->setAccess(AS);
4256         IndirectField->setImplicit();
4257         SemaRef.PushOnScopeChains(IndirectField, S);
4258 
4259         // That includes picking up the appropriate access specifier.
4260         if (AS != AS_none) IndirectField->setAccess(AS);
4261 
4262         Chaining.resize(OldChainingSize);
4263       }
4264     }
4265   }
4266 
4267   return Invalid;
4268 }
4269 
4270 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4271 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4272 /// illegal input values are mapped to SC_None.
4273 static StorageClass
4274 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4275   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4276   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4277          "Parser allowed 'typedef' as storage class VarDecl.");
4278   switch (StorageClassSpec) {
4279   case DeclSpec::SCS_unspecified:    return SC_None;
4280   case DeclSpec::SCS_extern:
4281     if (DS.isExternInLinkageSpec())
4282       return SC_None;
4283     return SC_Extern;
4284   case DeclSpec::SCS_static:         return SC_Static;
4285   case DeclSpec::SCS_auto:           return SC_Auto;
4286   case DeclSpec::SCS_register:       return SC_Register;
4287   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4288     // Illegal SCSs map to None: error reporting is up to the caller.
4289   case DeclSpec::SCS_mutable:        // Fall through.
4290   case DeclSpec::SCS_typedef:        return SC_None;
4291   }
4292   llvm_unreachable("unknown storage class specifier");
4293 }
4294 
4295 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4296   assert(Record->hasInClassInitializer());
4297 
4298   for (const auto *I : Record->decls()) {
4299     const auto *FD = dyn_cast<FieldDecl>(I);
4300     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4301       FD = IFD->getAnonField();
4302     if (FD && FD->hasInClassInitializer())
4303       return FD->getLocation();
4304   }
4305 
4306   llvm_unreachable("couldn't find in-class initializer");
4307 }
4308 
4309 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4310                                       SourceLocation DefaultInitLoc) {
4311   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4312     return;
4313 
4314   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4315   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4316 }
4317 
4318 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4319                                       CXXRecordDecl *AnonUnion) {
4320   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4321     return;
4322 
4323   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4324 }
4325 
4326 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4327 /// anonymous structure or union. Anonymous unions are a C++ feature
4328 /// (C++ [class.union]) and a C11 feature; anonymous structures
4329 /// are a C11 feature and GNU C++ extension.
4330 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4331                                         AccessSpecifier AS,
4332                                         RecordDecl *Record,
4333                                         const PrintingPolicy &Policy) {
4334   DeclContext *Owner = Record->getDeclContext();
4335 
4336   // Diagnose whether this anonymous struct/union is an extension.
4337   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4338     Diag(Record->getLocation(), diag::ext_anonymous_union);
4339   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4340     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4341   else if (!Record->isUnion() && !getLangOpts().C11)
4342     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4343 
4344   // C and C++ require different kinds of checks for anonymous
4345   // structs/unions.
4346   bool Invalid = false;
4347   if (getLangOpts().CPlusPlus) {
4348     const char *PrevSpec = nullptr;
4349     unsigned DiagID;
4350     if (Record->isUnion()) {
4351       // C++ [class.union]p6:
4352       //   Anonymous unions declared in a named namespace or in the
4353       //   global namespace shall be declared static.
4354       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4355           (isa<TranslationUnitDecl>(Owner) ||
4356            (isa<NamespaceDecl>(Owner) &&
4357             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4358         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4359           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4360 
4361         // Recover by adding 'static'.
4362         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4363                                PrevSpec, DiagID, Policy);
4364       }
4365       // C++ [class.union]p6:
4366       //   A storage class is not allowed in a declaration of an
4367       //   anonymous union in a class scope.
4368       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4369                isa<RecordDecl>(Owner)) {
4370         Diag(DS.getStorageClassSpecLoc(),
4371              diag::err_anonymous_union_with_storage_spec)
4372           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4373 
4374         // Recover by removing the storage specifier.
4375         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4376                                SourceLocation(),
4377                                PrevSpec, DiagID, Context.getPrintingPolicy());
4378       }
4379     }
4380 
4381     // Ignore const/volatile/restrict qualifiers.
4382     if (DS.getTypeQualifiers()) {
4383       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4384         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4385           << Record->isUnion() << "const"
4386           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4387       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4388         Diag(DS.getVolatileSpecLoc(),
4389              diag::ext_anonymous_struct_union_qualified)
4390           << Record->isUnion() << "volatile"
4391           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4392       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4393         Diag(DS.getRestrictSpecLoc(),
4394              diag::ext_anonymous_struct_union_qualified)
4395           << Record->isUnion() << "restrict"
4396           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4397       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4398         Diag(DS.getAtomicSpecLoc(),
4399              diag::ext_anonymous_struct_union_qualified)
4400           << Record->isUnion() << "_Atomic"
4401           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4402       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4403         Diag(DS.getUnalignedSpecLoc(),
4404              diag::ext_anonymous_struct_union_qualified)
4405           << Record->isUnion() << "__unaligned"
4406           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4407 
4408       DS.ClearTypeQualifiers();
4409     }
4410 
4411     // C++ [class.union]p2:
4412     //   The member-specification of an anonymous union shall only
4413     //   define non-static data members. [Note: nested types and
4414     //   functions cannot be declared within an anonymous union. ]
4415     for (auto *Mem : Record->decls()) {
4416       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4417         // C++ [class.union]p3:
4418         //   An anonymous union shall not have private or protected
4419         //   members (clause 11).
4420         assert(FD->getAccess() != AS_none);
4421         if (FD->getAccess() != AS_public) {
4422           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4423             << Record->isUnion() << (FD->getAccess() == AS_protected);
4424           Invalid = true;
4425         }
4426 
4427         // C++ [class.union]p1
4428         //   An object of a class with a non-trivial constructor, a non-trivial
4429         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4430         //   assignment operator cannot be a member of a union, nor can an
4431         //   array of such objects.
4432         if (CheckNontrivialField(FD))
4433           Invalid = true;
4434       } else if (Mem->isImplicit()) {
4435         // Any implicit members are fine.
4436       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4437         // This is a type that showed up in an
4438         // elaborated-type-specifier inside the anonymous struct or
4439         // union, but which actually declares a type outside of the
4440         // anonymous struct or union. It's okay.
4441       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4442         if (!MemRecord->isAnonymousStructOrUnion() &&
4443             MemRecord->getDeclName()) {
4444           // Visual C++ allows type definition in anonymous struct or union.
4445           if (getLangOpts().MicrosoftExt)
4446             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4447               << Record->isUnion();
4448           else {
4449             // This is a nested type declaration.
4450             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4451               << Record->isUnion();
4452             Invalid = true;
4453           }
4454         } else {
4455           // This is an anonymous type definition within another anonymous type.
4456           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4457           // not part of standard C++.
4458           Diag(MemRecord->getLocation(),
4459                diag::ext_anonymous_record_with_anonymous_type)
4460             << Record->isUnion();
4461         }
4462       } else if (isa<AccessSpecDecl>(Mem)) {
4463         // Any access specifier is fine.
4464       } else if (isa<StaticAssertDecl>(Mem)) {
4465         // In C++1z, static_assert declarations are also fine.
4466       } else {
4467         // We have something that isn't a non-static data
4468         // member. Complain about it.
4469         unsigned DK = diag::err_anonymous_record_bad_member;
4470         if (isa<TypeDecl>(Mem))
4471           DK = diag::err_anonymous_record_with_type;
4472         else if (isa<FunctionDecl>(Mem))
4473           DK = diag::err_anonymous_record_with_function;
4474         else if (isa<VarDecl>(Mem))
4475           DK = diag::err_anonymous_record_with_static;
4476 
4477         // Visual C++ allows type definition in anonymous struct or union.
4478         if (getLangOpts().MicrosoftExt &&
4479             DK == diag::err_anonymous_record_with_type)
4480           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4481             << Record->isUnion();
4482         else {
4483           Diag(Mem->getLocation(), DK) << Record->isUnion();
4484           Invalid = true;
4485         }
4486       }
4487     }
4488 
4489     // C++11 [class.union]p8 (DR1460):
4490     //   At most one variant member of a union may have a
4491     //   brace-or-equal-initializer.
4492     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4493         Owner->isRecord())
4494       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4495                                 cast<CXXRecordDecl>(Record));
4496   }
4497 
4498   if (!Record->isUnion() && !Owner->isRecord()) {
4499     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4500       << getLangOpts().CPlusPlus;
4501     Invalid = true;
4502   }
4503 
4504   // Mock up a declarator.
4505   Declarator Dc(DS, Declarator::MemberContext);
4506   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4507   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4508 
4509   // Create a declaration for this anonymous struct/union.
4510   NamedDecl *Anon = nullptr;
4511   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4512     Anon = FieldDecl::Create(Context, OwningClass,
4513                              DS.getLocStart(),
4514                              Record->getLocation(),
4515                              /*IdentifierInfo=*/nullptr,
4516                              Context.getTypeDeclType(Record),
4517                              TInfo,
4518                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4519                              /*InitStyle=*/ICIS_NoInit);
4520     Anon->setAccess(AS);
4521     if (getLangOpts().CPlusPlus)
4522       FieldCollector->Add(cast<FieldDecl>(Anon));
4523   } else {
4524     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4525     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4526     if (SCSpec == DeclSpec::SCS_mutable) {
4527       // mutable can only appear on non-static class members, so it's always
4528       // an error here
4529       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4530       Invalid = true;
4531       SC = SC_None;
4532     }
4533 
4534     Anon = VarDecl::Create(Context, Owner,
4535                            DS.getLocStart(),
4536                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4537                            Context.getTypeDeclType(Record),
4538                            TInfo, SC);
4539 
4540     // Default-initialize the implicit variable. This initialization will be
4541     // trivial in almost all cases, except if a union member has an in-class
4542     // initializer:
4543     //   union { int n = 0; };
4544     ActOnUninitializedDecl(Anon);
4545   }
4546   Anon->setImplicit();
4547 
4548   // Mark this as an anonymous struct/union type.
4549   Record->setAnonymousStructOrUnion(true);
4550 
4551   // Add the anonymous struct/union object to the current
4552   // context. We'll be referencing this object when we refer to one of
4553   // its members.
4554   Owner->addDecl(Anon);
4555 
4556   // Inject the members of the anonymous struct/union into the owning
4557   // context and into the identifier resolver chain for name lookup
4558   // purposes.
4559   SmallVector<NamedDecl*, 2> Chain;
4560   Chain.push_back(Anon);
4561 
4562   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4563     Invalid = true;
4564 
4565   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4566     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4567       Decl *ManglingContextDecl;
4568       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4569               NewVD->getDeclContext(), ManglingContextDecl)) {
4570         Context.setManglingNumber(
4571             NewVD, MCtx->getManglingNumber(
4572                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4573         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4574       }
4575     }
4576   }
4577 
4578   if (Invalid)
4579     Anon->setInvalidDecl();
4580 
4581   return Anon;
4582 }
4583 
4584 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4585 /// Microsoft C anonymous structure.
4586 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4587 /// Example:
4588 ///
4589 /// struct A { int a; };
4590 /// struct B { struct A; int b; };
4591 ///
4592 /// void foo() {
4593 ///   B var;
4594 ///   var.a = 3;
4595 /// }
4596 ///
4597 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4598                                            RecordDecl *Record) {
4599   assert(Record && "expected a record!");
4600 
4601   // Mock up a declarator.
4602   Declarator Dc(DS, Declarator::TypeNameContext);
4603   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4604   assert(TInfo && "couldn't build declarator info for anonymous struct");
4605 
4606   auto *ParentDecl = cast<RecordDecl>(CurContext);
4607   QualType RecTy = Context.getTypeDeclType(Record);
4608 
4609   // Create a declaration for this anonymous struct.
4610   NamedDecl *Anon = FieldDecl::Create(Context,
4611                              ParentDecl,
4612                              DS.getLocStart(),
4613                              DS.getLocStart(),
4614                              /*IdentifierInfo=*/nullptr,
4615                              RecTy,
4616                              TInfo,
4617                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4618                              /*InitStyle=*/ICIS_NoInit);
4619   Anon->setImplicit();
4620 
4621   // Add the anonymous struct object to the current context.
4622   CurContext->addDecl(Anon);
4623 
4624   // Inject the members of the anonymous struct into the current
4625   // context and into the identifier resolver chain for name lookup
4626   // purposes.
4627   SmallVector<NamedDecl*, 2> Chain;
4628   Chain.push_back(Anon);
4629 
4630   RecordDecl *RecordDef = Record->getDefinition();
4631   if (RequireCompleteType(Anon->getLocation(), RecTy,
4632                           diag::err_field_incomplete) ||
4633       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4634                                           AS_none, Chain)) {
4635     Anon->setInvalidDecl();
4636     ParentDecl->setInvalidDecl();
4637   }
4638 
4639   return Anon;
4640 }
4641 
4642 /// GetNameForDeclarator - Determine the full declaration name for the
4643 /// given Declarator.
4644 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4645   return GetNameFromUnqualifiedId(D.getName());
4646 }
4647 
4648 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4649 DeclarationNameInfo
4650 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4651   DeclarationNameInfo NameInfo;
4652   NameInfo.setLoc(Name.StartLocation);
4653 
4654   switch (Name.getKind()) {
4655 
4656   case UnqualifiedId::IK_ImplicitSelfParam:
4657   case UnqualifiedId::IK_Identifier:
4658     NameInfo.setName(Name.Identifier);
4659     NameInfo.setLoc(Name.StartLocation);
4660     return NameInfo;
4661 
4662   case UnqualifiedId::IK_OperatorFunctionId:
4663     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4664                                            Name.OperatorFunctionId.Operator));
4665     NameInfo.setLoc(Name.StartLocation);
4666     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4667       = Name.OperatorFunctionId.SymbolLocations[0];
4668     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4669       = Name.EndLocation.getRawEncoding();
4670     return NameInfo;
4671 
4672   case UnqualifiedId::IK_LiteralOperatorId:
4673     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4674                                                            Name.Identifier));
4675     NameInfo.setLoc(Name.StartLocation);
4676     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4677     return NameInfo;
4678 
4679   case UnqualifiedId::IK_ConversionFunctionId: {
4680     TypeSourceInfo *TInfo;
4681     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4682     if (Ty.isNull())
4683       return DeclarationNameInfo();
4684     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4685                                                Context.getCanonicalType(Ty)));
4686     NameInfo.setLoc(Name.StartLocation);
4687     NameInfo.setNamedTypeInfo(TInfo);
4688     return NameInfo;
4689   }
4690 
4691   case UnqualifiedId::IK_ConstructorName: {
4692     TypeSourceInfo *TInfo;
4693     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4694     if (Ty.isNull())
4695       return DeclarationNameInfo();
4696     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4697                                               Context.getCanonicalType(Ty)));
4698     NameInfo.setLoc(Name.StartLocation);
4699     NameInfo.setNamedTypeInfo(TInfo);
4700     return NameInfo;
4701   }
4702 
4703   case UnqualifiedId::IK_ConstructorTemplateId: {
4704     // In well-formed code, we can only have a constructor
4705     // template-id that refers to the current context, so go there
4706     // to find the actual type being constructed.
4707     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4708     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4709       return DeclarationNameInfo();
4710 
4711     // Determine the type of the class being constructed.
4712     QualType CurClassType = Context.getTypeDeclType(CurClass);
4713 
4714     // FIXME: Check two things: that the template-id names the same type as
4715     // CurClassType, and that the template-id does not occur when the name
4716     // was qualified.
4717 
4718     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4719                                     Context.getCanonicalType(CurClassType)));
4720     NameInfo.setLoc(Name.StartLocation);
4721     // FIXME: should we retrieve TypeSourceInfo?
4722     NameInfo.setNamedTypeInfo(nullptr);
4723     return NameInfo;
4724   }
4725 
4726   case UnqualifiedId::IK_DestructorName: {
4727     TypeSourceInfo *TInfo;
4728     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4729     if (Ty.isNull())
4730       return DeclarationNameInfo();
4731     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4732                                               Context.getCanonicalType(Ty)));
4733     NameInfo.setLoc(Name.StartLocation);
4734     NameInfo.setNamedTypeInfo(TInfo);
4735     return NameInfo;
4736   }
4737 
4738   case UnqualifiedId::IK_TemplateId: {
4739     TemplateName TName = Name.TemplateId->Template.get();
4740     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4741     return Context.getNameForTemplate(TName, TNameLoc);
4742   }
4743 
4744   } // switch (Name.getKind())
4745 
4746   llvm_unreachable("Unknown name kind");
4747 }
4748 
4749 static QualType getCoreType(QualType Ty) {
4750   do {
4751     if (Ty->isPointerType() || Ty->isReferenceType())
4752       Ty = Ty->getPointeeType();
4753     else if (Ty->isArrayType())
4754       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4755     else
4756       return Ty.withoutLocalFastQualifiers();
4757   } while (true);
4758 }
4759 
4760 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4761 /// and Definition have "nearly" matching parameters. This heuristic is
4762 /// used to improve diagnostics in the case where an out-of-line function
4763 /// definition doesn't match any declaration within the class or namespace.
4764 /// Also sets Params to the list of indices to the parameters that differ
4765 /// between the declaration and the definition. If hasSimilarParameters
4766 /// returns true and Params is empty, then all of the parameters match.
4767 static bool hasSimilarParameters(ASTContext &Context,
4768                                      FunctionDecl *Declaration,
4769                                      FunctionDecl *Definition,
4770                                      SmallVectorImpl<unsigned> &Params) {
4771   Params.clear();
4772   if (Declaration->param_size() != Definition->param_size())
4773     return false;
4774   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4775     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4776     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4777 
4778     // The parameter types are identical
4779     if (Context.hasSameType(DefParamTy, DeclParamTy))
4780       continue;
4781 
4782     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4783     QualType DefParamBaseTy = getCoreType(DefParamTy);
4784     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4785     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4786 
4787     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4788         (DeclTyName && DeclTyName == DefTyName))
4789       Params.push_back(Idx);
4790     else  // The two parameters aren't even close
4791       return false;
4792   }
4793 
4794   return true;
4795 }
4796 
4797 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4798 /// declarator needs to be rebuilt in the current instantiation.
4799 /// Any bits of declarator which appear before the name are valid for
4800 /// consideration here.  That's specifically the type in the decl spec
4801 /// and the base type in any member-pointer chunks.
4802 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4803                                                     DeclarationName Name) {
4804   // The types we specifically need to rebuild are:
4805   //   - typenames, typeofs, and decltypes
4806   //   - types which will become injected class names
4807   // Of course, we also need to rebuild any type referencing such a
4808   // type.  It's safest to just say "dependent", but we call out a
4809   // few cases here.
4810 
4811   DeclSpec &DS = D.getMutableDeclSpec();
4812   switch (DS.getTypeSpecType()) {
4813   case DeclSpec::TST_typename:
4814   case DeclSpec::TST_typeofType:
4815   case DeclSpec::TST_underlyingType:
4816   case DeclSpec::TST_atomic: {
4817     // Grab the type from the parser.
4818     TypeSourceInfo *TSI = nullptr;
4819     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4820     if (T.isNull() || !T->isDependentType()) break;
4821 
4822     // Make sure there's a type source info.  This isn't really much
4823     // of a waste; most dependent types should have type source info
4824     // attached already.
4825     if (!TSI)
4826       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4827 
4828     // Rebuild the type in the current instantiation.
4829     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4830     if (!TSI) return true;
4831 
4832     // Store the new type back in the decl spec.
4833     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4834     DS.UpdateTypeRep(LocType);
4835     break;
4836   }
4837 
4838   case DeclSpec::TST_decltype:
4839   case DeclSpec::TST_typeofExpr: {
4840     Expr *E = DS.getRepAsExpr();
4841     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4842     if (Result.isInvalid()) return true;
4843     DS.UpdateExprRep(Result.get());
4844     break;
4845   }
4846 
4847   default:
4848     // Nothing to do for these decl specs.
4849     break;
4850   }
4851 
4852   // It doesn't matter what order we do this in.
4853   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4854     DeclaratorChunk &Chunk = D.getTypeObject(I);
4855 
4856     // The only type information in the declarator which can come
4857     // before the declaration name is the base type of a member
4858     // pointer.
4859     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4860       continue;
4861 
4862     // Rebuild the scope specifier in-place.
4863     CXXScopeSpec &SS = Chunk.Mem.Scope();
4864     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4865       return true;
4866   }
4867 
4868   return false;
4869 }
4870 
4871 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4872   D.setFunctionDefinitionKind(FDK_Declaration);
4873   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4874 
4875   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4876       Dcl && Dcl->getDeclContext()->isFileContext())
4877     Dcl->setTopLevelDeclInObjCContainer();
4878 
4879   if (getLangOpts().OpenCL)
4880     setCurrentOpenCLExtensionForDecl(Dcl);
4881 
4882   return Dcl;
4883 }
4884 
4885 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4886 ///   If T is the name of a class, then each of the following shall have a
4887 ///   name different from T:
4888 ///     - every static data member of class T;
4889 ///     - every member function of class T
4890 ///     - every member of class T that is itself a type;
4891 /// \returns true if the declaration name violates these rules.
4892 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4893                                    DeclarationNameInfo NameInfo) {
4894   DeclarationName Name = NameInfo.getName();
4895 
4896   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
4897   while (Record && Record->isAnonymousStructOrUnion())
4898     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
4899   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
4900     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4901     return true;
4902   }
4903 
4904   return false;
4905 }
4906 
4907 /// \brief Diagnose a declaration whose declarator-id has the given
4908 /// nested-name-specifier.
4909 ///
4910 /// \param SS The nested-name-specifier of the declarator-id.
4911 ///
4912 /// \param DC The declaration context to which the nested-name-specifier
4913 /// resolves.
4914 ///
4915 /// \param Name The name of the entity being declared.
4916 ///
4917 /// \param Loc The location of the name of the entity being declared.
4918 ///
4919 /// \returns true if we cannot safely recover from this error, false otherwise.
4920 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4921                                         DeclarationName Name,
4922                                         SourceLocation Loc) {
4923   DeclContext *Cur = CurContext;
4924   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4925     Cur = Cur->getParent();
4926 
4927   // If the user provided a superfluous scope specifier that refers back to the
4928   // class in which the entity is already declared, diagnose and ignore it.
4929   //
4930   // class X {
4931   //   void X::f();
4932   // };
4933   //
4934   // Note, it was once ill-formed to give redundant qualification in all
4935   // contexts, but that rule was removed by DR482.
4936   if (Cur->Equals(DC)) {
4937     if (Cur->isRecord()) {
4938       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4939                                       : diag::err_member_extra_qualification)
4940         << Name << FixItHint::CreateRemoval(SS.getRange());
4941       SS.clear();
4942     } else {
4943       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4944     }
4945     return false;
4946   }
4947 
4948   // Check whether the qualifying scope encloses the scope of the original
4949   // declaration.
4950   if (!Cur->Encloses(DC)) {
4951     if (Cur->isRecord())
4952       Diag(Loc, diag::err_member_qualification)
4953         << Name << SS.getRange();
4954     else if (isa<TranslationUnitDecl>(DC))
4955       Diag(Loc, diag::err_invalid_declarator_global_scope)
4956         << Name << SS.getRange();
4957     else if (isa<FunctionDecl>(Cur))
4958       Diag(Loc, diag::err_invalid_declarator_in_function)
4959         << Name << SS.getRange();
4960     else if (isa<BlockDecl>(Cur))
4961       Diag(Loc, diag::err_invalid_declarator_in_block)
4962         << Name << SS.getRange();
4963     else
4964       Diag(Loc, diag::err_invalid_declarator_scope)
4965       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4966 
4967     return true;
4968   }
4969 
4970   if (Cur->isRecord()) {
4971     // Cannot qualify members within a class.
4972     Diag(Loc, diag::err_member_qualification)
4973       << Name << SS.getRange();
4974     SS.clear();
4975 
4976     // C++ constructors and destructors with incorrect scopes can break
4977     // our AST invariants by having the wrong underlying types. If
4978     // that's the case, then drop this declaration entirely.
4979     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4980          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4981         !Context.hasSameType(Name.getCXXNameType(),
4982                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4983       return true;
4984 
4985     return false;
4986   }
4987 
4988   // C++11 [dcl.meaning]p1:
4989   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4990   //   not begin with a decltype-specifer"
4991   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4992   while (SpecLoc.getPrefix())
4993     SpecLoc = SpecLoc.getPrefix();
4994   if (dyn_cast_or_null<DecltypeType>(
4995         SpecLoc.getNestedNameSpecifier()->getAsType()))
4996     Diag(Loc, diag::err_decltype_in_declarator)
4997       << SpecLoc.getTypeLoc().getSourceRange();
4998 
4999   return false;
5000 }
5001 
5002 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
5003                                   MultiTemplateParamsArg TemplateParamLists) {
5004   // TODO: consider using NameInfo for diagnostic.
5005   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5006   DeclarationName Name = NameInfo.getName();
5007 
5008   // All of these full declarators require an identifier.  If it doesn't have
5009   // one, the ParsedFreeStandingDeclSpec action should be used.
5010   if (D.isDecompositionDeclarator()) {
5011     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5012   } else if (!Name) {
5013     if (!D.isInvalidType())  // Reject this if we think it is valid.
5014       Diag(D.getDeclSpec().getLocStart(),
5015            diag::err_declarator_need_ident)
5016         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5017     return nullptr;
5018   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5019     return nullptr;
5020 
5021   // The scope passed in may not be a decl scope.  Zip up the scope tree until
5022   // we find one that is.
5023   while ((S->getFlags() & Scope::DeclScope) == 0 ||
5024          (S->getFlags() & Scope::TemplateParamScope) != 0)
5025     S = S->getParent();
5026 
5027   DeclContext *DC = CurContext;
5028   if (D.getCXXScopeSpec().isInvalid())
5029     D.setInvalidType();
5030   else if (D.getCXXScopeSpec().isSet()) {
5031     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5032                                         UPPC_DeclarationQualifier))
5033       return nullptr;
5034 
5035     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5036     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5037     if (!DC || isa<EnumDecl>(DC)) {
5038       // If we could not compute the declaration context, it's because the
5039       // declaration context is dependent but does not refer to a class,
5040       // class template, or class template partial specialization. Complain
5041       // and return early, to avoid the coming semantic disaster.
5042       Diag(D.getIdentifierLoc(),
5043            diag::err_template_qualified_declarator_no_match)
5044         << D.getCXXScopeSpec().getScopeRep()
5045         << D.getCXXScopeSpec().getRange();
5046       return nullptr;
5047     }
5048     bool IsDependentContext = DC->isDependentContext();
5049 
5050     if (!IsDependentContext &&
5051         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5052       return nullptr;
5053 
5054     // If a class is incomplete, do not parse entities inside it.
5055     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5056       Diag(D.getIdentifierLoc(),
5057            diag::err_member_def_undefined_record)
5058         << Name << DC << D.getCXXScopeSpec().getRange();
5059       return nullptr;
5060     }
5061     if (!D.getDeclSpec().isFriendSpecified()) {
5062       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
5063                                       Name, D.getIdentifierLoc())) {
5064         if (DC->isRecord())
5065           return nullptr;
5066 
5067         D.setInvalidType();
5068       }
5069     }
5070 
5071     // Check whether we need to rebuild the type of the given
5072     // declaration in the current instantiation.
5073     if (EnteringContext && IsDependentContext &&
5074         TemplateParamLists.size() != 0) {
5075       ContextRAII SavedContext(*this, DC);
5076       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5077         D.setInvalidType();
5078     }
5079   }
5080 
5081   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5082   QualType R = TInfo->getType();
5083 
5084   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5085     // If this is a typedef, we'll end up spewing multiple diagnostics.
5086     // Just return early; it's safer. If this is a function, let the
5087     // "constructor cannot have a return type" diagnostic handle it.
5088     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5089       return nullptr;
5090 
5091   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5092                                       UPPC_DeclarationType))
5093     D.setInvalidType();
5094 
5095   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5096                         ForRedeclaration);
5097 
5098   // See if this is a redefinition of a variable in the same scope.
5099   if (!D.getCXXScopeSpec().isSet()) {
5100     bool IsLinkageLookup = false;
5101     bool CreateBuiltins = false;
5102 
5103     // If the declaration we're planning to build will be a function
5104     // or object with linkage, then look for another declaration with
5105     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5106     //
5107     // If the declaration we're planning to build will be declared with
5108     // external linkage in the translation unit, create any builtin with
5109     // the same name.
5110     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5111       /* Do nothing*/;
5112     else if (CurContext->isFunctionOrMethod() &&
5113              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5114               R->isFunctionType())) {
5115       IsLinkageLookup = true;
5116       CreateBuiltins =
5117           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5118     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5119                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5120       CreateBuiltins = true;
5121 
5122     if (IsLinkageLookup)
5123       Previous.clear(LookupRedeclarationWithLinkage);
5124 
5125     LookupName(Previous, S, CreateBuiltins);
5126   } else { // Something like "int foo::x;"
5127     LookupQualifiedName(Previous, DC);
5128 
5129     // C++ [dcl.meaning]p1:
5130     //   When the declarator-id is qualified, the declaration shall refer to a
5131     //  previously declared member of the class or namespace to which the
5132     //  qualifier refers (or, in the case of a namespace, of an element of the
5133     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5134     //  thereof; [...]
5135     //
5136     // Note that we already checked the context above, and that we do not have
5137     // enough information to make sure that Previous contains the declaration
5138     // we want to match. For example, given:
5139     //
5140     //   class X {
5141     //     void f();
5142     //     void f(float);
5143     //   };
5144     //
5145     //   void X::f(int) { } // ill-formed
5146     //
5147     // In this case, Previous will point to the overload set
5148     // containing the two f's declared in X, but neither of them
5149     // matches.
5150 
5151     // C++ [dcl.meaning]p1:
5152     //   [...] the member shall not merely have been introduced by a
5153     //   using-declaration in the scope of the class or namespace nominated by
5154     //   the nested-name-specifier of the declarator-id.
5155     RemoveUsingDecls(Previous);
5156   }
5157 
5158   if (Previous.isSingleResult() &&
5159       Previous.getFoundDecl()->isTemplateParameter()) {
5160     // Maybe we will complain about the shadowed template parameter.
5161     if (!D.isInvalidType())
5162       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5163                                       Previous.getFoundDecl());
5164 
5165     // Just pretend that we didn't see the previous declaration.
5166     Previous.clear();
5167   }
5168 
5169   // In C++, the previous declaration we find might be a tag type
5170   // (class or enum). In this case, the new declaration will hide the
5171   // tag type. Note that this does does not apply if we're declaring a
5172   // typedef (C++ [dcl.typedef]p4).
5173   if (Previous.isSingleTagDecl() &&
5174       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5175     Previous.clear();
5176 
5177   // Check that there are no default arguments other than in the parameters
5178   // of a function declaration (C++ only).
5179   if (getLangOpts().CPlusPlus)
5180     CheckExtraCXXDefaultArguments(D);
5181 
5182   if (D.getDeclSpec().isConceptSpecified()) {
5183     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5184     // applied only to the definition of a function template or variable
5185     // template, declared in namespace scope
5186     if (!TemplateParamLists.size()) {
5187       Diag(D.getDeclSpec().getConceptSpecLoc(),
5188            diag:: err_concept_wrong_decl_kind);
5189       return nullptr;
5190     }
5191 
5192     if (!DC->getRedeclContext()->isFileContext()) {
5193       Diag(D.getIdentifierLoc(),
5194            diag::err_concept_decls_may_only_appear_in_namespace_scope);
5195       return nullptr;
5196     }
5197   }
5198 
5199   NamedDecl *New;
5200 
5201   bool AddToScope = true;
5202   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5203     if (TemplateParamLists.size()) {
5204       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5205       return nullptr;
5206     }
5207 
5208     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5209   } else if (R->isFunctionType()) {
5210     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5211                                   TemplateParamLists,
5212                                   AddToScope);
5213   } else {
5214     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5215                                   AddToScope);
5216   }
5217 
5218   if (!New)
5219     return nullptr;
5220 
5221   // If this has an identifier and is not a function template specialization,
5222   // add it to the scope stack.
5223   if (New->getDeclName() && AddToScope) {
5224     // Only make a locally-scoped extern declaration visible if it is the first
5225     // declaration of this entity. Qualified lookup for such an entity should
5226     // only find this declaration if there is no visible declaration of it.
5227     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5228     PushOnScopeChains(New, S, AddToContext);
5229     if (!AddToContext)
5230       CurContext->addHiddenDecl(New);
5231   }
5232 
5233   if (isInOpenMPDeclareTargetContext())
5234     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5235 
5236   return New;
5237 }
5238 
5239 /// Helper method to turn variable array types into constant array
5240 /// types in certain situations which would otherwise be errors (for
5241 /// GCC compatibility).
5242 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5243                                                     ASTContext &Context,
5244                                                     bool &SizeIsNegative,
5245                                                     llvm::APSInt &Oversized) {
5246   // This method tries to turn a variable array into a constant
5247   // array even when the size isn't an ICE.  This is necessary
5248   // for compatibility with code that depends on gcc's buggy
5249   // constant expression folding, like struct {char x[(int)(char*)2];}
5250   SizeIsNegative = false;
5251   Oversized = 0;
5252 
5253   if (T->isDependentType())
5254     return QualType();
5255 
5256   QualifierCollector Qs;
5257   const Type *Ty = Qs.strip(T);
5258 
5259   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5260     QualType Pointee = PTy->getPointeeType();
5261     QualType FixedType =
5262         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5263                                             Oversized);
5264     if (FixedType.isNull()) return FixedType;
5265     FixedType = Context.getPointerType(FixedType);
5266     return Qs.apply(Context, FixedType);
5267   }
5268   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5269     QualType Inner = PTy->getInnerType();
5270     QualType FixedType =
5271         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5272                                             Oversized);
5273     if (FixedType.isNull()) return FixedType;
5274     FixedType = Context.getParenType(FixedType);
5275     return Qs.apply(Context, FixedType);
5276   }
5277 
5278   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5279   if (!VLATy)
5280     return QualType();
5281   // FIXME: We should probably handle this case
5282   if (VLATy->getElementType()->isVariablyModifiedType())
5283     return QualType();
5284 
5285   llvm::APSInt Res;
5286   if (!VLATy->getSizeExpr() ||
5287       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5288     return QualType();
5289 
5290   // Check whether the array size is negative.
5291   if (Res.isSigned() && Res.isNegative()) {
5292     SizeIsNegative = true;
5293     return QualType();
5294   }
5295 
5296   // Check whether the array is too large to be addressed.
5297   unsigned ActiveSizeBits
5298     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5299                                               Res);
5300   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5301     Oversized = Res;
5302     return QualType();
5303   }
5304 
5305   return Context.getConstantArrayType(VLATy->getElementType(),
5306                                       Res, ArrayType::Normal, 0);
5307 }
5308 
5309 static void
5310 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5311   SrcTL = SrcTL.getUnqualifiedLoc();
5312   DstTL = DstTL.getUnqualifiedLoc();
5313   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5314     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5315     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5316                                       DstPTL.getPointeeLoc());
5317     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5318     return;
5319   }
5320   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5321     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5322     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5323                                       DstPTL.getInnerLoc());
5324     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5325     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5326     return;
5327   }
5328   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5329   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5330   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5331   TypeLoc DstElemTL = DstATL.getElementLoc();
5332   DstElemTL.initializeFullCopy(SrcElemTL);
5333   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5334   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5335   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5336 }
5337 
5338 /// Helper method to turn variable array types into constant array
5339 /// types in certain situations which would otherwise be errors (for
5340 /// GCC compatibility).
5341 static TypeSourceInfo*
5342 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5343                                               ASTContext &Context,
5344                                               bool &SizeIsNegative,
5345                                               llvm::APSInt &Oversized) {
5346   QualType FixedTy
5347     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5348                                           SizeIsNegative, Oversized);
5349   if (FixedTy.isNull())
5350     return nullptr;
5351   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5352   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5353                                     FixedTInfo->getTypeLoc());
5354   return FixedTInfo;
5355 }
5356 
5357 /// \brief Register the given locally-scoped extern "C" declaration so
5358 /// that it can be found later for redeclarations. We include any extern "C"
5359 /// declaration that is not visible in the translation unit here, not just
5360 /// function-scope declarations.
5361 void
5362 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5363   if (!getLangOpts().CPlusPlus &&
5364       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5365     // Don't need to track declarations in the TU in C.
5366     return;
5367 
5368   // Note that we have a locally-scoped external with this name.
5369   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5370 }
5371 
5372 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5373   // FIXME: We can have multiple results via __attribute__((overloadable)).
5374   auto Result = Context.getExternCContextDecl()->lookup(Name);
5375   return Result.empty() ? nullptr : *Result.begin();
5376 }
5377 
5378 /// \brief Diagnose function specifiers on a declaration of an identifier that
5379 /// does not identify a function.
5380 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5381   // FIXME: We should probably indicate the identifier in question to avoid
5382   // confusion for constructs like "virtual int a(), b;"
5383   if (DS.isVirtualSpecified())
5384     Diag(DS.getVirtualSpecLoc(),
5385          diag::err_virtual_non_function);
5386 
5387   if (DS.isExplicitSpecified())
5388     Diag(DS.getExplicitSpecLoc(),
5389          diag::err_explicit_non_function);
5390 
5391   if (DS.isNoreturnSpecified())
5392     Diag(DS.getNoreturnSpecLoc(),
5393          diag::err_noreturn_non_function);
5394 }
5395 
5396 NamedDecl*
5397 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5398                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5399   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5400   if (D.getCXXScopeSpec().isSet()) {
5401     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5402       << D.getCXXScopeSpec().getRange();
5403     D.setInvalidType();
5404     // Pretend we didn't see the scope specifier.
5405     DC = CurContext;
5406     Previous.clear();
5407   }
5408 
5409   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5410 
5411   if (D.getDeclSpec().isInlineSpecified())
5412     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5413         << getLangOpts().CPlusPlus1z;
5414   if (D.getDeclSpec().isConstexprSpecified())
5415     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5416       << 1;
5417   if (D.getDeclSpec().isConceptSpecified())
5418     Diag(D.getDeclSpec().getConceptSpecLoc(),
5419          diag::err_concept_wrong_decl_kind);
5420 
5421   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5422     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5423       << D.getName().getSourceRange();
5424     return nullptr;
5425   }
5426 
5427   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5428   if (!NewTD) return nullptr;
5429 
5430   // Handle attributes prior to checking for duplicates in MergeVarDecl
5431   ProcessDeclAttributes(S, NewTD, D);
5432 
5433   CheckTypedefForVariablyModifiedType(S, NewTD);
5434 
5435   bool Redeclaration = D.isRedeclaration();
5436   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5437   D.setRedeclaration(Redeclaration);
5438   return ND;
5439 }
5440 
5441 void
5442 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5443   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5444   // then it shall have block scope.
5445   // Note that variably modified types must be fixed before merging the decl so
5446   // that redeclarations will match.
5447   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5448   QualType T = TInfo->getType();
5449   if (T->isVariablyModifiedType()) {
5450     getCurFunction()->setHasBranchProtectedScope();
5451 
5452     if (S->getFnParent() == nullptr) {
5453       bool SizeIsNegative;
5454       llvm::APSInt Oversized;
5455       TypeSourceInfo *FixedTInfo =
5456         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5457                                                       SizeIsNegative,
5458                                                       Oversized);
5459       if (FixedTInfo) {
5460         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5461         NewTD->setTypeSourceInfo(FixedTInfo);
5462       } else {
5463         if (SizeIsNegative)
5464           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5465         else if (T->isVariableArrayType())
5466           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5467         else if (Oversized.getBoolValue())
5468           Diag(NewTD->getLocation(), diag::err_array_too_large)
5469             << Oversized.toString(10);
5470         else
5471           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5472         NewTD->setInvalidDecl();
5473       }
5474     }
5475   }
5476 }
5477 
5478 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5479 /// declares a typedef-name, either using the 'typedef' type specifier or via
5480 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5481 NamedDecl*
5482 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5483                            LookupResult &Previous, bool &Redeclaration) {
5484   // Merge the decl with the existing one if appropriate. If the decl is
5485   // in an outer scope, it isn't the same thing.
5486   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5487                        /*AllowInlineNamespace*/false);
5488   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5489   if (!Previous.empty()) {
5490     Redeclaration = true;
5491     MergeTypedefNameDecl(S, NewTD, Previous);
5492   }
5493 
5494   // If this is the C FILE type, notify the AST context.
5495   if (IdentifierInfo *II = NewTD->getIdentifier())
5496     if (!NewTD->isInvalidDecl() &&
5497         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5498       if (II->isStr("FILE"))
5499         Context.setFILEDecl(NewTD);
5500       else if (II->isStr("jmp_buf"))
5501         Context.setjmp_bufDecl(NewTD);
5502       else if (II->isStr("sigjmp_buf"))
5503         Context.setsigjmp_bufDecl(NewTD);
5504       else if (II->isStr("ucontext_t"))
5505         Context.setucontext_tDecl(NewTD);
5506     }
5507 
5508   return NewTD;
5509 }
5510 
5511 /// \brief Determines whether the given declaration is an out-of-scope
5512 /// previous declaration.
5513 ///
5514 /// This routine should be invoked when name lookup has found a
5515 /// previous declaration (PrevDecl) that is not in the scope where a
5516 /// new declaration by the same name is being introduced. If the new
5517 /// declaration occurs in a local scope, previous declarations with
5518 /// linkage may still be considered previous declarations (C99
5519 /// 6.2.2p4-5, C++ [basic.link]p6).
5520 ///
5521 /// \param PrevDecl the previous declaration found by name
5522 /// lookup
5523 ///
5524 /// \param DC the context in which the new declaration is being
5525 /// declared.
5526 ///
5527 /// \returns true if PrevDecl is an out-of-scope previous declaration
5528 /// for a new delcaration with the same name.
5529 static bool
5530 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5531                                 ASTContext &Context) {
5532   if (!PrevDecl)
5533     return false;
5534 
5535   if (!PrevDecl->hasLinkage())
5536     return false;
5537 
5538   if (Context.getLangOpts().CPlusPlus) {
5539     // C++ [basic.link]p6:
5540     //   If there is a visible declaration of an entity with linkage
5541     //   having the same name and type, ignoring entities declared
5542     //   outside the innermost enclosing namespace scope, the block
5543     //   scope declaration declares that same entity and receives the
5544     //   linkage of the previous declaration.
5545     DeclContext *OuterContext = DC->getRedeclContext();
5546     if (!OuterContext->isFunctionOrMethod())
5547       // This rule only applies to block-scope declarations.
5548       return false;
5549 
5550     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5551     if (PrevOuterContext->isRecord())
5552       // We found a member function: ignore it.
5553       return false;
5554 
5555     // Find the innermost enclosing namespace for the new and
5556     // previous declarations.
5557     OuterContext = OuterContext->getEnclosingNamespaceContext();
5558     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5559 
5560     // The previous declaration is in a different namespace, so it
5561     // isn't the same function.
5562     if (!OuterContext->Equals(PrevOuterContext))
5563       return false;
5564   }
5565 
5566   return true;
5567 }
5568 
5569 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5570   CXXScopeSpec &SS = D.getCXXScopeSpec();
5571   if (!SS.isSet()) return;
5572   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5573 }
5574 
5575 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5576   QualType type = decl->getType();
5577   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5578   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5579     // Various kinds of declaration aren't allowed to be __autoreleasing.
5580     unsigned kind = -1U;
5581     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5582       if (var->hasAttr<BlocksAttr>())
5583         kind = 0; // __block
5584       else if (!var->hasLocalStorage())
5585         kind = 1; // global
5586     } else if (isa<ObjCIvarDecl>(decl)) {
5587       kind = 3; // ivar
5588     } else if (isa<FieldDecl>(decl)) {
5589       kind = 2; // field
5590     }
5591 
5592     if (kind != -1U) {
5593       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5594         << kind;
5595     }
5596   } else if (lifetime == Qualifiers::OCL_None) {
5597     // Try to infer lifetime.
5598     if (!type->isObjCLifetimeType())
5599       return false;
5600 
5601     lifetime = type->getObjCARCImplicitLifetime();
5602     type = Context.getLifetimeQualifiedType(type, lifetime);
5603     decl->setType(type);
5604   }
5605 
5606   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5607     // Thread-local variables cannot have lifetime.
5608     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5609         var->getTLSKind()) {
5610       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5611         << var->getType();
5612       return true;
5613     }
5614   }
5615 
5616   return false;
5617 }
5618 
5619 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5620   // Ensure that an auto decl is deduced otherwise the checks below might cache
5621   // the wrong linkage.
5622   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5623 
5624   // 'weak' only applies to declarations with external linkage.
5625   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5626     if (!ND.isExternallyVisible()) {
5627       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5628       ND.dropAttr<WeakAttr>();
5629     }
5630   }
5631   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5632     if (ND.isExternallyVisible()) {
5633       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5634       ND.dropAttr<WeakRefAttr>();
5635       ND.dropAttr<AliasAttr>();
5636     }
5637   }
5638 
5639   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5640     if (VD->hasInit()) {
5641       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5642         assert(VD->isThisDeclarationADefinition() &&
5643                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5644         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5645         VD->dropAttr<AliasAttr>();
5646       }
5647     }
5648   }
5649 
5650   // 'selectany' only applies to externally visible variable declarations.
5651   // It does not apply to functions.
5652   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5653     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5654       S.Diag(Attr->getLocation(),
5655              diag::err_attribute_selectany_non_extern_data);
5656       ND.dropAttr<SelectAnyAttr>();
5657     }
5658   }
5659 
5660   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5661     // dll attributes require external linkage. Static locals may have external
5662     // linkage but still cannot be explicitly imported or exported.
5663     auto *VD = dyn_cast<VarDecl>(&ND);
5664     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5665       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5666         << &ND << Attr;
5667       ND.setInvalidDecl();
5668     }
5669   }
5670 
5671   // Virtual functions cannot be marked as 'notail'.
5672   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5673     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5674       if (MD->isVirtual()) {
5675         S.Diag(ND.getLocation(),
5676                diag::err_invalid_attribute_on_virtual_function)
5677             << Attr;
5678         ND.dropAttr<NotTailCalledAttr>();
5679       }
5680 }
5681 
5682 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5683                                            NamedDecl *NewDecl,
5684                                            bool IsSpecialization,
5685                                            bool IsDefinition) {
5686   if (OldDecl->isInvalidDecl())
5687     return;
5688 
5689   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5690     OldDecl = OldTD->getTemplatedDecl();
5691     if (!IsSpecialization)
5692       IsDefinition = false;
5693   }
5694   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5695     NewDecl = NewTD->getTemplatedDecl();
5696 
5697   if (!OldDecl || !NewDecl)
5698     return;
5699 
5700   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5701   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5702   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5703   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5704 
5705   // dllimport and dllexport are inheritable attributes so we have to exclude
5706   // inherited attribute instances.
5707   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5708                     (NewExportAttr && !NewExportAttr->isInherited());
5709 
5710   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5711   // the only exception being explicit specializations.
5712   // Implicitly generated declarations are also excluded for now because there
5713   // is no other way to switch these to use dllimport or dllexport.
5714   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5715 
5716   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5717     // Allow with a warning for free functions and global variables.
5718     bool JustWarn = false;
5719     if (!OldDecl->isCXXClassMember()) {
5720       auto *VD = dyn_cast<VarDecl>(OldDecl);
5721       if (VD && !VD->getDescribedVarTemplate())
5722         JustWarn = true;
5723       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5724       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5725         JustWarn = true;
5726     }
5727 
5728     // We cannot change a declaration that's been used because IR has already
5729     // been emitted. Dllimported functions will still work though (modulo
5730     // address equality) as they can use the thunk.
5731     if (OldDecl->isUsed())
5732       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5733         JustWarn = false;
5734 
5735     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5736                                : diag::err_attribute_dll_redeclaration;
5737     S.Diag(NewDecl->getLocation(), DiagID)
5738         << NewDecl
5739         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5740     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5741     if (!JustWarn) {
5742       NewDecl->setInvalidDecl();
5743       return;
5744     }
5745   }
5746 
5747   // A redeclaration is not allowed to drop a dllimport attribute, the only
5748   // exceptions being inline function definitions, local extern declarations,
5749   // qualified friend declarations or special MSVC extension: in the last case,
5750   // the declaration is treated as if it were marked dllexport.
5751   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5752   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5753   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5754     // Ignore static data because out-of-line definitions are diagnosed
5755     // separately.
5756     IsStaticDataMember = VD->isStaticDataMember();
5757     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5758                    VarDecl::DeclarationOnly;
5759   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5760     IsInline = FD->isInlined();
5761     IsQualifiedFriend = FD->getQualifier() &&
5762                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5763   }
5764 
5765   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5766       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5767     if (IsMicrosoft && IsDefinition) {
5768       S.Diag(NewDecl->getLocation(),
5769              diag::warn_redeclaration_without_import_attribute)
5770           << NewDecl;
5771       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5772       NewDecl->dropAttr<DLLImportAttr>();
5773       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
5774           NewImportAttr->getRange(), S.Context,
5775           NewImportAttr->getSpellingListIndex()));
5776     } else {
5777       S.Diag(NewDecl->getLocation(),
5778              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5779           << NewDecl << OldImportAttr;
5780       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5781       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5782       OldDecl->dropAttr<DLLImportAttr>();
5783       NewDecl->dropAttr<DLLImportAttr>();
5784     }
5785   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
5786     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5787     OldDecl->dropAttr<DLLImportAttr>();
5788     NewDecl->dropAttr<DLLImportAttr>();
5789     S.Diag(NewDecl->getLocation(),
5790            diag::warn_dllimport_dropped_from_inline_function)
5791         << NewDecl << OldImportAttr;
5792   }
5793 }
5794 
5795 /// Given that we are within the definition of the given function,
5796 /// will that definition behave like C99's 'inline', where the
5797 /// definition is discarded except for optimization purposes?
5798 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5799   // Try to avoid calling GetGVALinkageForFunction.
5800 
5801   // All cases of this require the 'inline' keyword.
5802   if (!FD->isInlined()) return false;
5803 
5804   // This is only possible in C++ with the gnu_inline attribute.
5805   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5806     return false;
5807 
5808   // Okay, go ahead and call the relatively-more-expensive function.
5809   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5810 }
5811 
5812 /// Determine whether a variable is extern "C" prior to attaching
5813 /// an initializer. We can't just call isExternC() here, because that
5814 /// will also compute and cache whether the declaration is externally
5815 /// visible, which might change when we attach the initializer.
5816 ///
5817 /// This can only be used if the declaration is known to not be a
5818 /// redeclaration of an internal linkage declaration.
5819 ///
5820 /// For instance:
5821 ///
5822 ///   auto x = []{};
5823 ///
5824 /// Attaching the initializer here makes this declaration not externally
5825 /// visible, because its type has internal linkage.
5826 ///
5827 /// FIXME: This is a hack.
5828 template<typename T>
5829 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5830   if (S.getLangOpts().CPlusPlus) {
5831     // In C++, the overloadable attribute negates the effects of extern "C".
5832     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5833       return false;
5834 
5835     // So do CUDA's host/device attributes.
5836     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
5837                                  D->template hasAttr<CUDAHostAttr>()))
5838       return false;
5839   }
5840   return D->isExternC();
5841 }
5842 
5843 static bool shouldConsiderLinkage(const VarDecl *VD) {
5844   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5845   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
5846     return VD->hasExternalStorage();
5847   if (DC->isFileContext())
5848     return true;
5849   if (DC->isRecord())
5850     return false;
5851   llvm_unreachable("Unexpected context");
5852 }
5853 
5854 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5855   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5856   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
5857       isa<OMPDeclareReductionDecl>(DC))
5858     return true;
5859   if (DC->isRecord())
5860     return false;
5861   llvm_unreachable("Unexpected context");
5862 }
5863 
5864 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5865                           AttributeList::Kind Kind) {
5866   for (const AttributeList *L = AttrList; L; L = L->getNext())
5867     if (L->getKind() == Kind)
5868       return true;
5869   return false;
5870 }
5871 
5872 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5873                           AttributeList::Kind Kind) {
5874   // Check decl attributes on the DeclSpec.
5875   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5876     return true;
5877 
5878   // Walk the declarator structure, checking decl attributes that were in a type
5879   // position to the decl itself.
5880   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5881     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5882       return true;
5883   }
5884 
5885   // Finally, check attributes on the decl itself.
5886   return hasParsedAttr(S, PD.getAttributes(), Kind);
5887 }
5888 
5889 /// Adjust the \c DeclContext for a function or variable that might be a
5890 /// function-local external declaration.
5891 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5892   if (!DC->isFunctionOrMethod())
5893     return false;
5894 
5895   // If this is a local extern function or variable declared within a function
5896   // template, don't add it into the enclosing namespace scope until it is
5897   // instantiated; it might have a dependent type right now.
5898   if (DC->isDependentContext())
5899     return true;
5900 
5901   // C++11 [basic.link]p7:
5902   //   When a block scope declaration of an entity with linkage is not found to
5903   //   refer to some other declaration, then that entity is a member of the
5904   //   innermost enclosing namespace.
5905   //
5906   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5907   // semantically-enclosing namespace, not a lexically-enclosing one.
5908   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5909     DC = DC->getParent();
5910   return true;
5911 }
5912 
5913 /// \brief Returns true if given declaration has external C language linkage.
5914 static bool isDeclExternC(const Decl *D) {
5915   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5916     return FD->isExternC();
5917   if (const auto *VD = dyn_cast<VarDecl>(D))
5918     return VD->isExternC();
5919 
5920   llvm_unreachable("Unknown type of decl!");
5921 }
5922 
5923 NamedDecl *Sema::ActOnVariableDeclarator(
5924     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
5925     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
5926     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
5927   QualType R = TInfo->getType();
5928   DeclarationName Name = GetNameForDeclarator(D).getName();
5929 
5930   IdentifierInfo *II = Name.getAsIdentifierInfo();
5931 
5932   if (D.isDecompositionDeclarator()) {
5933     AddToScope = false;
5934     // Take the name of the first declarator as our name for diagnostic
5935     // purposes.
5936     auto &Decomp = D.getDecompositionDeclarator();
5937     if (!Decomp.bindings().empty()) {
5938       II = Decomp.bindings()[0].Name;
5939       Name = II;
5940     }
5941   } else if (!II) {
5942     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5943       << Name;
5944     return nullptr;
5945   }
5946 
5947   if (getLangOpts().OpenCL) {
5948     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
5949     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
5950     // argument.
5951     if (R->isImageType() || R->isPipeType()) {
5952       Diag(D.getIdentifierLoc(),
5953            diag::err_opencl_type_can_only_be_used_as_function_parameter)
5954           << R;
5955       D.setInvalidType();
5956       return nullptr;
5957     }
5958 
5959     // OpenCL v1.2 s6.9.r:
5960     // The event type cannot be used to declare a program scope variable.
5961     // OpenCL v2.0 s6.9.q:
5962     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
5963     if (NULL == S->getParent()) {
5964       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
5965         Diag(D.getIdentifierLoc(),
5966              diag::err_invalid_type_for_program_scope_var) << R;
5967         D.setInvalidType();
5968         return nullptr;
5969       }
5970     }
5971 
5972     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5973     QualType NR = R;
5974     while (NR->isPointerType()) {
5975       if (NR->isFunctionPointerType()) {
5976         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5977         D.setInvalidType();
5978         break;
5979       }
5980       NR = NR->getPointeeType();
5981     }
5982 
5983     if (!getOpenCLOptions().isEnabled("cl_khr_fp16")) {
5984       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5985       // half array type (unless the cl_khr_fp16 extension is enabled).
5986       if (Context.getBaseElementType(R)->isHalfType()) {
5987         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5988         D.setInvalidType();
5989       }
5990     }
5991 
5992     // OpenCL v1.2 s6.9.b p4:
5993     // The sampler type cannot be used with the __local and __global address
5994     // space qualifiers.
5995     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5996       R.getAddressSpace() == LangAS::opencl_global)) {
5997       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5998     }
5999 
6000     // OpenCL v1.2 s6.9.r:
6001     // The event type cannot be used with the __local, __constant and __global
6002     // address space qualifiers.
6003     if (R->isEventT()) {
6004       if (R.getAddressSpace()) {
6005         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
6006         D.setInvalidType();
6007       }
6008     }
6009   }
6010 
6011   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
6012   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
6013 
6014   // dllimport globals without explicit storage class are treated as extern. We
6015   // have to change the storage class this early to get the right DeclContext.
6016   if (SC == SC_None && !DC->isRecord() &&
6017       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
6018       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
6019     SC = SC_Extern;
6020 
6021   DeclContext *OriginalDC = DC;
6022   bool IsLocalExternDecl = SC == SC_Extern &&
6023                            adjustContextForLocalExternDecl(DC);
6024 
6025   if (SCSpec == DeclSpec::SCS_mutable) {
6026     // mutable can only appear on non-static class members, so it's always
6027     // an error here
6028     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
6029     D.setInvalidType();
6030     SC = SC_None;
6031   }
6032 
6033   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
6034       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
6035                               D.getDeclSpec().getStorageClassSpecLoc())) {
6036     // In C++11, the 'register' storage class specifier is deprecated.
6037     // Suppress the warning in system macros, it's used in macros in some
6038     // popular C system headers, such as in glibc's htonl() macro.
6039     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6040          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
6041                                    : diag::warn_deprecated_register)
6042       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6043   }
6044 
6045   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6046 
6047   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6048     // C99 6.9p2: The storage-class specifiers auto and register shall not
6049     // appear in the declaration specifiers in an external declaration.
6050     // Global Register+Asm is a GNU extension we support.
6051     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6052       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6053       D.setInvalidType();
6054     }
6055   }
6056 
6057   bool IsExplicitSpecialization = false;
6058   bool IsVariableTemplateSpecialization = false;
6059   bool IsPartialSpecialization = false;
6060   bool IsVariableTemplate = false;
6061   VarDecl *NewVD = nullptr;
6062   VarTemplateDecl *NewTemplate = nullptr;
6063   TemplateParameterList *TemplateParams = nullptr;
6064   if (!getLangOpts().CPlusPlus) {
6065     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6066                             D.getIdentifierLoc(), II,
6067                             R, TInfo, SC);
6068 
6069     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
6070       ParsingInitForAutoVars.insert(NewVD);
6071 
6072     if (D.isInvalidType())
6073       NewVD->setInvalidDecl();
6074   } else {
6075     bool Invalid = false;
6076 
6077     if (DC->isRecord() && !CurContext->isRecord()) {
6078       // This is an out-of-line definition of a static data member.
6079       switch (SC) {
6080       case SC_None:
6081         break;
6082       case SC_Static:
6083         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6084              diag::err_static_out_of_line)
6085           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6086         break;
6087       case SC_Auto:
6088       case SC_Register:
6089       case SC_Extern:
6090         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6091         // to names of variables declared in a block or to function parameters.
6092         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6093         // of class members
6094 
6095         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6096              diag::err_storage_class_for_static_member)
6097           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6098         break;
6099       case SC_PrivateExtern:
6100         llvm_unreachable("C storage class in c++!");
6101       }
6102     }
6103 
6104     if (SC == SC_Static && CurContext->isRecord()) {
6105       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6106         if (RD->isLocalClass())
6107           Diag(D.getIdentifierLoc(),
6108                diag::err_static_data_member_not_allowed_in_local_class)
6109             << Name << RD->getDeclName();
6110 
6111         // C++98 [class.union]p1: If a union contains a static data member,
6112         // the program is ill-formed. C++11 drops this restriction.
6113         if (RD->isUnion())
6114           Diag(D.getIdentifierLoc(),
6115                getLangOpts().CPlusPlus11
6116                  ? diag::warn_cxx98_compat_static_data_member_in_union
6117                  : diag::ext_static_data_member_in_union) << Name;
6118         // We conservatively disallow static data members in anonymous structs.
6119         else if (!RD->getDeclName())
6120           Diag(D.getIdentifierLoc(),
6121                diag::err_static_data_member_not_allowed_in_anon_struct)
6122             << Name << RD->isUnion();
6123       }
6124     }
6125 
6126     // Match up the template parameter lists with the scope specifier, then
6127     // determine whether we have a template or a template specialization.
6128     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6129         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6130         D.getCXXScopeSpec(),
6131         D.getName().getKind() == UnqualifiedId::IK_TemplateId
6132             ? D.getName().TemplateId
6133             : nullptr,
6134         TemplateParamLists,
6135         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
6136 
6137     if (TemplateParams) {
6138       if (!TemplateParams->size() &&
6139           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6140         // There is an extraneous 'template<>' for this variable. Complain
6141         // about it, but allow the declaration of the variable.
6142         Diag(TemplateParams->getTemplateLoc(),
6143              diag::err_template_variable_noparams)
6144           << II
6145           << SourceRange(TemplateParams->getTemplateLoc(),
6146                          TemplateParams->getRAngleLoc());
6147         TemplateParams = nullptr;
6148       } else {
6149         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6150           // This is an explicit specialization or a partial specialization.
6151           // FIXME: Check that we can declare a specialization here.
6152           IsVariableTemplateSpecialization = true;
6153           IsPartialSpecialization = TemplateParams->size() > 0;
6154         } else { // if (TemplateParams->size() > 0)
6155           // This is a template declaration.
6156           IsVariableTemplate = true;
6157 
6158           // Check that we can declare a template here.
6159           if (CheckTemplateDeclScope(S, TemplateParams))
6160             return nullptr;
6161 
6162           // Only C++1y supports variable templates (N3651).
6163           Diag(D.getIdentifierLoc(),
6164                getLangOpts().CPlusPlus14
6165                    ? diag::warn_cxx11_compat_variable_template
6166                    : diag::ext_variable_template);
6167         }
6168       }
6169     } else {
6170       assert(
6171           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6172           "should have a 'template<>' for this decl");
6173     }
6174 
6175     if (IsVariableTemplateSpecialization) {
6176       SourceLocation TemplateKWLoc =
6177           TemplateParamLists.size() > 0
6178               ? TemplateParamLists[0]->getTemplateLoc()
6179               : SourceLocation();
6180       DeclResult Res = ActOnVarTemplateSpecialization(
6181           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6182           IsPartialSpecialization);
6183       if (Res.isInvalid())
6184         return nullptr;
6185       NewVD = cast<VarDecl>(Res.get());
6186       AddToScope = false;
6187     } else if (D.isDecompositionDeclarator()) {
6188       NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6189                                         D.getIdentifierLoc(), R, TInfo, SC,
6190                                         Bindings);
6191     } else
6192       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6193                               D.getIdentifierLoc(), II, R, TInfo, SC);
6194 
6195     // If this is supposed to be a variable template, create it as such.
6196     if (IsVariableTemplate) {
6197       NewTemplate =
6198           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6199                                   TemplateParams, NewVD);
6200       NewVD->setDescribedVarTemplate(NewTemplate);
6201     }
6202 
6203     // If this decl has an auto type in need of deduction, make a note of the
6204     // Decl so we can diagnose uses of it in its own initializer.
6205     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
6206       ParsingInitForAutoVars.insert(NewVD);
6207 
6208     if (D.isInvalidType() || Invalid) {
6209       NewVD->setInvalidDecl();
6210       if (NewTemplate)
6211         NewTemplate->setInvalidDecl();
6212     }
6213 
6214     SetNestedNameSpecifier(NewVD, D);
6215 
6216     // If we have any template parameter lists that don't directly belong to
6217     // the variable (matching the scope specifier), store them.
6218     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6219     if (TemplateParamLists.size() > VDTemplateParamLists)
6220       NewVD->setTemplateParameterListsInfo(
6221           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6222 
6223     if (D.getDeclSpec().isConstexprSpecified()) {
6224       NewVD->setConstexpr(true);
6225       // C++1z [dcl.spec.constexpr]p1:
6226       //   A static data member declared with the constexpr specifier is
6227       //   implicitly an inline variable.
6228       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6229         NewVD->setImplicitlyInline();
6230     }
6231 
6232     if (D.getDeclSpec().isConceptSpecified()) {
6233       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6234         VTD->setConcept();
6235 
6236       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6237       // be declared with the thread_local, inline, friend, or constexpr
6238       // specifiers, [...]
6239       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6240         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6241              diag::err_concept_decl_invalid_specifiers)
6242             << 0 << 0;
6243         NewVD->setInvalidDecl(true);
6244       }
6245 
6246       if (D.getDeclSpec().isConstexprSpecified()) {
6247         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6248              diag::err_concept_decl_invalid_specifiers)
6249             << 0 << 3;
6250         NewVD->setInvalidDecl(true);
6251       }
6252 
6253       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6254       // applied only to the definition of a function template or variable
6255       // template, declared in namespace scope.
6256       if (IsVariableTemplateSpecialization) {
6257         Diag(D.getDeclSpec().getConceptSpecLoc(),
6258              diag::err_concept_specified_specialization)
6259             << (IsPartialSpecialization ? 2 : 1);
6260       }
6261 
6262       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6263       // following restrictions:
6264       // - The declared type shall have the type bool.
6265       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6266           !NewVD->isInvalidDecl()) {
6267         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6268         NewVD->setInvalidDecl(true);
6269       }
6270     }
6271   }
6272 
6273   if (D.getDeclSpec().isInlineSpecified()) {
6274     if (!getLangOpts().CPlusPlus) {
6275       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6276           << 0;
6277     } else if (CurContext->isFunctionOrMethod()) {
6278       // 'inline' is not allowed on block scope variable declaration.
6279       Diag(D.getDeclSpec().getInlineSpecLoc(),
6280            diag::err_inline_declaration_block_scope) << Name
6281         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6282     } else {
6283       Diag(D.getDeclSpec().getInlineSpecLoc(),
6284            getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6285                                      : diag::ext_inline_variable);
6286       NewVD->setInlineSpecified();
6287     }
6288   }
6289 
6290   // Set the lexical context. If the declarator has a C++ scope specifier, the
6291   // lexical context will be different from the semantic context.
6292   NewVD->setLexicalDeclContext(CurContext);
6293   if (NewTemplate)
6294     NewTemplate->setLexicalDeclContext(CurContext);
6295 
6296   if (IsLocalExternDecl) {
6297     if (D.isDecompositionDeclarator())
6298       for (auto *B : Bindings)
6299         B->setLocalExternDecl();
6300     else
6301       NewVD->setLocalExternDecl();
6302   }
6303 
6304   bool EmitTLSUnsupportedError = false;
6305   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6306     // C++11 [dcl.stc]p4:
6307     //   When thread_local is applied to a variable of block scope the
6308     //   storage-class-specifier static is implied if it does not appear
6309     //   explicitly.
6310     // Core issue: 'static' is not implied if the variable is declared
6311     //   'extern'.
6312     if (NewVD->hasLocalStorage() &&
6313         (SCSpec != DeclSpec::SCS_unspecified ||
6314          TSCS != DeclSpec::TSCS_thread_local ||
6315          !DC->isFunctionOrMethod()))
6316       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6317            diag::err_thread_non_global)
6318         << DeclSpec::getSpecifierName(TSCS);
6319     else if (!Context.getTargetInfo().isTLSSupported()) {
6320       if (getLangOpts().CUDA) {
6321         // Postpone error emission until we've collected attributes required to
6322         // figure out whether it's a host or device variable and whether the
6323         // error should be ignored.
6324         EmitTLSUnsupportedError = true;
6325         // We still need to mark the variable as TLS so it shows up in AST with
6326         // proper storage class for other tools to use even if we're not going
6327         // to emit any code for it.
6328         NewVD->setTSCSpec(TSCS);
6329       } else
6330         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6331              diag::err_thread_unsupported);
6332     } else
6333       NewVD->setTSCSpec(TSCS);
6334   }
6335 
6336   // C99 6.7.4p3
6337   //   An inline definition of a function with external linkage shall
6338   //   not contain a definition of a modifiable object with static or
6339   //   thread storage duration...
6340   // We only apply this when the function is required to be defined
6341   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6342   // that a local variable with thread storage duration still has to
6343   // be marked 'static'.  Also note that it's possible to get these
6344   // semantics in C++ using __attribute__((gnu_inline)).
6345   if (SC == SC_Static && S->getFnParent() != nullptr &&
6346       !NewVD->getType().isConstQualified()) {
6347     FunctionDecl *CurFD = getCurFunctionDecl();
6348     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6349       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6350            diag::warn_static_local_in_extern_inline);
6351       MaybeSuggestAddingStaticToDecl(CurFD);
6352     }
6353   }
6354 
6355   if (D.getDeclSpec().isModulePrivateSpecified()) {
6356     if (IsVariableTemplateSpecialization)
6357       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6358           << (IsPartialSpecialization ? 1 : 0)
6359           << FixItHint::CreateRemoval(
6360                  D.getDeclSpec().getModulePrivateSpecLoc());
6361     else if (IsExplicitSpecialization)
6362       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6363         << 2
6364         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6365     else if (NewVD->hasLocalStorage())
6366       Diag(NewVD->getLocation(), diag::err_module_private_local)
6367         << 0 << NewVD->getDeclName()
6368         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6369         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6370     else {
6371       NewVD->setModulePrivate();
6372       if (NewTemplate)
6373         NewTemplate->setModulePrivate();
6374       for (auto *B : Bindings)
6375         B->setModulePrivate();
6376     }
6377   }
6378 
6379   // Handle attributes prior to checking for duplicates in MergeVarDecl
6380   ProcessDeclAttributes(S, NewVD, D);
6381 
6382   if (getLangOpts().CUDA) {
6383     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6384       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6385            diag::err_thread_unsupported);
6386     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6387     // storage [duration]."
6388     if (SC == SC_None && S->getFnParent() != nullptr &&
6389         (NewVD->hasAttr<CUDASharedAttr>() ||
6390          NewVD->hasAttr<CUDAConstantAttr>())) {
6391       NewVD->setStorageClass(SC_Static);
6392     }
6393   }
6394 
6395   // Ensure that dllimport globals without explicit storage class are treated as
6396   // extern. The storage class is set above using parsed attributes. Now we can
6397   // check the VarDecl itself.
6398   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6399          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6400          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6401 
6402   // In auto-retain/release, infer strong retension for variables of
6403   // retainable type.
6404   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6405     NewVD->setInvalidDecl();
6406 
6407   // Handle GNU asm-label extension (encoded as an attribute).
6408   if (Expr *E = (Expr*)D.getAsmLabel()) {
6409     // The parser guarantees this is a string.
6410     StringLiteral *SE = cast<StringLiteral>(E);
6411     StringRef Label = SE->getString();
6412     if (S->getFnParent() != nullptr) {
6413       switch (SC) {
6414       case SC_None:
6415       case SC_Auto:
6416         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6417         break;
6418       case SC_Register:
6419         // Local Named register
6420         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6421             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6422           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6423         break;
6424       case SC_Static:
6425       case SC_Extern:
6426       case SC_PrivateExtern:
6427         break;
6428       }
6429     } else if (SC == SC_Register) {
6430       // Global Named register
6431       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6432         const auto &TI = Context.getTargetInfo();
6433         bool HasSizeMismatch;
6434 
6435         if (!TI.isValidGCCRegisterName(Label))
6436           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6437         else if (!TI.validateGlobalRegisterVariable(Label,
6438                                                     Context.getTypeSize(R),
6439                                                     HasSizeMismatch))
6440           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6441         else if (HasSizeMismatch)
6442           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6443       }
6444 
6445       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6446         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6447         NewVD->setInvalidDecl(true);
6448       }
6449     }
6450 
6451     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6452                                                 Context, Label, 0));
6453   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6454     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6455       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6456     if (I != ExtnameUndeclaredIdentifiers.end()) {
6457       if (isDeclExternC(NewVD)) {
6458         NewVD->addAttr(I->second);
6459         ExtnameUndeclaredIdentifiers.erase(I);
6460       } else
6461         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6462             << /*Variable*/1 << NewVD;
6463     }
6464   }
6465 
6466   // Find the shadowed declaration before filtering for scope.
6467   NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
6468                                 ? getShadowedDeclaration(NewVD, Previous)
6469                                 : nullptr;
6470 
6471   // Don't consider existing declarations that are in a different
6472   // scope and are out-of-semantic-context declarations (if the new
6473   // declaration has linkage).
6474   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6475                        D.getCXXScopeSpec().isNotEmpty() ||
6476                        IsExplicitSpecialization ||
6477                        IsVariableTemplateSpecialization);
6478 
6479   // Check whether the previous declaration is in the same block scope. This
6480   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6481   if (getLangOpts().CPlusPlus &&
6482       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6483     NewVD->setPreviousDeclInSameBlockScope(
6484         Previous.isSingleResult() && !Previous.isShadowed() &&
6485         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6486 
6487   if (!getLangOpts().CPlusPlus) {
6488     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6489   } else {
6490     // If this is an explicit specialization of a static data member, check it.
6491     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6492         CheckMemberSpecialization(NewVD, Previous))
6493       NewVD->setInvalidDecl();
6494 
6495     // Merge the decl with the existing one if appropriate.
6496     if (!Previous.empty()) {
6497       if (Previous.isSingleResult() &&
6498           isa<FieldDecl>(Previous.getFoundDecl()) &&
6499           D.getCXXScopeSpec().isSet()) {
6500         // The user tried to define a non-static data member
6501         // out-of-line (C++ [dcl.meaning]p1).
6502         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6503           << D.getCXXScopeSpec().getRange();
6504         Previous.clear();
6505         NewVD->setInvalidDecl();
6506       }
6507     } else if (D.getCXXScopeSpec().isSet()) {
6508       // No previous declaration in the qualifying scope.
6509       Diag(D.getIdentifierLoc(), diag::err_no_member)
6510         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6511         << D.getCXXScopeSpec().getRange();
6512       NewVD->setInvalidDecl();
6513     }
6514 
6515     if (!IsVariableTemplateSpecialization)
6516       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6517 
6518     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6519     // an explicit specialization (14.8.3) or a partial specialization of a
6520     // concept definition.
6521     if (IsVariableTemplateSpecialization &&
6522         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6523         Previous.isSingleResult()) {
6524       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6525       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6526         if (VarTmpl->isConcept()) {
6527           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6528               << 1                            /*variable*/
6529               << (IsPartialSpecialization ? 2 /*partially specialized*/
6530                                           : 1 /*explicitly specialized*/);
6531           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6532           NewVD->setInvalidDecl();
6533         }
6534       }
6535     }
6536 
6537     if (NewTemplate) {
6538       VarTemplateDecl *PrevVarTemplate =
6539           NewVD->getPreviousDecl()
6540               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6541               : nullptr;
6542 
6543       // Check the template parameter list of this declaration, possibly
6544       // merging in the template parameter list from the previous variable
6545       // template declaration.
6546       if (CheckTemplateParameterList(
6547               TemplateParams,
6548               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6549                               : nullptr,
6550               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6551                DC->isDependentContext())
6552                   ? TPC_ClassTemplateMember
6553                   : TPC_VarTemplate))
6554         NewVD->setInvalidDecl();
6555 
6556       // If we are providing an explicit specialization of a static variable
6557       // template, make a note of that.
6558       if (PrevVarTemplate &&
6559           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6560         PrevVarTemplate->setMemberSpecialization();
6561     }
6562   }
6563 
6564   // Diagnose shadowed variables iff this isn't a redeclaration.
6565   if (ShadowedDecl && !D.isRedeclaration())
6566     CheckShadow(NewVD, ShadowedDecl, Previous);
6567 
6568   ProcessPragmaWeak(S, NewVD);
6569 
6570   // If this is the first declaration of an extern C variable, update
6571   // the map of such variables.
6572   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6573       isIncompleteDeclExternC(*this, NewVD))
6574     RegisterLocallyScopedExternCDecl(NewVD, S);
6575 
6576   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6577     Decl *ManglingContextDecl;
6578     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6579             NewVD->getDeclContext(), ManglingContextDecl)) {
6580       Context.setManglingNumber(
6581           NewVD, MCtx->getManglingNumber(
6582                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6583       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6584     }
6585   }
6586 
6587   // Special handling of variable named 'main'.
6588   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6589       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6590       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6591 
6592     // C++ [basic.start.main]p3
6593     // A program that declares a variable main at global scope is ill-formed.
6594     if (getLangOpts().CPlusPlus)
6595       Diag(D.getLocStart(), diag::err_main_global_variable);
6596 
6597     // In C, and external-linkage variable named main results in undefined
6598     // behavior.
6599     else if (NewVD->hasExternalFormalLinkage())
6600       Diag(D.getLocStart(), diag::warn_main_redefined);
6601   }
6602 
6603   if (D.isRedeclaration() && !Previous.empty()) {
6604     checkDLLAttributeRedeclaration(
6605         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6606         IsExplicitSpecialization, D.isFunctionDefinition());
6607   }
6608 
6609   if (NewTemplate) {
6610     if (NewVD->isInvalidDecl())
6611       NewTemplate->setInvalidDecl();
6612     ActOnDocumentableDecl(NewTemplate);
6613     return NewTemplate;
6614   }
6615 
6616   return NewVD;
6617 }
6618 
6619 /// Enum describing the %select options in diag::warn_decl_shadow.
6620 enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field };
6621 
6622 /// Determine what kind of declaration we're shadowing.
6623 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6624                                                 const DeclContext *OldDC) {
6625   if (isa<RecordDecl>(OldDC))
6626     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6627   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6628 }
6629 
6630 /// Return the location of the capture if the given lambda captures the given
6631 /// variable \p VD, or an invalid source location otherwise.
6632 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6633                                          const VarDecl *VD) {
6634   for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
6635     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6636       return Capture.getLocation();
6637   }
6638   return SourceLocation();
6639 }
6640 
6641 /// \brief Return the declaration shadowed by the given variable \p D, or null
6642 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
6643 NamedDecl *Sema::getShadowedDeclaration(const VarDecl *D,
6644                                         const LookupResult &R) {
6645   // Return if warning is ignored.
6646   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6647     return nullptr;
6648 
6649   // Don't diagnose declarations at file scope.
6650   if (D->hasGlobalStorage())
6651     return nullptr;
6652 
6653   // Only diagnose if we're shadowing an unambiguous field or variable.
6654   if (R.getResultKind() != LookupResult::Found)
6655     return nullptr;
6656 
6657   NamedDecl *ShadowedDecl = R.getFoundDecl();
6658   return isa<VarDecl>(ShadowedDecl) || isa<FieldDecl>(ShadowedDecl)
6659              ? ShadowedDecl
6660              : nullptr;
6661 }
6662 
6663 /// \brief Diagnose variable or built-in function shadowing.  Implements
6664 /// -Wshadow.
6665 ///
6666 /// This method is called whenever a VarDecl is added to a "useful"
6667 /// scope.
6668 ///
6669 /// \param ShadowedDecl the declaration that is shadowed by the given variable
6670 /// \param R the lookup of the name
6671 ///
6672 void Sema::CheckShadow(VarDecl *D, NamedDecl *ShadowedDecl,
6673                        const LookupResult &R) {
6674   DeclContext *NewDC = D->getDeclContext();
6675 
6676   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6677     // Fields are not shadowed by variables in C++ static methods.
6678     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6679       if (MD->isStatic())
6680         return;
6681 
6682     // Fields shadowed by constructor parameters are a special case. Usually
6683     // the constructor initializes the field with the parameter.
6684     if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) {
6685       // Remember that this was shadowed so we can either warn about its
6686       // modification or its existence depending on warning settings.
6687       D = D->getCanonicalDecl();
6688       ShadowingDecls.insert({D, FD});
6689       return;
6690     }
6691   }
6692 
6693   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6694     if (shadowedVar->isExternC()) {
6695       // For shadowing external vars, make sure that we point to the global
6696       // declaration, not a locally scoped extern declaration.
6697       for (auto I : shadowedVar->redecls())
6698         if (I->isFileVarDecl()) {
6699           ShadowedDecl = I;
6700           break;
6701         }
6702     }
6703 
6704   DeclContext *OldDC = ShadowedDecl->getDeclContext();
6705 
6706   unsigned WarningDiag = diag::warn_decl_shadow;
6707   SourceLocation CaptureLoc;
6708   if (isa<VarDecl>(ShadowedDecl) && NewDC && isa<CXXMethodDecl>(NewDC)) {
6709     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
6710       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
6711         if (RD->getLambdaCaptureDefault() == LCD_None) {
6712           // Try to avoid warnings for lambdas with an explicit capture list.
6713           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
6714           // Warn only when the lambda captures the shadowed decl explicitly.
6715           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
6716           if (CaptureLoc.isInvalid())
6717             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
6718         } else {
6719           // Remember that this was shadowed so we can avoid the warning if the
6720           // shadowed decl isn't captured and the warning settings allow it.
6721           cast<LambdaScopeInfo>(getCurFunction())
6722               ->ShadowingDecls.push_back({D, cast<VarDecl>(ShadowedDecl)});
6723           return;
6724         }
6725       }
6726     }
6727   }
6728 
6729   // Only warn about certain kinds of shadowing for class members.
6730   if (NewDC && NewDC->isRecord()) {
6731     // In particular, don't warn about shadowing non-class members.
6732     if (!OldDC->isRecord())
6733       return;
6734 
6735     // TODO: should we warn about static data members shadowing
6736     // static data members from base classes?
6737 
6738     // TODO: don't diagnose for inaccessible shadowed members.
6739     // This is hard to do perfectly because we might friend the
6740     // shadowing context, but that's just a false negative.
6741   }
6742 
6743 
6744   DeclarationName Name = R.getLookupName();
6745 
6746   // Emit warning and note.
6747   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6748     return;
6749   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
6750   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
6751   if (!CaptureLoc.isInvalid())
6752     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
6753         << Name << /*explicitly*/ 1;
6754   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6755 }
6756 
6757 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
6758 /// when these variables are captured by the lambda.
6759 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
6760   for (const auto &Shadow : LSI->ShadowingDecls) {
6761     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
6762     // Try to avoid the warning when the shadowed decl isn't captured.
6763     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
6764     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6765     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
6766                                        ? diag::warn_decl_shadow_uncaptured_local
6767                                        : diag::warn_decl_shadow)
6768         << Shadow.VD->getDeclName()
6769         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
6770     if (!CaptureLoc.isInvalid())
6771       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
6772           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
6773     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6774   }
6775 }
6776 
6777 /// \brief Check -Wshadow without the advantage of a previous lookup.
6778 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6779   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6780     return;
6781 
6782   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6783                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6784   LookupName(R, S);
6785   if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
6786     CheckShadow(D, ShadowedDecl, R);
6787 }
6788 
6789 /// Check if 'E', which is an expression that is about to be modified, refers
6790 /// to a constructor parameter that shadows a field.
6791 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
6792   // Quickly ignore expressions that can't be shadowing ctor parameters.
6793   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
6794     return;
6795   E = E->IgnoreParenImpCasts();
6796   auto *DRE = dyn_cast<DeclRefExpr>(E);
6797   if (!DRE)
6798     return;
6799   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
6800   auto I = ShadowingDecls.find(D);
6801   if (I == ShadowingDecls.end())
6802     return;
6803   const NamedDecl *ShadowedDecl = I->second;
6804   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6805   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
6806   Diag(D->getLocation(), diag::note_var_declared_here) << D;
6807   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6808 
6809   // Avoid issuing multiple warnings about the same decl.
6810   ShadowingDecls.erase(I);
6811 }
6812 
6813 /// Check for conflict between this global or extern "C" declaration and
6814 /// previous global or extern "C" declarations. This is only used in C++.
6815 template<typename T>
6816 static bool checkGlobalOrExternCConflict(
6817     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6818   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6819   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6820 
6821   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6822     // The common case: this global doesn't conflict with any extern "C"
6823     // declaration.
6824     return false;
6825   }
6826 
6827   if (Prev) {
6828     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6829       // Both the old and new declarations have C language linkage. This is a
6830       // redeclaration.
6831       Previous.clear();
6832       Previous.addDecl(Prev);
6833       return true;
6834     }
6835 
6836     // This is a global, non-extern "C" declaration, and there is a previous
6837     // non-global extern "C" declaration. Diagnose if this is a variable
6838     // declaration.
6839     if (!isa<VarDecl>(ND))
6840       return false;
6841   } else {
6842     // The declaration is extern "C". Check for any declaration in the
6843     // translation unit which might conflict.
6844     if (IsGlobal) {
6845       // We have already performed the lookup into the translation unit.
6846       IsGlobal = false;
6847       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6848            I != E; ++I) {
6849         if (isa<VarDecl>(*I)) {
6850           Prev = *I;
6851           break;
6852         }
6853       }
6854     } else {
6855       DeclContext::lookup_result R =
6856           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6857       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6858            I != E; ++I) {
6859         if (isa<VarDecl>(*I)) {
6860           Prev = *I;
6861           break;
6862         }
6863         // FIXME: If we have any other entity with this name in global scope,
6864         // the declaration is ill-formed, but that is a defect: it breaks the
6865         // 'stat' hack, for instance. Only variables can have mangled name
6866         // clashes with extern "C" declarations, so only they deserve a
6867         // diagnostic.
6868       }
6869     }
6870 
6871     if (!Prev)
6872       return false;
6873   }
6874 
6875   // Use the first declaration's location to ensure we point at something which
6876   // is lexically inside an extern "C" linkage-spec.
6877   assert(Prev && "should have found a previous declaration to diagnose");
6878   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6879     Prev = FD->getFirstDecl();
6880   else
6881     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6882 
6883   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6884     << IsGlobal << ND;
6885   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6886     << IsGlobal;
6887   return false;
6888 }
6889 
6890 /// Apply special rules for handling extern "C" declarations. Returns \c true
6891 /// if we have found that this is a redeclaration of some prior entity.
6892 ///
6893 /// Per C++ [dcl.link]p6:
6894 ///   Two declarations [for a function or variable] with C language linkage
6895 ///   with the same name that appear in different scopes refer to the same
6896 ///   [entity]. An entity with C language linkage shall not be declared with
6897 ///   the same name as an entity in global scope.
6898 template<typename T>
6899 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6900                                                   LookupResult &Previous) {
6901   if (!S.getLangOpts().CPlusPlus) {
6902     // In C, when declaring a global variable, look for a corresponding 'extern'
6903     // variable declared in function scope. We don't need this in C++, because
6904     // we find local extern decls in the surrounding file-scope DeclContext.
6905     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6906       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6907         Previous.clear();
6908         Previous.addDecl(Prev);
6909         return true;
6910       }
6911     }
6912     return false;
6913   }
6914 
6915   // A declaration in the translation unit can conflict with an extern "C"
6916   // declaration.
6917   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6918     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6919 
6920   // An extern "C" declaration can conflict with a declaration in the
6921   // translation unit or can be a redeclaration of an extern "C" declaration
6922   // in another scope.
6923   if (isIncompleteDeclExternC(S,ND))
6924     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6925 
6926   // Neither global nor extern "C": nothing to do.
6927   return false;
6928 }
6929 
6930 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6931   // If the decl is already known invalid, don't check it.
6932   if (NewVD->isInvalidDecl())
6933     return;
6934 
6935   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6936   QualType T = TInfo->getType();
6937 
6938   // Defer checking an 'auto' type until its initializer is attached.
6939   if (T->isUndeducedType())
6940     return;
6941 
6942   if (NewVD->hasAttrs())
6943     CheckAlignasUnderalignment(NewVD);
6944 
6945   if (T->isObjCObjectType()) {
6946     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6947       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6948     T = Context.getObjCObjectPointerType(T);
6949     NewVD->setType(T);
6950   }
6951 
6952   // Emit an error if an address space was applied to decl with local storage.
6953   // This includes arrays of objects with address space qualifiers, but not
6954   // automatic variables that point to other address spaces.
6955   // ISO/IEC TR 18037 S5.1.2
6956   if (!getLangOpts().OpenCL
6957       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6958     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6959     NewVD->setInvalidDecl();
6960     return;
6961   }
6962 
6963   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
6964   // scope.
6965   if (getLangOpts().OpenCLVersion == 120 &&
6966       !getOpenCLOptions().isEnabled("cl_clang_storage_class_specifiers") &&
6967       NewVD->isStaticLocal()) {
6968     Diag(NewVD->getLocation(), diag::err_static_function_scope);
6969     NewVD->setInvalidDecl();
6970     return;
6971   }
6972 
6973   if (getLangOpts().OpenCL) {
6974     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
6975     if (NewVD->hasAttr<BlocksAttr>()) {
6976       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
6977       return;
6978     }
6979 
6980     if (T->isBlockPointerType()) {
6981       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
6982       // can't use 'extern' storage class.
6983       if (!T.isConstQualified()) {
6984         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
6985             << 0 /*const*/;
6986         NewVD->setInvalidDecl();
6987         return;
6988       }
6989       if (NewVD->hasExternalStorage()) {
6990         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
6991         NewVD->setInvalidDecl();
6992         return;
6993       }
6994     }
6995     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6996     // __constant address space.
6997     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6998     // variables inside a function can also be declared in the global
6999     // address space.
7000     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
7001         NewVD->hasExternalStorage()) {
7002       if (!T->isSamplerT() &&
7003           !(T.getAddressSpace() == LangAS::opencl_constant ||
7004             (T.getAddressSpace() == LangAS::opencl_global &&
7005              getLangOpts().OpenCLVersion == 200))) {
7006         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
7007         if (getLangOpts().OpenCLVersion == 200)
7008           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7009               << Scope << "global or constant";
7010         else
7011           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
7012               << Scope << "constant";
7013         NewVD->setInvalidDecl();
7014         return;
7015       }
7016     } else {
7017       if (T.getAddressSpace() == LangAS::opencl_global) {
7018         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7019             << 1 /*is any function*/ << "global";
7020         NewVD->setInvalidDecl();
7021         return;
7022       }
7023       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
7024       // in functions.
7025       if (T.getAddressSpace() == LangAS::opencl_constant ||
7026           T.getAddressSpace() == LangAS::opencl_local) {
7027         FunctionDecl *FD = getCurFunctionDecl();
7028         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
7029           if (T.getAddressSpace() == LangAS::opencl_constant)
7030             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7031                 << 0 /*non-kernel only*/ << "constant";
7032           else
7033             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
7034                 << 0 /*non-kernel only*/ << "local";
7035           NewVD->setInvalidDecl();
7036           return;
7037         }
7038       }
7039     }
7040   }
7041 
7042   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
7043       && !NewVD->hasAttr<BlocksAttr>()) {
7044     if (getLangOpts().getGC() != LangOptions::NonGC)
7045       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
7046     else {
7047       assert(!getLangOpts().ObjCAutoRefCount);
7048       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
7049     }
7050   }
7051 
7052   bool isVM = T->isVariablyModifiedType();
7053   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7054       NewVD->hasAttr<BlocksAttr>())
7055     getCurFunction()->setHasBranchProtectedScope();
7056 
7057   if ((isVM && NewVD->hasLinkage()) ||
7058       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7059     bool SizeIsNegative;
7060     llvm::APSInt Oversized;
7061     TypeSourceInfo *FixedTInfo =
7062       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7063                                                     SizeIsNegative, Oversized);
7064     if (!FixedTInfo && T->isVariableArrayType()) {
7065       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7066       // FIXME: This won't give the correct result for
7067       // int a[10][n];
7068       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7069 
7070       if (NewVD->isFileVarDecl())
7071         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7072         << SizeRange;
7073       else if (NewVD->isStaticLocal())
7074         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7075         << SizeRange;
7076       else
7077         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7078         << SizeRange;
7079       NewVD->setInvalidDecl();
7080       return;
7081     }
7082 
7083     if (!FixedTInfo) {
7084       if (NewVD->isFileVarDecl())
7085         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7086       else
7087         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7088       NewVD->setInvalidDecl();
7089       return;
7090     }
7091 
7092     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7093     NewVD->setType(FixedTInfo->getType());
7094     NewVD->setTypeSourceInfo(FixedTInfo);
7095   }
7096 
7097   if (T->isVoidType()) {
7098     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7099     //                    of objects and functions.
7100     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7101       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7102         << T;
7103       NewVD->setInvalidDecl();
7104       return;
7105     }
7106   }
7107 
7108   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7109     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7110     NewVD->setInvalidDecl();
7111     return;
7112   }
7113 
7114   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7115     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7116     NewVD->setInvalidDecl();
7117     return;
7118   }
7119 
7120   if (NewVD->isConstexpr() && !T->isDependentType() &&
7121       RequireLiteralType(NewVD->getLocation(), T,
7122                          diag::err_constexpr_var_non_literal)) {
7123     NewVD->setInvalidDecl();
7124     return;
7125   }
7126 }
7127 
7128 /// \brief Perform semantic checking on a newly-created variable
7129 /// declaration.
7130 ///
7131 /// This routine performs all of the type-checking required for a
7132 /// variable declaration once it has been built. It is used both to
7133 /// check variables after they have been parsed and their declarators
7134 /// have been translated into a declaration, and to check variables
7135 /// that have been instantiated from a template.
7136 ///
7137 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7138 ///
7139 /// Returns true if the variable declaration is a redeclaration.
7140 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7141   CheckVariableDeclarationType(NewVD);
7142 
7143   // If the decl is already known invalid, don't check it.
7144   if (NewVD->isInvalidDecl())
7145     return false;
7146 
7147   // If we did not find anything by this name, look for a non-visible
7148   // extern "C" declaration with the same name.
7149   if (Previous.empty() &&
7150       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7151     Previous.setShadowed();
7152 
7153   if (!Previous.empty()) {
7154     MergeVarDecl(NewVD, Previous);
7155     return true;
7156   }
7157   return false;
7158 }
7159 
7160 namespace {
7161 struct FindOverriddenMethod {
7162   Sema *S;
7163   CXXMethodDecl *Method;
7164 
7165   /// Member lookup function that determines whether a given C++
7166   /// method overrides a method in a base class, to be used with
7167   /// CXXRecordDecl::lookupInBases().
7168   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7169     RecordDecl *BaseRecord =
7170         Specifier->getType()->getAs<RecordType>()->getDecl();
7171 
7172     DeclarationName Name = Method->getDeclName();
7173 
7174     // FIXME: Do we care about other names here too?
7175     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7176       // We really want to find the base class destructor here.
7177       QualType T = S->Context.getTypeDeclType(BaseRecord);
7178       CanQualType CT = S->Context.getCanonicalType(T);
7179 
7180       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7181     }
7182 
7183     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7184          Path.Decls = Path.Decls.slice(1)) {
7185       NamedDecl *D = Path.Decls.front();
7186       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7187         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7188           return true;
7189       }
7190     }
7191 
7192     return false;
7193   }
7194 };
7195 
7196 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7197 } // end anonymous namespace
7198 
7199 /// \brief Report an error regarding overriding, along with any relevant
7200 /// overriden methods.
7201 ///
7202 /// \param DiagID the primary error to report.
7203 /// \param MD the overriding method.
7204 /// \param OEK which overrides to include as notes.
7205 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7206                             OverrideErrorKind OEK = OEK_All) {
7207   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7208   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7209                                       E = MD->end_overridden_methods();
7210        I != E; ++I) {
7211     // This check (& the OEK parameter) could be replaced by a predicate, but
7212     // without lambdas that would be overkill. This is still nicer than writing
7213     // out the diag loop 3 times.
7214     if ((OEK == OEK_All) ||
7215         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7216         (OEK == OEK_Deleted && (*I)->isDeleted()))
7217       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7218   }
7219 }
7220 
7221 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7222 /// and if so, check that it's a valid override and remember it.
7223 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7224   // Look for methods in base classes that this method might override.
7225   CXXBasePaths Paths;
7226   FindOverriddenMethod FOM;
7227   FOM.Method = MD;
7228   FOM.S = this;
7229   bool hasDeletedOverridenMethods = false;
7230   bool hasNonDeletedOverridenMethods = false;
7231   bool AddedAny = false;
7232   if (DC->lookupInBases(FOM, Paths)) {
7233     for (auto *I : Paths.found_decls()) {
7234       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7235         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7236         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7237             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7238             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7239             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7240           hasDeletedOverridenMethods |= OldMD->isDeleted();
7241           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7242           AddedAny = true;
7243         }
7244       }
7245     }
7246   }
7247 
7248   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7249     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7250   }
7251   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7252     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7253   }
7254 
7255   return AddedAny;
7256 }
7257 
7258 namespace {
7259   // Struct for holding all of the extra arguments needed by
7260   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7261   struct ActOnFDArgs {
7262     Scope *S;
7263     Declarator &D;
7264     MultiTemplateParamsArg TemplateParamLists;
7265     bool AddToScope;
7266   };
7267 } // end anonymous namespace
7268 
7269 namespace {
7270 
7271 // Callback to only accept typo corrections that have a non-zero edit distance.
7272 // Also only accept corrections that have the same parent decl.
7273 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7274  public:
7275   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7276                             CXXRecordDecl *Parent)
7277       : Context(Context), OriginalFD(TypoFD),
7278         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7279 
7280   bool ValidateCandidate(const TypoCorrection &candidate) override {
7281     if (candidate.getEditDistance() == 0)
7282       return false;
7283 
7284     SmallVector<unsigned, 1> MismatchedParams;
7285     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7286                                           CDeclEnd = candidate.end();
7287          CDecl != CDeclEnd; ++CDecl) {
7288       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7289 
7290       if (FD && !FD->hasBody() &&
7291           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7292         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7293           CXXRecordDecl *Parent = MD->getParent();
7294           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7295             return true;
7296         } else if (!ExpectedParent) {
7297           return true;
7298         }
7299       }
7300     }
7301 
7302     return false;
7303   }
7304 
7305  private:
7306   ASTContext &Context;
7307   FunctionDecl *OriginalFD;
7308   CXXRecordDecl *ExpectedParent;
7309 };
7310 
7311 } // end anonymous namespace
7312 
7313 /// \brief Generate diagnostics for an invalid function redeclaration.
7314 ///
7315 /// This routine handles generating the diagnostic messages for an invalid
7316 /// function redeclaration, including finding possible similar declarations
7317 /// or performing typo correction if there are no previous declarations with
7318 /// the same name.
7319 ///
7320 /// Returns a NamedDecl iff typo correction was performed and substituting in
7321 /// the new declaration name does not cause new errors.
7322 static NamedDecl *DiagnoseInvalidRedeclaration(
7323     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7324     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7325   DeclarationName Name = NewFD->getDeclName();
7326   DeclContext *NewDC = NewFD->getDeclContext();
7327   SmallVector<unsigned, 1> MismatchedParams;
7328   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7329   TypoCorrection Correction;
7330   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7331   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7332                                    : diag::err_member_decl_does_not_match;
7333   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7334                     IsLocalFriend ? Sema::LookupLocalFriendName
7335                                   : Sema::LookupOrdinaryName,
7336                     Sema::ForRedeclaration);
7337 
7338   NewFD->setInvalidDecl();
7339   if (IsLocalFriend)
7340     SemaRef.LookupName(Prev, S);
7341   else
7342     SemaRef.LookupQualifiedName(Prev, NewDC);
7343   assert(!Prev.isAmbiguous() &&
7344          "Cannot have an ambiguity in previous-declaration lookup");
7345   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7346   if (!Prev.empty()) {
7347     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7348          Func != FuncEnd; ++Func) {
7349       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7350       if (FD &&
7351           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7352         // Add 1 to the index so that 0 can mean the mismatch didn't
7353         // involve a parameter
7354         unsigned ParamNum =
7355             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7356         NearMatches.push_back(std::make_pair(FD, ParamNum));
7357       }
7358     }
7359   // If the qualified name lookup yielded nothing, try typo correction
7360   } else if ((Correction = SemaRef.CorrectTypo(
7361                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7362                   &ExtraArgs.D.getCXXScopeSpec(),
7363                   llvm::make_unique<DifferentNameValidatorCCC>(
7364                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7365                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7366     // Set up everything for the call to ActOnFunctionDeclarator
7367     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7368                               ExtraArgs.D.getIdentifierLoc());
7369     Previous.clear();
7370     Previous.setLookupName(Correction.getCorrection());
7371     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7372                                     CDeclEnd = Correction.end();
7373          CDecl != CDeclEnd; ++CDecl) {
7374       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7375       if (FD && !FD->hasBody() &&
7376           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7377         Previous.addDecl(FD);
7378       }
7379     }
7380     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7381 
7382     NamedDecl *Result;
7383     // Retry building the function declaration with the new previous
7384     // declarations, and with errors suppressed.
7385     {
7386       // Trap errors.
7387       Sema::SFINAETrap Trap(SemaRef);
7388 
7389       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7390       // pieces need to verify the typo-corrected C++ declaration and hopefully
7391       // eliminate the need for the parameter pack ExtraArgs.
7392       Result = SemaRef.ActOnFunctionDeclarator(
7393           ExtraArgs.S, ExtraArgs.D,
7394           Correction.getCorrectionDecl()->getDeclContext(),
7395           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7396           ExtraArgs.AddToScope);
7397 
7398       if (Trap.hasErrorOccurred())
7399         Result = nullptr;
7400     }
7401 
7402     if (Result) {
7403       // Determine which correction we picked.
7404       Decl *Canonical = Result->getCanonicalDecl();
7405       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7406            I != E; ++I)
7407         if ((*I)->getCanonicalDecl() == Canonical)
7408           Correction.setCorrectionDecl(*I);
7409 
7410       SemaRef.diagnoseTypo(
7411           Correction,
7412           SemaRef.PDiag(IsLocalFriend
7413                           ? diag::err_no_matching_local_friend_suggest
7414                           : diag::err_member_decl_does_not_match_suggest)
7415             << Name << NewDC << IsDefinition);
7416       return Result;
7417     }
7418 
7419     // Pretend the typo correction never occurred
7420     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7421                               ExtraArgs.D.getIdentifierLoc());
7422     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7423     Previous.clear();
7424     Previous.setLookupName(Name);
7425   }
7426 
7427   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7428       << Name << NewDC << IsDefinition << NewFD->getLocation();
7429 
7430   bool NewFDisConst = false;
7431   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7432     NewFDisConst = NewMD->isConst();
7433 
7434   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7435        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7436        NearMatch != NearMatchEnd; ++NearMatch) {
7437     FunctionDecl *FD = NearMatch->first;
7438     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7439     bool FDisConst = MD && MD->isConst();
7440     bool IsMember = MD || !IsLocalFriend;
7441 
7442     // FIXME: These notes are poorly worded for the local friend case.
7443     if (unsigned Idx = NearMatch->second) {
7444       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7445       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7446       if (Loc.isInvalid()) Loc = FD->getLocation();
7447       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7448                                  : diag::note_local_decl_close_param_match)
7449         << Idx << FDParam->getType()
7450         << NewFD->getParamDecl(Idx - 1)->getType();
7451     } else if (FDisConst != NewFDisConst) {
7452       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7453           << NewFDisConst << FD->getSourceRange().getEnd();
7454     } else
7455       SemaRef.Diag(FD->getLocation(),
7456                    IsMember ? diag::note_member_def_close_match
7457                             : diag::note_local_decl_close_match);
7458   }
7459   return nullptr;
7460 }
7461 
7462 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7463   switch (D.getDeclSpec().getStorageClassSpec()) {
7464   default: llvm_unreachable("Unknown storage class!");
7465   case DeclSpec::SCS_auto:
7466   case DeclSpec::SCS_register:
7467   case DeclSpec::SCS_mutable:
7468     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7469                  diag::err_typecheck_sclass_func);
7470     D.setInvalidType();
7471     break;
7472   case DeclSpec::SCS_unspecified: break;
7473   case DeclSpec::SCS_extern:
7474     if (D.getDeclSpec().isExternInLinkageSpec())
7475       return SC_None;
7476     return SC_Extern;
7477   case DeclSpec::SCS_static: {
7478     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7479       // C99 6.7.1p5:
7480       //   The declaration of an identifier for a function that has
7481       //   block scope shall have no explicit storage-class specifier
7482       //   other than extern
7483       // See also (C++ [dcl.stc]p4).
7484       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7485                    diag::err_static_block_func);
7486       break;
7487     } else
7488       return SC_Static;
7489   }
7490   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7491   }
7492 
7493   // No explicit storage class has already been returned
7494   return SC_None;
7495 }
7496 
7497 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7498                                            DeclContext *DC, QualType &R,
7499                                            TypeSourceInfo *TInfo,
7500                                            StorageClass SC,
7501                                            bool &IsVirtualOkay) {
7502   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7503   DeclarationName Name = NameInfo.getName();
7504 
7505   FunctionDecl *NewFD = nullptr;
7506   bool isInline = D.getDeclSpec().isInlineSpecified();
7507 
7508   if (!SemaRef.getLangOpts().CPlusPlus) {
7509     // Determine whether the function was written with a
7510     // prototype. This true when:
7511     //   - there is a prototype in the declarator, or
7512     //   - the type R of the function is some kind of typedef or other reference
7513     //     to a type name (which eventually refers to a function type).
7514     bool HasPrototype =
7515       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7516       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
7517 
7518     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7519                                  D.getLocStart(), NameInfo, R,
7520                                  TInfo, SC, isInline,
7521                                  HasPrototype, false);
7522     if (D.isInvalidType())
7523       NewFD->setInvalidDecl();
7524 
7525     return NewFD;
7526   }
7527 
7528   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7529   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7530 
7531   // Check that the return type is not an abstract class type.
7532   // For record types, this is done by the AbstractClassUsageDiagnoser once
7533   // the class has been completely parsed.
7534   if (!DC->isRecord() &&
7535       SemaRef.RequireNonAbstractType(
7536           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7537           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7538     D.setInvalidType();
7539 
7540   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7541     // This is a C++ constructor declaration.
7542     assert(DC->isRecord() &&
7543            "Constructors can only be declared in a member context");
7544 
7545     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7546     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7547                                       D.getLocStart(), NameInfo,
7548                                       R, TInfo, isExplicit, isInline,
7549                                       /*isImplicitlyDeclared=*/false,
7550                                       isConstexpr);
7551 
7552   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7553     // This is a C++ destructor declaration.
7554     if (DC->isRecord()) {
7555       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7556       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7557       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7558                                         SemaRef.Context, Record,
7559                                         D.getLocStart(),
7560                                         NameInfo, R, TInfo, isInline,
7561                                         /*isImplicitlyDeclared=*/false);
7562 
7563       // If the class is complete, then we now create the implicit exception
7564       // specification. If the class is incomplete or dependent, we can't do
7565       // it yet.
7566       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7567           Record->getDefinition() && !Record->isBeingDefined() &&
7568           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7569         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7570       }
7571 
7572       IsVirtualOkay = true;
7573       return NewDD;
7574 
7575     } else {
7576       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7577       D.setInvalidType();
7578 
7579       // Create a FunctionDecl to satisfy the function definition parsing
7580       // code path.
7581       return FunctionDecl::Create(SemaRef.Context, DC,
7582                                   D.getLocStart(),
7583                                   D.getIdentifierLoc(), Name, R, TInfo,
7584                                   SC, isInline,
7585                                   /*hasPrototype=*/true, isConstexpr);
7586     }
7587 
7588   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7589     if (!DC->isRecord()) {
7590       SemaRef.Diag(D.getIdentifierLoc(),
7591            diag::err_conv_function_not_member);
7592       return nullptr;
7593     }
7594 
7595     SemaRef.CheckConversionDeclarator(D, R, SC);
7596     IsVirtualOkay = true;
7597     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7598                                      D.getLocStart(), NameInfo,
7599                                      R, TInfo, isInline, isExplicit,
7600                                      isConstexpr, SourceLocation());
7601 
7602   } else if (DC->isRecord()) {
7603     // If the name of the function is the same as the name of the record,
7604     // then this must be an invalid constructor that has a return type.
7605     // (The parser checks for a return type and makes the declarator a
7606     // constructor if it has no return type).
7607     if (Name.getAsIdentifierInfo() &&
7608         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7609       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7610         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7611         << SourceRange(D.getIdentifierLoc());
7612       return nullptr;
7613     }
7614 
7615     // This is a C++ method declaration.
7616     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7617                                                cast<CXXRecordDecl>(DC),
7618                                                D.getLocStart(), NameInfo, R,
7619                                                TInfo, SC, isInline,
7620                                                isConstexpr, SourceLocation());
7621     IsVirtualOkay = !Ret->isStatic();
7622     return Ret;
7623   } else {
7624     bool isFriend =
7625         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7626     if (!isFriend && SemaRef.CurContext->isRecord())
7627       return nullptr;
7628 
7629     // Determine whether the function was written with a
7630     // prototype. This true when:
7631     //   - we're in C++ (where every function has a prototype),
7632     return FunctionDecl::Create(SemaRef.Context, DC,
7633                                 D.getLocStart(),
7634                                 NameInfo, R, TInfo, SC, isInline,
7635                                 true/*HasPrototype*/, isConstexpr);
7636   }
7637 }
7638 
7639 enum OpenCLParamType {
7640   ValidKernelParam,
7641   PtrPtrKernelParam,
7642   PtrKernelParam,
7643   InvalidAddrSpacePtrKernelParam,
7644   InvalidKernelParam,
7645   RecordKernelParam
7646 };
7647 
7648 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
7649   if (PT->isPointerType()) {
7650     QualType PointeeType = PT->getPointeeType();
7651     if (PointeeType->isPointerType())
7652       return PtrPtrKernelParam;
7653     if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
7654         PointeeType.getAddressSpace() == 0)
7655       return InvalidAddrSpacePtrKernelParam;
7656     return PtrKernelParam;
7657   }
7658 
7659   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7660   // be used as builtin types.
7661 
7662   if (PT->isImageType())
7663     return PtrKernelParam;
7664 
7665   if (PT->isBooleanType())
7666     return InvalidKernelParam;
7667 
7668   if (PT->isEventT())
7669     return InvalidKernelParam;
7670 
7671   // OpenCL extension spec v1.2 s9.5:
7672   // This extension adds support for half scalar and vector types as built-in
7673   // types that can be used for arithmetic operations, conversions etc.
7674   if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16") && PT->isHalfType())
7675     return InvalidKernelParam;
7676 
7677   if (PT->isRecordType())
7678     return RecordKernelParam;
7679 
7680   return ValidKernelParam;
7681 }
7682 
7683 static void checkIsValidOpenCLKernelParameter(
7684   Sema &S,
7685   Declarator &D,
7686   ParmVarDecl *Param,
7687   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7688   QualType PT = Param->getType();
7689 
7690   // Cache the valid types we encounter to avoid rechecking structs that are
7691   // used again
7692   if (ValidTypes.count(PT.getTypePtr()))
7693     return;
7694 
7695   switch (getOpenCLKernelParameterType(S, PT)) {
7696   case PtrPtrKernelParam:
7697     // OpenCL v1.2 s6.9.a:
7698     // A kernel function argument cannot be declared as a
7699     // pointer to a pointer type.
7700     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7701     D.setInvalidType();
7702     return;
7703 
7704   case InvalidAddrSpacePtrKernelParam:
7705     // OpenCL v1.0 s6.5:
7706     // __kernel function arguments declared to be a pointer of a type can point
7707     // to one of the following address spaces only : __global, __local or
7708     // __constant.
7709     S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
7710     D.setInvalidType();
7711     return;
7712 
7713     // OpenCL v1.2 s6.9.k:
7714     // Arguments to kernel functions in a program cannot be declared with the
7715     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7716     // uintptr_t or a struct and/or union that contain fields declared to be
7717     // one of these built-in scalar types.
7718 
7719   case InvalidKernelParam:
7720     // OpenCL v1.2 s6.8 n:
7721     // A kernel function argument cannot be declared
7722     // of event_t type.
7723     // Do not diagnose half type since it is diagnosed as invalid argument
7724     // type for any function elsewhere.
7725     if (!PT->isHalfType())
7726       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7727     D.setInvalidType();
7728     return;
7729 
7730   case PtrKernelParam:
7731   case ValidKernelParam:
7732     ValidTypes.insert(PT.getTypePtr());
7733     return;
7734 
7735   case RecordKernelParam:
7736     break;
7737   }
7738 
7739   // Track nested structs we will inspect
7740   SmallVector<const Decl *, 4> VisitStack;
7741 
7742   // Track where we are in the nested structs. Items will migrate from
7743   // VisitStack to HistoryStack as we do the DFS for bad field.
7744   SmallVector<const FieldDecl *, 4> HistoryStack;
7745   HistoryStack.push_back(nullptr);
7746 
7747   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7748   VisitStack.push_back(PD);
7749 
7750   assert(VisitStack.back() && "First decl null?");
7751 
7752   do {
7753     const Decl *Next = VisitStack.pop_back_val();
7754     if (!Next) {
7755       assert(!HistoryStack.empty());
7756       // Found a marker, we have gone up a level
7757       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7758         ValidTypes.insert(Hist->getType().getTypePtr());
7759 
7760       continue;
7761     }
7762 
7763     // Adds everything except the original parameter declaration (which is not a
7764     // field itself) to the history stack.
7765     const RecordDecl *RD;
7766     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7767       HistoryStack.push_back(Field);
7768       RD = Field->getType()->castAs<RecordType>()->getDecl();
7769     } else {
7770       RD = cast<RecordDecl>(Next);
7771     }
7772 
7773     // Add a null marker so we know when we've gone back up a level
7774     VisitStack.push_back(nullptr);
7775 
7776     for (const auto *FD : RD->fields()) {
7777       QualType QT = FD->getType();
7778 
7779       if (ValidTypes.count(QT.getTypePtr()))
7780         continue;
7781 
7782       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
7783       if (ParamType == ValidKernelParam)
7784         continue;
7785 
7786       if (ParamType == RecordKernelParam) {
7787         VisitStack.push_back(FD);
7788         continue;
7789       }
7790 
7791       // OpenCL v1.2 s6.9.p:
7792       // Arguments to kernel functions that are declared to be a struct or union
7793       // do not allow OpenCL objects to be passed as elements of the struct or
7794       // union.
7795       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7796           ParamType == InvalidAddrSpacePtrKernelParam) {
7797         S.Diag(Param->getLocation(),
7798                diag::err_record_with_pointers_kernel_param)
7799           << PT->isUnionType()
7800           << PT;
7801       } else {
7802         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7803       }
7804 
7805       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7806         << PD->getDeclName();
7807 
7808       // We have an error, now let's go back up through history and show where
7809       // the offending field came from
7810       for (ArrayRef<const FieldDecl *>::const_iterator
7811                I = HistoryStack.begin() + 1,
7812                E = HistoryStack.end();
7813            I != E; ++I) {
7814         const FieldDecl *OuterField = *I;
7815         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7816           << OuterField->getType();
7817       }
7818 
7819       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7820         << QT->isPointerType()
7821         << QT;
7822       D.setInvalidType();
7823       return;
7824     }
7825   } while (!VisitStack.empty());
7826 }
7827 
7828 /// Find the DeclContext in which a tag is implicitly declared if we see an
7829 /// elaborated type specifier in the specified context, and lookup finds
7830 /// nothing.
7831 static DeclContext *getTagInjectionContext(DeclContext *DC) {
7832   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
7833     DC = DC->getParent();
7834   return DC;
7835 }
7836 
7837 /// Find the Scope in which a tag is implicitly declared if we see an
7838 /// elaborated type specifier in the specified context, and lookup finds
7839 /// nothing.
7840 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
7841   while (S->isClassScope() ||
7842          (LangOpts.CPlusPlus &&
7843           S->isFunctionPrototypeScope()) ||
7844          ((S->getFlags() & Scope::DeclScope) == 0) ||
7845          (S->getEntity() && S->getEntity()->isTransparentContext()))
7846     S = S->getParent();
7847   return S;
7848 }
7849 
7850 NamedDecl*
7851 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7852                               TypeSourceInfo *TInfo, LookupResult &Previous,
7853                               MultiTemplateParamsArg TemplateParamLists,
7854                               bool &AddToScope) {
7855   QualType R = TInfo->getType();
7856 
7857   assert(R.getTypePtr()->isFunctionType());
7858 
7859   // TODO: consider using NameInfo for diagnostic.
7860   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7861   DeclarationName Name = NameInfo.getName();
7862   StorageClass SC = getFunctionStorageClass(*this, D);
7863 
7864   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7865     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7866          diag::err_invalid_thread)
7867       << DeclSpec::getSpecifierName(TSCS);
7868 
7869   if (D.isFirstDeclarationOfMember())
7870     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7871                            D.getIdentifierLoc());
7872 
7873   bool isFriend = false;
7874   FunctionTemplateDecl *FunctionTemplate = nullptr;
7875   bool isExplicitSpecialization = false;
7876   bool isFunctionTemplateSpecialization = false;
7877 
7878   bool isDependentClassScopeExplicitSpecialization = false;
7879   bool HasExplicitTemplateArgs = false;
7880   TemplateArgumentListInfo TemplateArgs;
7881 
7882   bool isVirtualOkay = false;
7883 
7884   DeclContext *OriginalDC = DC;
7885   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7886 
7887   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7888                                               isVirtualOkay);
7889   if (!NewFD) return nullptr;
7890 
7891   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7892     NewFD->setTopLevelDeclInObjCContainer();
7893 
7894   // Set the lexical context. If this is a function-scope declaration, or has a
7895   // C++ scope specifier, or is the object of a friend declaration, the lexical
7896   // context will be different from the semantic context.
7897   NewFD->setLexicalDeclContext(CurContext);
7898 
7899   if (IsLocalExternDecl)
7900     NewFD->setLocalExternDecl();
7901 
7902   if (getLangOpts().CPlusPlus) {
7903     bool isInline = D.getDeclSpec().isInlineSpecified();
7904     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7905     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7906     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7907     bool isConcept = D.getDeclSpec().isConceptSpecified();
7908     isFriend = D.getDeclSpec().isFriendSpecified();
7909     if (isFriend && !isInline && D.isFunctionDefinition()) {
7910       // C++ [class.friend]p5
7911       //   A function can be defined in a friend declaration of a
7912       //   class . . . . Such a function is implicitly inline.
7913       NewFD->setImplicitlyInline();
7914     }
7915 
7916     // If this is a method defined in an __interface, and is not a constructor
7917     // or an overloaded operator, then set the pure flag (isVirtual will already
7918     // return true).
7919     if (const CXXRecordDecl *Parent =
7920           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7921       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7922         NewFD->setPure(true);
7923 
7924       // C++ [class.union]p2
7925       //   A union can have member functions, but not virtual functions.
7926       if (isVirtual && Parent->isUnion())
7927         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7928     }
7929 
7930     SetNestedNameSpecifier(NewFD, D);
7931     isExplicitSpecialization = false;
7932     isFunctionTemplateSpecialization = false;
7933     if (D.isInvalidType())
7934       NewFD->setInvalidDecl();
7935 
7936     // Match up the template parameter lists with the scope specifier, then
7937     // determine whether we have a template or a template specialization.
7938     bool Invalid = false;
7939     if (TemplateParameterList *TemplateParams =
7940             MatchTemplateParametersToScopeSpecifier(
7941                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7942                 D.getCXXScopeSpec(),
7943                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7944                     ? D.getName().TemplateId
7945                     : nullptr,
7946                 TemplateParamLists, isFriend, isExplicitSpecialization,
7947                 Invalid)) {
7948       if (TemplateParams->size() > 0) {
7949         // This is a function template
7950 
7951         // Check that we can declare a template here.
7952         if (CheckTemplateDeclScope(S, TemplateParams))
7953           NewFD->setInvalidDecl();
7954 
7955         // A destructor cannot be a template.
7956         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7957           Diag(NewFD->getLocation(), diag::err_destructor_template);
7958           NewFD->setInvalidDecl();
7959         }
7960 
7961         // If we're adding a template to a dependent context, we may need to
7962         // rebuilding some of the types used within the template parameter list,
7963         // now that we know what the current instantiation is.
7964         if (DC->isDependentContext()) {
7965           ContextRAII SavedContext(*this, DC);
7966           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7967             Invalid = true;
7968         }
7969 
7970         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7971                                                         NewFD->getLocation(),
7972                                                         Name, TemplateParams,
7973                                                         NewFD);
7974         FunctionTemplate->setLexicalDeclContext(CurContext);
7975         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7976 
7977         // For source fidelity, store the other template param lists.
7978         if (TemplateParamLists.size() > 1) {
7979           NewFD->setTemplateParameterListsInfo(Context,
7980                                                TemplateParamLists.drop_back(1));
7981         }
7982       } else {
7983         // This is a function template specialization.
7984         isFunctionTemplateSpecialization = true;
7985         // For source fidelity, store all the template param lists.
7986         if (TemplateParamLists.size() > 0)
7987           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7988 
7989         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7990         if (isFriend) {
7991           // We want to remove the "template<>", found here.
7992           SourceRange RemoveRange = TemplateParams->getSourceRange();
7993 
7994           // If we remove the template<> and the name is not a
7995           // template-id, we're actually silently creating a problem:
7996           // the friend declaration will refer to an untemplated decl,
7997           // and clearly the user wants a template specialization.  So
7998           // we need to insert '<>' after the name.
7999           SourceLocation InsertLoc;
8000           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
8001             InsertLoc = D.getName().getSourceRange().getEnd();
8002             InsertLoc = getLocForEndOfToken(InsertLoc);
8003           }
8004 
8005           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
8006             << Name << RemoveRange
8007             << FixItHint::CreateRemoval(RemoveRange)
8008             << FixItHint::CreateInsertion(InsertLoc, "<>");
8009         }
8010       }
8011     }
8012     else {
8013       // All template param lists were matched against the scope specifier:
8014       // this is NOT (an explicit specialization of) a template.
8015       if (TemplateParamLists.size() > 0)
8016         // For source fidelity, store all the template param lists.
8017         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
8018     }
8019 
8020     if (Invalid) {
8021       NewFD->setInvalidDecl();
8022       if (FunctionTemplate)
8023         FunctionTemplate->setInvalidDecl();
8024     }
8025 
8026     // C++ [dcl.fct.spec]p5:
8027     //   The virtual specifier shall only be used in declarations of
8028     //   nonstatic class member functions that appear within a
8029     //   member-specification of a class declaration; see 10.3.
8030     //
8031     if (isVirtual && !NewFD->isInvalidDecl()) {
8032       if (!isVirtualOkay) {
8033         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8034              diag::err_virtual_non_function);
8035       } else if (!CurContext->isRecord()) {
8036         // 'virtual' was specified outside of the class.
8037         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8038              diag::err_virtual_out_of_class)
8039           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8040       } else if (NewFD->getDescribedFunctionTemplate()) {
8041         // C++ [temp.mem]p3:
8042         //  A member function template shall not be virtual.
8043         Diag(D.getDeclSpec().getVirtualSpecLoc(),
8044              diag::err_virtual_member_function_template)
8045           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
8046       } else {
8047         // Okay: Add virtual to the method.
8048         NewFD->setVirtualAsWritten(true);
8049       }
8050 
8051       if (getLangOpts().CPlusPlus14 &&
8052           NewFD->getReturnType()->isUndeducedType())
8053         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
8054     }
8055 
8056     if (getLangOpts().CPlusPlus14 &&
8057         (NewFD->isDependentContext() ||
8058          (isFriend && CurContext->isDependentContext())) &&
8059         NewFD->getReturnType()->isUndeducedType()) {
8060       // If the function template is referenced directly (for instance, as a
8061       // member of the current instantiation), pretend it has a dependent type.
8062       // This is not really justified by the standard, but is the only sane
8063       // thing to do.
8064       // FIXME: For a friend function, we have not marked the function as being
8065       // a friend yet, so 'isDependentContext' on the FD doesn't work.
8066       const FunctionProtoType *FPT =
8067           NewFD->getType()->castAs<FunctionProtoType>();
8068       QualType Result =
8069           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
8070       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
8071                                              FPT->getExtProtoInfo()));
8072     }
8073 
8074     // C++ [dcl.fct.spec]p3:
8075     //  The inline specifier shall not appear on a block scope function
8076     //  declaration.
8077     if (isInline && !NewFD->isInvalidDecl()) {
8078       if (CurContext->isFunctionOrMethod()) {
8079         // 'inline' is not allowed on block scope function declaration.
8080         Diag(D.getDeclSpec().getInlineSpecLoc(),
8081              diag::err_inline_declaration_block_scope) << Name
8082           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8083       }
8084     }
8085 
8086     // C++ [dcl.fct.spec]p6:
8087     //  The explicit specifier shall be used only in the declaration of a
8088     //  constructor or conversion function within its class definition;
8089     //  see 12.3.1 and 12.3.2.
8090     if (isExplicit && !NewFD->isInvalidDecl()) {
8091       if (!CurContext->isRecord()) {
8092         // 'explicit' was specified outside of the class.
8093         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8094              diag::err_explicit_out_of_class)
8095           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8096       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8097                  !isa<CXXConversionDecl>(NewFD)) {
8098         // 'explicit' was specified on a function that wasn't a constructor
8099         // or conversion function.
8100         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8101              diag::err_explicit_non_ctor_or_conv_function)
8102           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8103       }
8104     }
8105 
8106     if (isConstexpr) {
8107       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8108       // are implicitly inline.
8109       NewFD->setImplicitlyInline();
8110 
8111       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8112       // be either constructors or to return a literal type. Therefore,
8113       // destructors cannot be declared constexpr.
8114       if (isa<CXXDestructorDecl>(NewFD))
8115         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8116     }
8117 
8118     if (isConcept) {
8119       // This is a function concept.
8120       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
8121         FTD->setConcept();
8122 
8123       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8124       // applied only to the definition of a function template [...]
8125       if (!D.isFunctionDefinition()) {
8126         Diag(D.getDeclSpec().getConceptSpecLoc(),
8127              diag::err_function_concept_not_defined);
8128         NewFD->setInvalidDecl();
8129       }
8130 
8131       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
8132       // have no exception-specification and is treated as if it were specified
8133       // with noexcept(true) (15.4). [...]
8134       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
8135         if (FPT->hasExceptionSpec()) {
8136           SourceRange Range;
8137           if (D.isFunctionDeclarator())
8138             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
8139           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
8140               << FixItHint::CreateRemoval(Range);
8141           NewFD->setInvalidDecl();
8142         } else {
8143           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
8144         }
8145 
8146         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8147         // following restrictions:
8148         // - The declared return type shall have the type bool.
8149         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
8150           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
8151           NewFD->setInvalidDecl();
8152         }
8153 
8154         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8155         // following restrictions:
8156         // - The declaration's parameter list shall be equivalent to an empty
8157         //   parameter list.
8158         if (FPT->getNumParams() > 0 || FPT->isVariadic())
8159           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
8160       }
8161 
8162       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
8163       // implicity defined to be a constexpr declaration (implicitly inline)
8164       NewFD->setImplicitlyInline();
8165 
8166       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
8167       // be declared with the thread_local, inline, friend, or constexpr
8168       // specifiers, [...]
8169       if (isInline) {
8170         Diag(D.getDeclSpec().getInlineSpecLoc(),
8171              diag::err_concept_decl_invalid_specifiers)
8172             << 1 << 1;
8173         NewFD->setInvalidDecl(true);
8174       }
8175 
8176       if (isFriend) {
8177         Diag(D.getDeclSpec().getFriendSpecLoc(),
8178              diag::err_concept_decl_invalid_specifiers)
8179             << 1 << 2;
8180         NewFD->setInvalidDecl(true);
8181       }
8182 
8183       if (isConstexpr) {
8184         Diag(D.getDeclSpec().getConstexprSpecLoc(),
8185              diag::err_concept_decl_invalid_specifiers)
8186             << 1 << 3;
8187         NewFD->setInvalidDecl(true);
8188       }
8189 
8190       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8191       // applied only to the definition of a function template or variable
8192       // template, declared in namespace scope.
8193       if (isFunctionTemplateSpecialization) {
8194         Diag(D.getDeclSpec().getConceptSpecLoc(),
8195              diag::err_concept_specified_specialization) << 1;
8196         NewFD->setInvalidDecl(true);
8197         return NewFD;
8198       }
8199     }
8200 
8201     // If __module_private__ was specified, mark the function accordingly.
8202     if (D.getDeclSpec().isModulePrivateSpecified()) {
8203       if (isFunctionTemplateSpecialization) {
8204         SourceLocation ModulePrivateLoc
8205           = D.getDeclSpec().getModulePrivateSpecLoc();
8206         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8207           << 0
8208           << FixItHint::CreateRemoval(ModulePrivateLoc);
8209       } else {
8210         NewFD->setModulePrivate();
8211         if (FunctionTemplate)
8212           FunctionTemplate->setModulePrivate();
8213       }
8214     }
8215 
8216     if (isFriend) {
8217       if (FunctionTemplate) {
8218         FunctionTemplate->setObjectOfFriendDecl();
8219         FunctionTemplate->setAccess(AS_public);
8220       }
8221       NewFD->setObjectOfFriendDecl();
8222       NewFD->setAccess(AS_public);
8223     }
8224 
8225     // If a function is defined as defaulted or deleted, mark it as such now.
8226     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8227     // definition kind to FDK_Definition.
8228     switch (D.getFunctionDefinitionKind()) {
8229       case FDK_Declaration:
8230       case FDK_Definition:
8231         break;
8232 
8233       case FDK_Defaulted:
8234         NewFD->setDefaulted();
8235         break;
8236 
8237       case FDK_Deleted:
8238         NewFD->setDeletedAsWritten();
8239         break;
8240     }
8241 
8242     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8243         D.isFunctionDefinition()) {
8244       // C++ [class.mfct]p2:
8245       //   A member function may be defined (8.4) in its class definition, in
8246       //   which case it is an inline member function (7.1.2)
8247       NewFD->setImplicitlyInline();
8248     }
8249 
8250     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8251         !CurContext->isRecord()) {
8252       // C++ [class.static]p1:
8253       //   A data or function member of a class may be declared static
8254       //   in a class definition, in which case it is a static member of
8255       //   the class.
8256 
8257       // Complain about the 'static' specifier if it's on an out-of-line
8258       // member function definition.
8259       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8260            diag::err_static_out_of_line)
8261         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8262     }
8263 
8264     // C++11 [except.spec]p15:
8265     //   A deallocation function with no exception-specification is treated
8266     //   as if it were specified with noexcept(true).
8267     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8268     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8269          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8270         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8271       NewFD->setType(Context.getFunctionType(
8272           FPT->getReturnType(), FPT->getParamTypes(),
8273           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8274   }
8275 
8276   // Filter out previous declarations that don't match the scope.
8277   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8278                        D.getCXXScopeSpec().isNotEmpty() ||
8279                        isExplicitSpecialization ||
8280                        isFunctionTemplateSpecialization);
8281 
8282   // Handle GNU asm-label extension (encoded as an attribute).
8283   if (Expr *E = (Expr*) D.getAsmLabel()) {
8284     // The parser guarantees this is a string.
8285     StringLiteral *SE = cast<StringLiteral>(E);
8286     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8287                                                 SE->getString(), 0));
8288   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8289     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8290       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8291     if (I != ExtnameUndeclaredIdentifiers.end()) {
8292       if (isDeclExternC(NewFD)) {
8293         NewFD->addAttr(I->second);
8294         ExtnameUndeclaredIdentifiers.erase(I);
8295       } else
8296         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8297             << /*Variable*/0 << NewFD;
8298     }
8299   }
8300 
8301   // Copy the parameter declarations from the declarator D to the function
8302   // declaration NewFD, if they are available.  First scavenge them into Params.
8303   SmallVector<ParmVarDecl*, 16> Params;
8304   unsigned FTIIdx;
8305   if (D.isFunctionDeclarator(FTIIdx)) {
8306     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8307 
8308     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8309     // function that takes no arguments, not a function that takes a
8310     // single void argument.
8311     // We let through "const void" here because Sema::GetTypeForDeclarator
8312     // already checks for that case.
8313     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8314       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8315         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8316         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8317         Param->setDeclContext(NewFD);
8318         Params.push_back(Param);
8319 
8320         if (Param->isInvalidDecl())
8321           NewFD->setInvalidDecl();
8322       }
8323     }
8324 
8325     if (!getLangOpts().CPlusPlus) {
8326       // In C, find all the tag declarations from the prototype and move them
8327       // into the function DeclContext. Remove them from the surrounding tag
8328       // injection context of the function, which is typically but not always
8329       // the TU.
8330       DeclContext *PrototypeTagContext =
8331           getTagInjectionContext(NewFD->getLexicalDeclContext());
8332       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8333         auto *TD = dyn_cast<TagDecl>(NonParmDecl);
8334 
8335         // We don't want to reparent enumerators. Look at their parent enum
8336         // instead.
8337         if (!TD) {
8338           if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
8339             TD = cast<EnumDecl>(ECD->getDeclContext());
8340         }
8341         if (!TD)
8342           continue;
8343         DeclContext *TagDC = TD->getLexicalDeclContext();
8344         if (!TagDC->containsDecl(TD))
8345           continue;
8346         TagDC->removeDecl(TD);
8347         TD->setDeclContext(NewFD);
8348         NewFD->addDecl(TD);
8349 
8350         // Preserve the lexical DeclContext if it is not the surrounding tag
8351         // injection context of the FD. In this example, the semantic context of
8352         // E will be f and the lexical context will be S, while both the
8353         // semantic and lexical contexts of S will be f:
8354         //   void f(struct S { enum E { a } f; } s);
8355         if (TagDC != PrototypeTagContext)
8356           TD->setLexicalDeclContext(TagDC);
8357       }
8358     }
8359   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8360     // When we're declaring a function with a typedef, typeof, etc as in the
8361     // following example, we'll need to synthesize (unnamed)
8362     // parameters for use in the declaration.
8363     //
8364     // @code
8365     // typedef void fn(int);
8366     // fn f;
8367     // @endcode
8368 
8369     // Synthesize a parameter for each argument type.
8370     for (const auto &AI : FT->param_types()) {
8371       ParmVarDecl *Param =
8372           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8373       Param->setScopeInfo(0, Params.size());
8374       Params.push_back(Param);
8375     }
8376   } else {
8377     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8378            "Should not need args for typedef of non-prototype fn");
8379   }
8380 
8381   // Finally, we know we have the right number of parameters, install them.
8382   NewFD->setParams(Params);
8383 
8384   if (D.getDeclSpec().isNoreturnSpecified())
8385     NewFD->addAttr(
8386         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8387                                        Context, 0));
8388 
8389   // Functions returning a variably modified type violate C99 6.7.5.2p2
8390   // because all functions have linkage.
8391   if (!NewFD->isInvalidDecl() &&
8392       NewFD->getReturnType()->isVariablyModifiedType()) {
8393     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8394     NewFD->setInvalidDecl();
8395   }
8396 
8397   // Apply an implicit SectionAttr if #pragma code_seg is active.
8398   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8399       !NewFD->hasAttr<SectionAttr>()) {
8400     NewFD->addAttr(
8401         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8402                                     CodeSegStack.CurrentValue->getString(),
8403                                     CodeSegStack.CurrentPragmaLocation));
8404     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8405                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8406                          ASTContext::PSF_Read,
8407                      NewFD))
8408       NewFD->dropAttr<SectionAttr>();
8409   }
8410 
8411   // Handle attributes.
8412   ProcessDeclAttributes(S, NewFD, D);
8413 
8414   if (getLangOpts().OpenCL) {
8415     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8416     // type declaration will generate a compilation error.
8417     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8418     if (AddressSpace == LangAS::opencl_local ||
8419         AddressSpace == LangAS::opencl_global ||
8420         AddressSpace == LangAS::opencl_constant) {
8421       Diag(NewFD->getLocation(),
8422            diag::err_opencl_return_value_with_address_space);
8423       NewFD->setInvalidDecl();
8424     }
8425   }
8426 
8427   if (!getLangOpts().CPlusPlus) {
8428     // Perform semantic checking on the function declaration.
8429     bool isExplicitSpecialization=false;
8430     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8431       CheckMain(NewFD, D.getDeclSpec());
8432 
8433     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8434       CheckMSVCRTEntryPoint(NewFD);
8435 
8436     if (!NewFD->isInvalidDecl())
8437       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8438                                                   isExplicitSpecialization));
8439     else if (!Previous.empty())
8440       // Recover gracefully from an invalid redeclaration.
8441       D.setRedeclaration(true);
8442     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8443             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8444            "previous declaration set still overloaded");
8445 
8446     // Diagnose no-prototype function declarations with calling conventions that
8447     // don't support variadic calls. Only do this in C and do it after merging
8448     // possibly prototyped redeclarations.
8449     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8450     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8451       CallingConv CC = FT->getExtInfo().getCC();
8452       if (!supportsVariadicCall(CC)) {
8453         // Windows system headers sometimes accidentally use stdcall without
8454         // (void) parameters, so we relax this to a warning.
8455         int DiagID =
8456             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8457         Diag(NewFD->getLocation(), DiagID)
8458             << FunctionType::getNameForCallConv(CC);
8459       }
8460     }
8461   } else {
8462     // C++11 [replacement.functions]p3:
8463     //  The program's definitions shall not be specified as inline.
8464     //
8465     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8466     //
8467     // Suppress the diagnostic if the function is __attribute__((used)), since
8468     // that forces an external definition to be emitted.
8469     if (D.getDeclSpec().isInlineSpecified() &&
8470         NewFD->isReplaceableGlobalAllocationFunction() &&
8471         !NewFD->hasAttr<UsedAttr>())
8472       Diag(D.getDeclSpec().getInlineSpecLoc(),
8473            diag::ext_operator_new_delete_declared_inline)
8474         << NewFD->getDeclName();
8475 
8476     // If the declarator is a template-id, translate the parser's template
8477     // argument list into our AST format.
8478     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8479       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8480       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8481       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8482       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8483                                          TemplateId->NumArgs);
8484       translateTemplateArguments(TemplateArgsPtr,
8485                                  TemplateArgs);
8486 
8487       HasExplicitTemplateArgs = true;
8488 
8489       if (NewFD->isInvalidDecl()) {
8490         HasExplicitTemplateArgs = false;
8491       } else if (FunctionTemplate) {
8492         // Function template with explicit template arguments.
8493         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8494           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8495 
8496         HasExplicitTemplateArgs = false;
8497       } else {
8498         assert((isFunctionTemplateSpecialization ||
8499                 D.getDeclSpec().isFriendSpecified()) &&
8500                "should have a 'template<>' for this decl");
8501         // "friend void foo<>(int);" is an implicit specialization decl.
8502         isFunctionTemplateSpecialization = true;
8503       }
8504     } else if (isFriend && isFunctionTemplateSpecialization) {
8505       // This combination is only possible in a recovery case;  the user
8506       // wrote something like:
8507       //   template <> friend void foo(int);
8508       // which we're recovering from as if the user had written:
8509       //   friend void foo<>(int);
8510       // Go ahead and fake up a template id.
8511       HasExplicitTemplateArgs = true;
8512       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8513       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8514     }
8515 
8516     // We do not add HD attributes to specializations here because
8517     // they may have different constexpr-ness compared to their
8518     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8519     // may end up with different effective targets. Instead, a
8520     // specialization inherits its target attributes from its template
8521     // in the CheckFunctionTemplateSpecialization() call below.
8522     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8523       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8524 
8525     // If it's a friend (and only if it's a friend), it's possible
8526     // that either the specialized function type or the specialized
8527     // template is dependent, and therefore matching will fail.  In
8528     // this case, don't check the specialization yet.
8529     bool InstantiationDependent = false;
8530     if (isFunctionTemplateSpecialization && isFriend &&
8531         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8532          TemplateSpecializationType::anyDependentTemplateArguments(
8533             TemplateArgs,
8534             InstantiationDependent))) {
8535       assert(HasExplicitTemplateArgs &&
8536              "friend function specialization without template args");
8537       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8538                                                        Previous))
8539         NewFD->setInvalidDecl();
8540     } else if (isFunctionTemplateSpecialization) {
8541       if (CurContext->isDependentContext() && CurContext->isRecord()
8542           && !isFriend) {
8543         isDependentClassScopeExplicitSpecialization = true;
8544         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8545           diag::ext_function_specialization_in_class :
8546           diag::err_function_specialization_in_class)
8547           << NewFD->getDeclName();
8548       } else if (CheckFunctionTemplateSpecialization(NewFD,
8549                                   (HasExplicitTemplateArgs ? &TemplateArgs
8550                                                            : nullptr),
8551                                                      Previous))
8552         NewFD->setInvalidDecl();
8553 
8554       // C++ [dcl.stc]p1:
8555       //   A storage-class-specifier shall not be specified in an explicit
8556       //   specialization (14.7.3)
8557       FunctionTemplateSpecializationInfo *Info =
8558           NewFD->getTemplateSpecializationInfo();
8559       if (Info && SC != SC_None) {
8560         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8561           Diag(NewFD->getLocation(),
8562                diag::err_explicit_specialization_inconsistent_storage_class)
8563             << SC
8564             << FixItHint::CreateRemoval(
8565                                       D.getDeclSpec().getStorageClassSpecLoc());
8566 
8567         else
8568           Diag(NewFD->getLocation(),
8569                diag::ext_explicit_specialization_storage_class)
8570             << FixItHint::CreateRemoval(
8571                                       D.getDeclSpec().getStorageClassSpecLoc());
8572       }
8573     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
8574       if (CheckMemberSpecialization(NewFD, Previous))
8575           NewFD->setInvalidDecl();
8576     }
8577 
8578     // Perform semantic checking on the function declaration.
8579     if (!isDependentClassScopeExplicitSpecialization) {
8580       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8581         CheckMain(NewFD, D.getDeclSpec());
8582 
8583       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8584         CheckMSVCRTEntryPoint(NewFD);
8585 
8586       if (!NewFD->isInvalidDecl())
8587         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8588                                                     isExplicitSpecialization));
8589       else if (!Previous.empty())
8590         // Recover gracefully from an invalid redeclaration.
8591         D.setRedeclaration(true);
8592     }
8593 
8594     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8595             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8596            "previous declaration set still overloaded");
8597 
8598     NamedDecl *PrincipalDecl = (FunctionTemplate
8599                                 ? cast<NamedDecl>(FunctionTemplate)
8600                                 : NewFD);
8601 
8602     if (isFriend && NewFD->getPreviousDecl()) {
8603       AccessSpecifier Access = AS_public;
8604       if (!NewFD->isInvalidDecl())
8605         Access = NewFD->getPreviousDecl()->getAccess();
8606 
8607       NewFD->setAccess(Access);
8608       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8609     }
8610 
8611     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8612         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8613       PrincipalDecl->setNonMemberOperator();
8614 
8615     // If we have a function template, check the template parameter
8616     // list. This will check and merge default template arguments.
8617     if (FunctionTemplate) {
8618       FunctionTemplateDecl *PrevTemplate =
8619                                      FunctionTemplate->getPreviousDecl();
8620       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8621                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8622                                     : nullptr,
8623                             D.getDeclSpec().isFriendSpecified()
8624                               ? (D.isFunctionDefinition()
8625                                    ? TPC_FriendFunctionTemplateDefinition
8626                                    : TPC_FriendFunctionTemplate)
8627                               : (D.getCXXScopeSpec().isSet() &&
8628                                  DC && DC->isRecord() &&
8629                                  DC->isDependentContext())
8630                                   ? TPC_ClassTemplateMember
8631                                   : TPC_FunctionTemplate);
8632     }
8633 
8634     if (NewFD->isInvalidDecl()) {
8635       // Ignore all the rest of this.
8636     } else if (!D.isRedeclaration()) {
8637       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8638                                        AddToScope };
8639       // Fake up an access specifier if it's supposed to be a class member.
8640       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8641         NewFD->setAccess(AS_public);
8642 
8643       // Qualified decls generally require a previous declaration.
8644       if (D.getCXXScopeSpec().isSet()) {
8645         // ...with the major exception of templated-scope or
8646         // dependent-scope friend declarations.
8647 
8648         // TODO: we currently also suppress this check in dependent
8649         // contexts because (1) the parameter depth will be off when
8650         // matching friend templates and (2) we might actually be
8651         // selecting a friend based on a dependent factor.  But there
8652         // are situations where these conditions don't apply and we
8653         // can actually do this check immediately.
8654         if (isFriend &&
8655             (TemplateParamLists.size() ||
8656              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8657              CurContext->isDependentContext())) {
8658           // ignore these
8659         } else {
8660           // The user tried to provide an out-of-line definition for a
8661           // function that is a member of a class or namespace, but there
8662           // was no such member function declared (C++ [class.mfct]p2,
8663           // C++ [namespace.memdef]p2). For example:
8664           //
8665           // class X {
8666           //   void f() const;
8667           // };
8668           //
8669           // void X::f() { } // ill-formed
8670           //
8671           // Complain about this problem, and attempt to suggest close
8672           // matches (e.g., those that differ only in cv-qualifiers and
8673           // whether the parameter types are references).
8674 
8675           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8676                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8677             AddToScope = ExtraArgs.AddToScope;
8678             return Result;
8679           }
8680         }
8681 
8682         // Unqualified local friend declarations are required to resolve
8683         // to something.
8684       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8685         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8686                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8687           AddToScope = ExtraArgs.AddToScope;
8688           return Result;
8689         }
8690       }
8691     } else if (!D.isFunctionDefinition() &&
8692                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8693                !isFriend && !isFunctionTemplateSpecialization &&
8694                !isExplicitSpecialization) {
8695       // An out-of-line member function declaration must also be a
8696       // definition (C++ [class.mfct]p2).
8697       // Note that this is not the case for explicit specializations of
8698       // function templates or member functions of class templates, per
8699       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8700       // extension for compatibility with old SWIG code which likes to
8701       // generate them.
8702       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8703         << D.getCXXScopeSpec().getRange();
8704     }
8705   }
8706 
8707   ProcessPragmaWeak(S, NewFD);
8708   checkAttributesAfterMerging(*this, *NewFD);
8709 
8710   AddKnownFunctionAttributes(NewFD);
8711 
8712   if (NewFD->hasAttr<OverloadableAttr>() &&
8713       !NewFD->getType()->getAs<FunctionProtoType>()) {
8714     Diag(NewFD->getLocation(),
8715          diag::err_attribute_overloadable_no_prototype)
8716       << NewFD;
8717 
8718     // Turn this into a variadic function with no parameters.
8719     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8720     FunctionProtoType::ExtProtoInfo EPI(
8721         Context.getDefaultCallingConvention(true, false));
8722     EPI.Variadic = true;
8723     EPI.ExtInfo = FT->getExtInfo();
8724 
8725     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8726     NewFD->setType(R);
8727   }
8728 
8729   // If there's a #pragma GCC visibility in scope, and this isn't a class
8730   // member, set the visibility of this function.
8731   if (!DC->isRecord() && NewFD->isExternallyVisible())
8732     AddPushedVisibilityAttribute(NewFD);
8733 
8734   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8735   // marking the function.
8736   AddCFAuditedAttribute(NewFD);
8737 
8738   // If this is a function definition, check if we have to apply optnone due to
8739   // a pragma.
8740   if(D.isFunctionDefinition())
8741     AddRangeBasedOptnone(NewFD);
8742 
8743   // If this is the first declaration of an extern C variable, update
8744   // the map of such variables.
8745   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8746       isIncompleteDeclExternC(*this, NewFD))
8747     RegisterLocallyScopedExternCDecl(NewFD, S);
8748 
8749   // Set this FunctionDecl's range up to the right paren.
8750   NewFD->setRangeEnd(D.getSourceRange().getEnd());
8751 
8752   if (D.isRedeclaration() && !Previous.empty()) {
8753     checkDLLAttributeRedeclaration(
8754         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8755         isExplicitSpecialization || isFunctionTemplateSpecialization,
8756         D.isFunctionDefinition());
8757   }
8758 
8759   if (getLangOpts().CUDA) {
8760     IdentifierInfo *II = NewFD->getIdentifier();
8761     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
8762         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8763       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8764         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8765 
8766       Context.setcudaConfigureCallDecl(NewFD);
8767     }
8768 
8769     // Variadic functions, other than a *declaration* of printf, are not allowed
8770     // in device-side CUDA code, unless someone passed
8771     // -fcuda-allow-variadic-functions.
8772     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
8773         (NewFD->hasAttr<CUDADeviceAttr>() ||
8774          NewFD->hasAttr<CUDAGlobalAttr>()) &&
8775         !(II && II->isStr("printf") && NewFD->isExternC() &&
8776           !D.isFunctionDefinition())) {
8777       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
8778     }
8779   }
8780 
8781   if (getLangOpts().CPlusPlus) {
8782     if (FunctionTemplate) {
8783       if (NewFD->isInvalidDecl())
8784         FunctionTemplate->setInvalidDecl();
8785       return FunctionTemplate;
8786     }
8787   }
8788 
8789   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8790     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8791     if ((getLangOpts().OpenCLVersion >= 120)
8792         && (SC == SC_Static)) {
8793       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8794       D.setInvalidType();
8795     }
8796 
8797     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8798     if (!NewFD->getReturnType()->isVoidType()) {
8799       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8800       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8801           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8802                                 : FixItHint());
8803       D.setInvalidType();
8804     }
8805 
8806     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8807     for (auto Param : NewFD->parameters())
8808       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8809   }
8810   for (const ParmVarDecl *Param : NewFD->parameters()) {
8811     QualType PT = Param->getType();
8812 
8813     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8814     // types.
8815     if (getLangOpts().OpenCLVersion >= 200) {
8816       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8817         QualType ElemTy = PipeTy->getElementType();
8818           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8819             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8820             D.setInvalidType();
8821           }
8822       }
8823     }
8824   }
8825 
8826   MarkUnusedFileScopedDecl(NewFD);
8827 
8828   // Here we have an function template explicit specialization at class scope.
8829   // The actually specialization will be postponed to template instatiation
8830   // time via the ClassScopeFunctionSpecializationDecl node.
8831   if (isDependentClassScopeExplicitSpecialization) {
8832     ClassScopeFunctionSpecializationDecl *NewSpec =
8833                          ClassScopeFunctionSpecializationDecl::Create(
8834                                 Context, CurContext, SourceLocation(),
8835                                 cast<CXXMethodDecl>(NewFD),
8836                                 HasExplicitTemplateArgs, TemplateArgs);
8837     CurContext->addDecl(NewSpec);
8838     AddToScope = false;
8839   }
8840 
8841   return NewFD;
8842 }
8843 
8844 /// \brief Checks if the new declaration declared in dependent context must be
8845 /// put in the same redeclaration chain as the specified declaration.
8846 ///
8847 /// \param D Declaration that is checked.
8848 /// \param PrevDecl Previous declaration found with proper lookup method for the
8849 ///                 same declaration name.
8850 /// \returns True if D must be added to the redeclaration chain which PrevDecl
8851 ///          belongs to.
8852 ///
8853 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
8854   // Any declarations should be put into redeclaration chains except for
8855   // friend declaration in a dependent context that names a function in
8856   // namespace scope.
8857   //
8858   // This allows to compile code like:
8859   //
8860   //       void func();
8861   //       template<typename T> class C1 { friend void func() { } };
8862   //       template<typename T> class C2 { friend void func() { } };
8863   //
8864   // This code snippet is a valid code unless both templates are instantiated.
8865   return !(D->getLexicalDeclContext()->isDependentContext() &&
8866            D->getDeclContext()->isFileContext() &&
8867            D->getFriendObjectKind() != Decl::FOK_None);
8868 }
8869 
8870 /// \brief Perform semantic checking of a new function declaration.
8871 ///
8872 /// Performs semantic analysis of the new function declaration
8873 /// NewFD. This routine performs all semantic checking that does not
8874 /// require the actual declarator involved in the declaration, and is
8875 /// used both for the declaration of functions as they are parsed
8876 /// (called via ActOnDeclarator) and for the declaration of functions
8877 /// that have been instantiated via C++ template instantiation (called
8878 /// via InstantiateDecl).
8879 ///
8880 /// \param IsExplicitSpecialization whether this new function declaration is
8881 /// an explicit specialization of the previous declaration.
8882 ///
8883 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8884 ///
8885 /// \returns true if the function declaration is a redeclaration.
8886 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8887                                     LookupResult &Previous,
8888                                     bool IsExplicitSpecialization) {
8889   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8890          "Variably modified return types are not handled here");
8891 
8892   // Determine whether the type of this function should be merged with
8893   // a previous visible declaration. This never happens for functions in C++,
8894   // and always happens in C if the previous declaration was visible.
8895   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8896                                !Previous.isShadowed();
8897 
8898   bool Redeclaration = false;
8899   NamedDecl *OldDecl = nullptr;
8900 
8901   // Merge or overload the declaration with an existing declaration of
8902   // the same name, if appropriate.
8903   if (!Previous.empty()) {
8904     // Determine whether NewFD is an overload of PrevDecl or
8905     // a declaration that requires merging. If it's an overload,
8906     // there's no more work to do here; we'll just add the new
8907     // function to the scope.
8908     if (!AllowOverloadingOfFunction(Previous, Context)) {
8909       NamedDecl *Candidate = Previous.getRepresentativeDecl();
8910       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8911         Redeclaration = true;
8912         OldDecl = Candidate;
8913       }
8914     } else {
8915       switch (CheckOverload(S, NewFD, Previous, OldDecl,
8916                             /*NewIsUsingDecl*/ false)) {
8917       case Ovl_Match:
8918         Redeclaration = true;
8919         break;
8920 
8921       case Ovl_NonFunction:
8922         Redeclaration = true;
8923         break;
8924 
8925       case Ovl_Overload:
8926         Redeclaration = false;
8927         break;
8928       }
8929 
8930       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8931         // If a function name is overloadable in C, then every function
8932         // with that name must be marked "overloadable".
8933         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8934           << Redeclaration << NewFD;
8935         NamedDecl *OverloadedDecl = nullptr;
8936         if (Redeclaration)
8937           OverloadedDecl = OldDecl;
8938         else if (!Previous.empty())
8939           OverloadedDecl = Previous.getRepresentativeDecl();
8940         if (OverloadedDecl)
8941           Diag(OverloadedDecl->getLocation(),
8942                diag::note_attribute_overloadable_prev_overload);
8943         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8944       }
8945     }
8946   }
8947 
8948   // Check for a previous extern "C" declaration with this name.
8949   if (!Redeclaration &&
8950       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8951     if (!Previous.empty()) {
8952       // This is an extern "C" declaration with the same name as a previous
8953       // declaration, and thus redeclares that entity...
8954       Redeclaration = true;
8955       OldDecl = Previous.getFoundDecl();
8956       MergeTypeWithPrevious = false;
8957 
8958       // ... except in the presence of __attribute__((overloadable)).
8959       if (OldDecl->hasAttr<OverloadableAttr>()) {
8960         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8961           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8962             << Redeclaration << NewFD;
8963           Diag(Previous.getFoundDecl()->getLocation(),
8964                diag::note_attribute_overloadable_prev_overload);
8965           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8966         }
8967         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8968           Redeclaration = false;
8969           OldDecl = nullptr;
8970         }
8971       }
8972     }
8973   }
8974 
8975   // C++11 [dcl.constexpr]p8:
8976   //   A constexpr specifier for a non-static member function that is not
8977   //   a constructor declares that member function to be const.
8978   //
8979   // This needs to be delayed until we know whether this is an out-of-line
8980   // definition of a static member function.
8981   //
8982   // This rule is not present in C++1y, so we produce a backwards
8983   // compatibility warning whenever it happens in C++11.
8984   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8985   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8986       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8987       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8988     CXXMethodDecl *OldMD = nullptr;
8989     if (OldDecl)
8990       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8991     if (!OldMD || !OldMD->isStatic()) {
8992       const FunctionProtoType *FPT =
8993         MD->getType()->castAs<FunctionProtoType>();
8994       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8995       EPI.TypeQuals |= Qualifiers::Const;
8996       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8997                                           FPT->getParamTypes(), EPI));
8998 
8999       // Warn that we did this, if we're not performing template instantiation.
9000       // In that case, we'll have warned already when the template was defined.
9001       if (ActiveTemplateInstantiations.empty()) {
9002         SourceLocation AddConstLoc;
9003         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
9004                 .IgnoreParens().getAs<FunctionTypeLoc>())
9005           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
9006 
9007         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
9008           << FixItHint::CreateInsertion(AddConstLoc, " const");
9009       }
9010     }
9011   }
9012 
9013   if (Redeclaration) {
9014     // NewFD and OldDecl represent declarations that need to be
9015     // merged.
9016     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
9017       NewFD->setInvalidDecl();
9018       return Redeclaration;
9019     }
9020 
9021     Previous.clear();
9022     Previous.addDecl(OldDecl);
9023 
9024     if (FunctionTemplateDecl *OldTemplateDecl
9025                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
9026       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
9027       FunctionTemplateDecl *NewTemplateDecl
9028         = NewFD->getDescribedFunctionTemplate();
9029       assert(NewTemplateDecl && "Template/non-template mismatch");
9030       if (CXXMethodDecl *Method
9031             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
9032         Method->setAccess(OldTemplateDecl->getAccess());
9033         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
9034       }
9035 
9036       // If this is an explicit specialization of a member that is a function
9037       // template, mark it as a member specialization.
9038       if (IsExplicitSpecialization &&
9039           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
9040         NewTemplateDecl->setMemberSpecialization();
9041         assert(OldTemplateDecl->isMemberSpecialization());
9042         // Explicit specializations of a member template do not inherit deleted
9043         // status from the parent member template that they are specializing.
9044         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
9045           FunctionDecl *const OldTemplatedDecl =
9046               OldTemplateDecl->getTemplatedDecl();
9047           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
9048           OldTemplatedDecl->setDeletedAsWritten(false);
9049         }
9050       }
9051 
9052     } else {
9053       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
9054         // This needs to happen first so that 'inline' propagates.
9055         NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
9056         if (isa<CXXMethodDecl>(NewFD))
9057           NewFD->setAccess(OldDecl->getAccess());
9058       }
9059     }
9060   }
9061 
9062   // Semantic checking for this function declaration (in isolation).
9063 
9064   if (getLangOpts().CPlusPlus) {
9065     // C++-specific checks.
9066     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
9067       CheckConstructor(Constructor);
9068     } else if (CXXDestructorDecl *Destructor =
9069                 dyn_cast<CXXDestructorDecl>(NewFD)) {
9070       CXXRecordDecl *Record = Destructor->getParent();
9071       QualType ClassType = Context.getTypeDeclType(Record);
9072 
9073       // FIXME: Shouldn't we be able to perform this check even when the class
9074       // type is dependent? Both gcc and edg can handle that.
9075       if (!ClassType->isDependentType()) {
9076         DeclarationName Name
9077           = Context.DeclarationNames.getCXXDestructorName(
9078                                         Context.getCanonicalType(ClassType));
9079         if (NewFD->getDeclName() != Name) {
9080           Diag(NewFD->getLocation(), diag::err_destructor_name);
9081           NewFD->setInvalidDecl();
9082           return Redeclaration;
9083         }
9084       }
9085     } else if (CXXConversionDecl *Conversion
9086                = dyn_cast<CXXConversionDecl>(NewFD)) {
9087       ActOnConversionDeclarator(Conversion);
9088     }
9089 
9090     // Find any virtual functions that this function overrides.
9091     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
9092       if (!Method->isFunctionTemplateSpecialization() &&
9093           !Method->getDescribedFunctionTemplate() &&
9094           Method->isCanonicalDecl()) {
9095         if (AddOverriddenMethods(Method->getParent(), Method)) {
9096           // If the function was marked as "static", we have a problem.
9097           if (NewFD->getStorageClass() == SC_Static) {
9098             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
9099           }
9100         }
9101       }
9102 
9103       if (Method->isStatic())
9104         checkThisInStaticMemberFunctionType(Method);
9105     }
9106 
9107     // Extra checking for C++ overloaded operators (C++ [over.oper]).
9108     if (NewFD->isOverloadedOperator() &&
9109         CheckOverloadedOperatorDeclaration(NewFD)) {
9110       NewFD->setInvalidDecl();
9111       return Redeclaration;
9112     }
9113 
9114     // Extra checking for C++0x literal operators (C++0x [over.literal]).
9115     if (NewFD->getLiteralIdentifier() &&
9116         CheckLiteralOperatorDeclaration(NewFD)) {
9117       NewFD->setInvalidDecl();
9118       return Redeclaration;
9119     }
9120 
9121     // In C++, check default arguments now that we have merged decls. Unless
9122     // the lexical context is the class, because in this case this is done
9123     // during delayed parsing anyway.
9124     if (!CurContext->isRecord())
9125       CheckCXXDefaultArguments(NewFD);
9126 
9127     // If this function declares a builtin function, check the type of this
9128     // declaration against the expected type for the builtin.
9129     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9130       ASTContext::GetBuiltinTypeError Error;
9131       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9132       QualType T = Context.GetBuiltinType(BuiltinID, Error);
9133       // If the type of the builtin differs only in its exception
9134       // specification, that's OK.
9135       // FIXME: If the types do differ in this way, it would be better to
9136       // retain the 'noexcept' form of the type.
9137       if (!T.isNull() &&
9138           !Context.hasSameFunctionTypeIgnoringExceptionSpec(T,
9139                                                             NewFD->getType()))
9140         // The type of this function differs from the type of the builtin,
9141         // so forget about the builtin entirely.
9142         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9143     }
9144 
9145     // If this function is declared as being extern "C", then check to see if
9146     // the function returns a UDT (class, struct, or union type) that is not C
9147     // compatible, and if it does, warn the user.
9148     // But, issue any diagnostic on the first declaration only.
9149     if (Previous.empty() && NewFD->isExternC()) {
9150       QualType R = NewFD->getReturnType();
9151       if (R->isIncompleteType() && !R->isVoidType())
9152         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9153             << NewFD << R;
9154       else if (!R.isPODType(Context) && !R->isVoidType() &&
9155                !R->isObjCObjectPointerType())
9156         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9157     }
9158 
9159     // C++1z [dcl.fct]p6:
9160     //   [...] whether the function has a non-throwing exception-specification
9161     //   [is] part of the function type
9162     //
9163     // This results in an ABI break between C++14 and C++17 for functions whose
9164     // declared type includes an exception-specification in a parameter or
9165     // return type. (Exception specifications on the function itself are OK in
9166     // most cases, and exception specifications are not permitted in most other
9167     // contexts where they could make it into a mangling.)
9168     if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) {
9169       auto HasNoexcept = [&](QualType T) -> bool {
9170         // Strip off declarator chunks that could be between us and a function
9171         // type. We don't need to look far, exception specifications are very
9172         // restricted prior to C++17.
9173         if (auto *RT = T->getAs<ReferenceType>())
9174           T = RT->getPointeeType();
9175         else if (T->isAnyPointerType())
9176           T = T->getPointeeType();
9177         else if (auto *MPT = T->getAs<MemberPointerType>())
9178           T = MPT->getPointeeType();
9179         if (auto *FPT = T->getAs<FunctionProtoType>())
9180           if (FPT->isNothrow(Context))
9181             return true;
9182         return false;
9183       };
9184 
9185       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9186       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9187       for (QualType T : FPT->param_types())
9188         AnyNoexcept |= HasNoexcept(T);
9189       if (AnyNoexcept)
9190         Diag(NewFD->getLocation(),
9191              diag::warn_cxx1z_compat_exception_spec_in_signature)
9192             << NewFD;
9193     }
9194 
9195     if (!Redeclaration && LangOpts.CUDA)
9196       checkCUDATargetOverload(NewFD, Previous);
9197   }
9198   return Redeclaration;
9199 }
9200 
9201 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9202   // C++11 [basic.start.main]p3:
9203   //   A program that [...] declares main to be inline, static or
9204   //   constexpr is ill-formed.
9205   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
9206   //   appear in a declaration of main.
9207   // static main is not an error under C99, but we should warn about it.
9208   // We accept _Noreturn main as an extension.
9209   if (FD->getStorageClass() == SC_Static)
9210     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9211          ? diag::err_static_main : diag::warn_static_main)
9212       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9213   if (FD->isInlineSpecified())
9214     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9215       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9216   if (DS.isNoreturnSpecified()) {
9217     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9218     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9219     Diag(NoreturnLoc, diag::ext_noreturn_main);
9220     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9221       << FixItHint::CreateRemoval(NoreturnRange);
9222   }
9223   if (FD->isConstexpr()) {
9224     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9225       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9226     FD->setConstexpr(false);
9227   }
9228 
9229   if (getLangOpts().OpenCL) {
9230     Diag(FD->getLocation(), diag::err_opencl_no_main)
9231         << FD->hasAttr<OpenCLKernelAttr>();
9232     FD->setInvalidDecl();
9233     return;
9234   }
9235 
9236   QualType T = FD->getType();
9237   assert(T->isFunctionType() && "function decl is not of function type");
9238   const FunctionType* FT = T->castAs<FunctionType>();
9239 
9240   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9241     // In C with GNU extensions we allow main() to have non-integer return
9242     // type, but we should warn about the extension, and we disable the
9243     // implicit-return-zero rule.
9244 
9245     // GCC in C mode accepts qualified 'int'.
9246     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9247       FD->setHasImplicitReturnZero(true);
9248     else {
9249       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9250       SourceRange RTRange = FD->getReturnTypeSourceRange();
9251       if (RTRange.isValid())
9252         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9253             << FixItHint::CreateReplacement(RTRange, "int");
9254     }
9255   } else {
9256     // In C and C++, main magically returns 0 if you fall off the end;
9257     // set the flag which tells us that.
9258     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9259 
9260     // All the standards say that main() should return 'int'.
9261     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9262       FD->setHasImplicitReturnZero(true);
9263     else {
9264       // Otherwise, this is just a flat-out error.
9265       SourceRange RTRange = FD->getReturnTypeSourceRange();
9266       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9267           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9268                                 : FixItHint());
9269       FD->setInvalidDecl(true);
9270     }
9271   }
9272 
9273   // Treat protoless main() as nullary.
9274   if (isa<FunctionNoProtoType>(FT)) return;
9275 
9276   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9277   unsigned nparams = FTP->getNumParams();
9278   assert(FD->getNumParams() == nparams);
9279 
9280   bool HasExtraParameters = (nparams > 3);
9281 
9282   if (FTP->isVariadic()) {
9283     Diag(FD->getLocation(), diag::ext_variadic_main);
9284     // FIXME: if we had information about the location of the ellipsis, we
9285     // could add a FixIt hint to remove it as a parameter.
9286   }
9287 
9288   // Darwin passes an undocumented fourth argument of type char**.  If
9289   // other platforms start sprouting these, the logic below will start
9290   // getting shifty.
9291   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9292     HasExtraParameters = false;
9293 
9294   if (HasExtraParameters) {
9295     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9296     FD->setInvalidDecl(true);
9297     nparams = 3;
9298   }
9299 
9300   // FIXME: a lot of the following diagnostics would be improved
9301   // if we had some location information about types.
9302 
9303   QualType CharPP =
9304     Context.getPointerType(Context.getPointerType(Context.CharTy));
9305   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9306 
9307   for (unsigned i = 0; i < nparams; ++i) {
9308     QualType AT = FTP->getParamType(i);
9309 
9310     bool mismatch = true;
9311 
9312     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9313       mismatch = false;
9314     else if (Expected[i] == CharPP) {
9315       // As an extension, the following forms are okay:
9316       //   char const **
9317       //   char const * const *
9318       //   char * const *
9319 
9320       QualifierCollector qs;
9321       const PointerType* PT;
9322       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9323           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9324           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9325                               Context.CharTy)) {
9326         qs.removeConst();
9327         mismatch = !qs.empty();
9328       }
9329     }
9330 
9331     if (mismatch) {
9332       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9333       // TODO: suggest replacing given type with expected type
9334       FD->setInvalidDecl(true);
9335     }
9336   }
9337 
9338   if (nparams == 1 && !FD->isInvalidDecl()) {
9339     Diag(FD->getLocation(), diag::warn_main_one_arg);
9340   }
9341 
9342   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9343     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9344     FD->setInvalidDecl();
9345   }
9346 }
9347 
9348 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9349   QualType T = FD->getType();
9350   assert(T->isFunctionType() && "function decl is not of function type");
9351   const FunctionType *FT = T->castAs<FunctionType>();
9352 
9353   // Set an implicit return of 'zero' if the function can return some integral,
9354   // enumeration, pointer or nullptr type.
9355   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9356       FT->getReturnType()->isAnyPointerType() ||
9357       FT->getReturnType()->isNullPtrType())
9358     // DllMain is exempt because a return value of zero means it failed.
9359     if (FD->getName() != "DllMain")
9360       FD->setHasImplicitReturnZero(true);
9361 
9362   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9363     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9364     FD->setInvalidDecl();
9365   }
9366 }
9367 
9368 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9369   // FIXME: Need strict checking.  In C89, we need to check for
9370   // any assignment, increment, decrement, function-calls, or
9371   // commas outside of a sizeof.  In C99, it's the same list,
9372   // except that the aforementioned are allowed in unevaluated
9373   // expressions.  Everything else falls under the
9374   // "may accept other forms of constant expressions" exception.
9375   // (We never end up here for C++, so the constant expression
9376   // rules there don't matter.)
9377   const Expr *Culprit;
9378   if (Init->isConstantInitializer(Context, false, &Culprit))
9379     return false;
9380   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9381     << Culprit->getSourceRange();
9382   return true;
9383 }
9384 
9385 namespace {
9386   // Visits an initialization expression to see if OrigDecl is evaluated in
9387   // its own initialization and throws a warning if it does.
9388   class SelfReferenceChecker
9389       : public EvaluatedExprVisitor<SelfReferenceChecker> {
9390     Sema &S;
9391     Decl *OrigDecl;
9392     bool isRecordType;
9393     bool isPODType;
9394     bool isReferenceType;
9395 
9396     bool isInitList;
9397     llvm::SmallVector<unsigned, 4> InitFieldIndex;
9398 
9399   public:
9400     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9401 
9402     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9403                                                     S(S), OrigDecl(OrigDecl) {
9404       isPODType = false;
9405       isRecordType = false;
9406       isReferenceType = false;
9407       isInitList = false;
9408       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9409         isPODType = VD->getType().isPODType(S.Context);
9410         isRecordType = VD->getType()->isRecordType();
9411         isReferenceType = VD->getType()->isReferenceType();
9412       }
9413     }
9414 
9415     // For most expressions, just call the visitor.  For initializer lists,
9416     // track the index of the field being initialized since fields are
9417     // initialized in order allowing use of previously initialized fields.
9418     void CheckExpr(Expr *E) {
9419       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9420       if (!InitList) {
9421         Visit(E);
9422         return;
9423       }
9424 
9425       // Track and increment the index here.
9426       isInitList = true;
9427       InitFieldIndex.push_back(0);
9428       for (auto Child : InitList->children()) {
9429         CheckExpr(cast<Expr>(Child));
9430         ++InitFieldIndex.back();
9431       }
9432       InitFieldIndex.pop_back();
9433     }
9434 
9435     // Returns true if MemberExpr is checked and no futher checking is needed.
9436     // Returns false if additional checking is required.
9437     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9438       llvm::SmallVector<FieldDecl*, 4> Fields;
9439       Expr *Base = E;
9440       bool ReferenceField = false;
9441 
9442       // Get the field memebers used.
9443       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9444         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9445         if (!FD)
9446           return false;
9447         Fields.push_back(FD);
9448         if (FD->getType()->isReferenceType())
9449           ReferenceField = true;
9450         Base = ME->getBase()->IgnoreParenImpCasts();
9451       }
9452 
9453       // Keep checking only if the base Decl is the same.
9454       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9455       if (!DRE || DRE->getDecl() != OrigDecl)
9456         return false;
9457 
9458       // A reference field can be bound to an unininitialized field.
9459       if (CheckReference && !ReferenceField)
9460         return true;
9461 
9462       // Convert FieldDecls to their index number.
9463       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9464       for (const FieldDecl *I : llvm::reverse(Fields))
9465         UsedFieldIndex.push_back(I->getFieldIndex());
9466 
9467       // See if a warning is needed by checking the first difference in index
9468       // numbers.  If field being used has index less than the field being
9469       // initialized, then the use is safe.
9470       for (auto UsedIter = UsedFieldIndex.begin(),
9471                 UsedEnd = UsedFieldIndex.end(),
9472                 OrigIter = InitFieldIndex.begin(),
9473                 OrigEnd = InitFieldIndex.end();
9474            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9475         if (*UsedIter < *OrigIter)
9476           return true;
9477         if (*UsedIter > *OrigIter)
9478           break;
9479       }
9480 
9481       // TODO: Add a different warning which will print the field names.
9482       HandleDeclRefExpr(DRE);
9483       return true;
9484     }
9485 
9486     // For most expressions, the cast is directly above the DeclRefExpr.
9487     // For conditional operators, the cast can be outside the conditional
9488     // operator if both expressions are DeclRefExpr's.
9489     void HandleValue(Expr *E) {
9490       E = E->IgnoreParens();
9491       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9492         HandleDeclRefExpr(DRE);
9493         return;
9494       }
9495 
9496       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9497         Visit(CO->getCond());
9498         HandleValue(CO->getTrueExpr());
9499         HandleValue(CO->getFalseExpr());
9500         return;
9501       }
9502 
9503       if (BinaryConditionalOperator *BCO =
9504               dyn_cast<BinaryConditionalOperator>(E)) {
9505         Visit(BCO->getCond());
9506         HandleValue(BCO->getFalseExpr());
9507         return;
9508       }
9509 
9510       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9511         HandleValue(OVE->getSourceExpr());
9512         return;
9513       }
9514 
9515       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9516         if (BO->getOpcode() == BO_Comma) {
9517           Visit(BO->getLHS());
9518           HandleValue(BO->getRHS());
9519           return;
9520         }
9521       }
9522 
9523       if (isa<MemberExpr>(E)) {
9524         if (isInitList) {
9525           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9526                                       false /*CheckReference*/))
9527             return;
9528         }
9529 
9530         Expr *Base = E->IgnoreParenImpCasts();
9531         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9532           // Check for static member variables and don't warn on them.
9533           if (!isa<FieldDecl>(ME->getMemberDecl()))
9534             return;
9535           Base = ME->getBase()->IgnoreParenImpCasts();
9536         }
9537         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9538           HandleDeclRefExpr(DRE);
9539         return;
9540       }
9541 
9542       Visit(E);
9543     }
9544 
9545     // Reference types not handled in HandleValue are handled here since all
9546     // uses of references are bad, not just r-value uses.
9547     void VisitDeclRefExpr(DeclRefExpr *E) {
9548       if (isReferenceType)
9549         HandleDeclRefExpr(E);
9550     }
9551 
9552     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9553       if (E->getCastKind() == CK_LValueToRValue) {
9554         HandleValue(E->getSubExpr());
9555         return;
9556       }
9557 
9558       Inherited::VisitImplicitCastExpr(E);
9559     }
9560 
9561     void VisitMemberExpr(MemberExpr *E) {
9562       if (isInitList) {
9563         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9564           return;
9565       }
9566 
9567       // Don't warn on arrays since they can be treated as pointers.
9568       if (E->getType()->canDecayToPointerType()) return;
9569 
9570       // Warn when a non-static method call is followed by non-static member
9571       // field accesses, which is followed by a DeclRefExpr.
9572       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9573       bool Warn = (MD && !MD->isStatic());
9574       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9575       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9576         if (!isa<FieldDecl>(ME->getMemberDecl()))
9577           Warn = false;
9578         Base = ME->getBase()->IgnoreParenImpCasts();
9579       }
9580 
9581       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9582         if (Warn)
9583           HandleDeclRefExpr(DRE);
9584         return;
9585       }
9586 
9587       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9588       // Visit that expression.
9589       Visit(Base);
9590     }
9591 
9592     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9593       Expr *Callee = E->getCallee();
9594 
9595       if (isa<UnresolvedLookupExpr>(Callee))
9596         return Inherited::VisitCXXOperatorCallExpr(E);
9597 
9598       Visit(Callee);
9599       for (auto Arg: E->arguments())
9600         HandleValue(Arg->IgnoreParenImpCasts());
9601     }
9602 
9603     void VisitUnaryOperator(UnaryOperator *E) {
9604       // For POD record types, addresses of its own members are well-defined.
9605       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9606           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9607         if (!isPODType)
9608           HandleValue(E->getSubExpr());
9609         return;
9610       }
9611 
9612       if (E->isIncrementDecrementOp()) {
9613         HandleValue(E->getSubExpr());
9614         return;
9615       }
9616 
9617       Inherited::VisitUnaryOperator(E);
9618     }
9619 
9620     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9621 
9622     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9623       if (E->getConstructor()->isCopyConstructor()) {
9624         Expr *ArgExpr = E->getArg(0);
9625         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9626           if (ILE->getNumInits() == 1)
9627             ArgExpr = ILE->getInit(0);
9628         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9629           if (ICE->getCastKind() == CK_NoOp)
9630             ArgExpr = ICE->getSubExpr();
9631         HandleValue(ArgExpr);
9632         return;
9633       }
9634       Inherited::VisitCXXConstructExpr(E);
9635     }
9636 
9637     void VisitCallExpr(CallExpr *E) {
9638       // Treat std::move as a use.
9639       if (E->getNumArgs() == 1) {
9640         if (FunctionDecl *FD = E->getDirectCallee()) {
9641           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9642               FD->getIdentifier()->isStr("move")) {
9643             HandleValue(E->getArg(0));
9644             return;
9645           }
9646         }
9647       }
9648 
9649       Inherited::VisitCallExpr(E);
9650     }
9651 
9652     void VisitBinaryOperator(BinaryOperator *E) {
9653       if (E->isCompoundAssignmentOp()) {
9654         HandleValue(E->getLHS());
9655         Visit(E->getRHS());
9656         return;
9657       }
9658 
9659       Inherited::VisitBinaryOperator(E);
9660     }
9661 
9662     // A custom visitor for BinaryConditionalOperator is needed because the
9663     // regular visitor would check the condition and true expression separately
9664     // but both point to the same place giving duplicate diagnostics.
9665     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9666       Visit(E->getCond());
9667       Visit(E->getFalseExpr());
9668     }
9669 
9670     void HandleDeclRefExpr(DeclRefExpr *DRE) {
9671       Decl* ReferenceDecl = DRE->getDecl();
9672       if (OrigDecl != ReferenceDecl) return;
9673       unsigned diag;
9674       if (isReferenceType) {
9675         diag = diag::warn_uninit_self_reference_in_reference_init;
9676       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9677         diag = diag::warn_static_self_reference_in_init;
9678       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9679                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9680                  DRE->getDecl()->getType()->isRecordType()) {
9681         diag = diag::warn_uninit_self_reference_in_init;
9682       } else {
9683         // Local variables will be handled by the CFG analysis.
9684         return;
9685       }
9686 
9687       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9688                             S.PDiag(diag)
9689                               << DRE->getNameInfo().getName()
9690                               << OrigDecl->getLocation()
9691                               << DRE->getSourceRange());
9692     }
9693   };
9694 
9695   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9696   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9697                                  bool DirectInit) {
9698     // Parameters arguments are occassionially constructed with itself,
9699     // for instance, in recursive functions.  Skip them.
9700     if (isa<ParmVarDecl>(OrigDecl))
9701       return;
9702 
9703     E = E->IgnoreParens();
9704 
9705     // Skip checking T a = a where T is not a record or reference type.
9706     // Doing so is a way to silence uninitialized warnings.
9707     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9708       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9709         if (ICE->getCastKind() == CK_LValueToRValue)
9710           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9711             if (DRE->getDecl() == OrigDecl)
9712               return;
9713 
9714     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9715   }
9716 } // end anonymous namespace
9717 
9718 namespace {
9719   // Simple wrapper to add the name of a variable or (if no variable is
9720   // available) a DeclarationName into a diagnostic.
9721   struct VarDeclOrName {
9722     VarDecl *VDecl;
9723     DeclarationName Name;
9724 
9725     friend const Sema::SemaDiagnosticBuilder &
9726     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
9727       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
9728     }
9729   };
9730 } // end anonymous namespace
9731 
9732 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9733                                             DeclarationName Name, QualType Type,
9734                                             TypeSourceInfo *TSI,
9735                                             SourceRange Range, bool DirectInit,
9736                                             Expr *Init) {
9737   bool IsInitCapture = !VDecl;
9738   assert((!VDecl || !VDecl->isInitCapture()) &&
9739          "init captures are expected to be deduced prior to initialization");
9740 
9741   VarDeclOrName VN{VDecl, Name};
9742 
9743   ArrayRef<Expr *> DeduceInits = Init;
9744   if (DirectInit) {
9745     if (auto *PL = dyn_cast<ParenListExpr>(Init))
9746       DeduceInits = PL->exprs();
9747     else if (auto *IL = dyn_cast<InitListExpr>(Init))
9748       DeduceInits = IL->inits();
9749   }
9750 
9751   // Deduction only works if we have exactly one source expression.
9752   if (DeduceInits.empty()) {
9753     // It isn't possible to write this directly, but it is possible to
9754     // end up in this situation with "auto x(some_pack...);"
9755     Diag(Init->getLocStart(), IsInitCapture
9756                                   ? diag::err_init_capture_no_expression
9757                                   : diag::err_auto_var_init_no_expression)
9758         << VN << Type << Range;
9759     return QualType();
9760   }
9761 
9762   if (DeduceInits.size() > 1) {
9763     Diag(DeduceInits[1]->getLocStart(),
9764          IsInitCapture ? diag::err_init_capture_multiple_expressions
9765                        : diag::err_auto_var_init_multiple_expressions)
9766         << VN << Type << Range;
9767     return QualType();
9768   }
9769 
9770   Expr *DeduceInit = DeduceInits[0];
9771   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9772     Diag(Init->getLocStart(), IsInitCapture
9773                                   ? diag::err_init_capture_paren_braces
9774                                   : diag::err_auto_var_init_paren_braces)
9775         << isa<InitListExpr>(Init) << VN << Type << Range;
9776     return QualType();
9777   }
9778 
9779   // Expressions default to 'id' when we're in a debugger.
9780   bool DefaultedAnyToId = false;
9781   if (getLangOpts().DebuggerCastResultToId &&
9782       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9783     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9784     if (Result.isInvalid()) {
9785       return QualType();
9786     }
9787     Init = Result.get();
9788     DefaultedAnyToId = true;
9789   }
9790 
9791   // C++ [dcl.decomp]p1:
9792   //   If the assignment-expression [...] has array type A and no ref-qualifier
9793   //   is present, e has type cv A
9794   if (VDecl && isa<DecompositionDecl>(VDecl) &&
9795       Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
9796       DeduceInit->getType()->isConstantArrayType())
9797     return Context.getQualifiedType(DeduceInit->getType(),
9798                                     Type.getQualifiers());
9799 
9800   QualType DeducedType;
9801   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9802     if (!IsInitCapture)
9803       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9804     else if (isa<InitListExpr>(Init))
9805       Diag(Range.getBegin(),
9806            diag::err_init_capture_deduction_failure_from_init_list)
9807           << VN
9808           << (DeduceInit->getType().isNull() ? TSI->getType()
9809                                              : DeduceInit->getType())
9810           << DeduceInit->getSourceRange();
9811     else
9812       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9813           << VN << TSI->getType()
9814           << (DeduceInit->getType().isNull() ? TSI->getType()
9815                                              : DeduceInit->getType())
9816           << DeduceInit->getSourceRange();
9817   }
9818 
9819   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9820   // 'id' instead of a specific object type prevents most of our usual
9821   // checks.
9822   // We only want to warn outside of template instantiations, though:
9823   // inside a template, the 'id' could have come from a parameter.
9824   if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
9825       !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9826     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9827     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
9828   }
9829 
9830   return DeducedType;
9831 }
9832 
9833 /// AddInitializerToDecl - Adds the initializer Init to the
9834 /// declaration dcl. If DirectInit is true, this is C++ direct
9835 /// initialization rather than copy initialization.
9836 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
9837   // If there is no declaration, there was an error parsing it.  Just ignore
9838   // the initializer.
9839   if (!RealDecl || RealDecl->isInvalidDecl()) {
9840     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
9841     return;
9842   }
9843 
9844   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
9845     // Pure-specifiers are handled in ActOnPureSpecifier.
9846     Diag(Method->getLocation(), diag::err_member_function_initialization)
9847       << Method->getDeclName() << Init->getSourceRange();
9848     Method->setInvalidDecl();
9849     return;
9850   }
9851 
9852   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9853   if (!VDecl) {
9854     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
9855     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9856     RealDecl->setInvalidDecl();
9857     return;
9858   }
9859 
9860   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9861   if (VDecl->getType()->isUndeducedType()) {
9862     // Attempt typo correction early so that the type of the init expression can
9863     // be deduced based on the chosen correction if the original init contains a
9864     // TypoExpr.
9865     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
9866     if (!Res.isUsable()) {
9867       RealDecl->setInvalidDecl();
9868       return;
9869     }
9870     Init = Res.get();
9871 
9872     QualType DeducedType = deduceVarTypeFromInitializer(
9873         VDecl, VDecl->getDeclName(), VDecl->getType(),
9874         VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
9875     if (DeducedType.isNull()) {
9876       RealDecl->setInvalidDecl();
9877       return;
9878     }
9879 
9880     VDecl->setType(DeducedType);
9881     assert(VDecl->isLinkageValid());
9882 
9883     // In ARC, infer lifetime.
9884     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9885       VDecl->setInvalidDecl();
9886 
9887     // If this is a redeclaration, check that the type we just deduced matches
9888     // the previously declared type.
9889     if (VarDecl *Old = VDecl->getPreviousDecl()) {
9890       // We never need to merge the type, because we cannot form an incomplete
9891       // array of auto, nor deduce such a type.
9892       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9893     }
9894 
9895     // Check the deduced type is valid for a variable declaration.
9896     CheckVariableDeclarationType(VDecl);
9897     if (VDecl->isInvalidDecl())
9898       return;
9899   }
9900 
9901   // dllimport cannot be used on variable definitions.
9902   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
9903     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
9904     VDecl->setInvalidDecl();
9905     return;
9906   }
9907 
9908   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
9909     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
9910     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
9911     VDecl->setInvalidDecl();
9912     return;
9913   }
9914 
9915   if (!VDecl->getType()->isDependentType()) {
9916     // A definition must end up with a complete type, which means it must be
9917     // complete with the restriction that an array type might be completed by
9918     // the initializer; note that later code assumes this restriction.
9919     QualType BaseDeclType = VDecl->getType();
9920     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
9921       BaseDeclType = Array->getElementType();
9922     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
9923                             diag::err_typecheck_decl_incomplete_type)) {
9924       RealDecl->setInvalidDecl();
9925       return;
9926     }
9927 
9928     // The variable can not have an abstract class type.
9929     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9930                                diag::err_abstract_type_in_decl,
9931                                AbstractVariableType))
9932       VDecl->setInvalidDecl();
9933   }
9934 
9935   // If adding the initializer will turn this declaration into a definition,
9936   // and we already have a definition for this variable, diagnose or otherwise
9937   // handle the situation.
9938   VarDecl *Def;
9939   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
9940       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
9941       !VDecl->isThisDeclarationADemotedDefinition() &&
9942       checkVarDeclRedefinition(Def, VDecl))
9943     return;
9944 
9945   if (getLangOpts().CPlusPlus) {
9946     // C++ [class.static.data]p4
9947     //   If a static data member is of const integral or const
9948     //   enumeration type, its declaration in the class definition can
9949     //   specify a constant-initializer which shall be an integral
9950     //   constant expression (5.19). In that case, the member can appear
9951     //   in integral constant expressions. The member shall still be
9952     //   defined in a namespace scope if it is used in the program and the
9953     //   namespace scope definition shall not contain an initializer.
9954     //
9955     // We already performed a redefinition check above, but for static
9956     // data members we also need to check whether there was an in-class
9957     // declaration with an initializer.
9958     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9959       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9960           << VDecl->getDeclName();
9961       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9962            diag::note_previous_initializer)
9963           << 0;
9964       return;
9965     }
9966 
9967     if (VDecl->hasLocalStorage())
9968       getCurFunction()->setHasBranchProtectedScope();
9969 
9970     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9971       VDecl->setInvalidDecl();
9972       return;
9973     }
9974   }
9975 
9976   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9977   // a kernel function cannot be initialized."
9978   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
9979     Diag(VDecl->getLocation(), diag::err_local_cant_init);
9980     VDecl->setInvalidDecl();
9981     return;
9982   }
9983 
9984   // Get the decls type and save a reference for later, since
9985   // CheckInitializerTypes may change it.
9986   QualType DclT = VDecl->getType(), SavT = DclT;
9987 
9988   // Expressions default to 'id' when we're in a debugger
9989   // and we are assigning it to a variable of Objective-C pointer type.
9990   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9991       Init->getType() == Context.UnknownAnyTy) {
9992     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9993     if (Result.isInvalid()) {
9994       VDecl->setInvalidDecl();
9995       return;
9996     }
9997     Init = Result.get();
9998   }
9999 
10000   // Perform the initialization.
10001   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
10002   if (!VDecl->isInvalidDecl()) {
10003     // Handle errors like: int a({0})
10004     if (CXXDirectInit && CXXDirectInit->getNumExprs() == 1 &&
10005         !canInitializeWithParenthesizedList(VDecl->getType()))
10006       if (auto IList = dyn_cast<InitListExpr>(CXXDirectInit->getExpr(0))) {
10007         Diag(VDecl->getLocation(), diag::err_list_init_in_parens)
10008             << VDecl->getType() << CXXDirectInit->getSourceRange()
10009             << FixItHint::CreateRemoval(CXXDirectInit->getLocStart())
10010             << FixItHint::CreateRemoval(CXXDirectInit->getLocEnd());
10011         Init = IList;
10012         CXXDirectInit = nullptr;
10013       }
10014 
10015     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
10016     InitializationKind Kind =
10017         DirectInit
10018             ? CXXDirectInit
10019                   ? InitializationKind::CreateDirect(VDecl->getLocation(),
10020                                                      Init->getLocStart(),
10021                                                      Init->getLocEnd())
10022                   : InitializationKind::CreateDirectList(VDecl->getLocation())
10023             : InitializationKind::CreateCopy(VDecl->getLocation(),
10024                                              Init->getLocStart());
10025 
10026     MultiExprArg Args = Init;
10027     if (CXXDirectInit)
10028       Args = MultiExprArg(CXXDirectInit->getExprs(),
10029                           CXXDirectInit->getNumExprs());
10030 
10031     // Try to correct any TypoExprs in the initialization arguments.
10032     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
10033       ExprResult Res = CorrectDelayedTyposInExpr(
10034           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
10035             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
10036             return Init.Failed() ? ExprError() : E;
10037           });
10038       if (Res.isInvalid()) {
10039         VDecl->setInvalidDecl();
10040       } else if (Res.get() != Args[Idx]) {
10041         Args[Idx] = Res.get();
10042       }
10043     }
10044     if (VDecl->isInvalidDecl())
10045       return;
10046 
10047     InitializationSequence InitSeq(*this, Entity, Kind, Args,
10048                                    /*TopLevelOfInitList=*/false,
10049                                    /*TreatUnavailableAsInvalid=*/false);
10050     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
10051     if (Result.isInvalid()) {
10052       VDecl->setInvalidDecl();
10053       return;
10054     }
10055 
10056     Init = Result.getAs<Expr>();
10057   }
10058 
10059   // Check for self-references within variable initializers.
10060   // Variables declared within a function/method body (except for references)
10061   // are handled by a dataflow analysis.
10062   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
10063       VDecl->getType()->isReferenceType()) {
10064     CheckSelfReference(*this, RealDecl, Init, DirectInit);
10065   }
10066 
10067   // If the type changed, it means we had an incomplete type that was
10068   // completed by the initializer. For example:
10069   //   int ary[] = { 1, 3, 5 };
10070   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
10071   if (!VDecl->isInvalidDecl() && (DclT != SavT))
10072     VDecl->setType(DclT);
10073 
10074   if (!VDecl->isInvalidDecl()) {
10075     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
10076 
10077     if (VDecl->hasAttr<BlocksAttr>())
10078       checkRetainCycles(VDecl, Init);
10079 
10080     // It is safe to assign a weak reference into a strong variable.
10081     // Although this code can still have problems:
10082     //   id x = self.weakProp;
10083     //   id y = self.weakProp;
10084     // we do not warn to warn spuriously when 'x' and 'y' are on separate
10085     // paths through the function. This should be revisited if
10086     // -Wrepeated-use-of-weak is made flow-sensitive.
10087     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
10088         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
10089                          Init->getLocStart()))
10090       getCurFunction()->markSafeWeakUse(Init);
10091   }
10092 
10093   // The initialization is usually a full-expression.
10094   //
10095   // FIXME: If this is a braced initialization of an aggregate, it is not
10096   // an expression, and each individual field initializer is a separate
10097   // full-expression. For instance, in:
10098   //
10099   //   struct Temp { ~Temp(); };
10100   //   struct S { S(Temp); };
10101   //   struct T { S a, b; } t = { Temp(), Temp() }
10102   //
10103   // we should destroy the first Temp before constructing the second.
10104   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10105                                           false,
10106                                           VDecl->isConstexpr());
10107   if (Result.isInvalid()) {
10108     VDecl->setInvalidDecl();
10109     return;
10110   }
10111   Init = Result.get();
10112 
10113   // Attach the initializer to the decl.
10114   VDecl->setInit(Init);
10115 
10116   if (VDecl->isLocalVarDecl()) {
10117     // C99 6.7.8p4: All the expressions in an initializer for an object that has
10118     // static storage duration shall be constant expressions or string literals.
10119     // C++ does not have this restriction.
10120     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
10121       const Expr *Culprit;
10122       if (VDecl->getStorageClass() == SC_Static)
10123         CheckForConstantInitializer(Init, DclT);
10124       // C89 is stricter than C99 for non-static aggregate types.
10125       // C89 6.5.7p3: All the expressions [...] in an initializer list
10126       // for an object that has aggregate or union type shall be
10127       // constant expressions.
10128       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10129                isa<InitListExpr>(Init) &&
10130                !Init->isConstantInitializer(Context, false, &Culprit))
10131         Diag(Culprit->getExprLoc(),
10132              diag::ext_aggregate_init_not_constant)
10133           << Culprit->getSourceRange();
10134     }
10135   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10136              VDecl->getLexicalDeclContext()->isRecord()) {
10137     // This is an in-class initialization for a static data member, e.g.,
10138     //
10139     // struct S {
10140     //   static const int value = 17;
10141     // };
10142 
10143     // C++ [class.mem]p4:
10144     //   A member-declarator can contain a constant-initializer only
10145     //   if it declares a static member (9.4) of const integral or
10146     //   const enumeration type, see 9.4.2.
10147     //
10148     // C++11 [class.static.data]p3:
10149     //   If a non-volatile non-inline const static data member is of integral
10150     //   or enumeration type, its declaration in the class definition can
10151     //   specify a brace-or-equal-initializer in which every initalizer-clause
10152     //   that is an assignment-expression is a constant expression. A static
10153     //   data member of literal type can be declared in the class definition
10154     //   with the constexpr specifier; if so, its declaration shall specify a
10155     //   brace-or-equal-initializer in which every initializer-clause that is
10156     //   an assignment-expression is a constant expression.
10157 
10158     // Do nothing on dependent types.
10159     if (DclT->isDependentType()) {
10160 
10161     // Allow any 'static constexpr' members, whether or not they are of literal
10162     // type. We separately check that every constexpr variable is of literal
10163     // type.
10164     } else if (VDecl->isConstexpr()) {
10165 
10166     // Require constness.
10167     } else if (!DclT.isConstQualified()) {
10168       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10169         << Init->getSourceRange();
10170       VDecl->setInvalidDecl();
10171 
10172     // We allow integer constant expressions in all cases.
10173     } else if (DclT->isIntegralOrEnumerationType()) {
10174       // Check whether the expression is a constant expression.
10175       SourceLocation Loc;
10176       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10177         // In C++11, a non-constexpr const static data member with an
10178         // in-class initializer cannot be volatile.
10179         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10180       else if (Init->isValueDependent())
10181         ; // Nothing to check.
10182       else if (Init->isIntegerConstantExpr(Context, &Loc))
10183         ; // Ok, it's an ICE!
10184       else if (Init->isEvaluatable(Context)) {
10185         // If we can constant fold the initializer through heroics, accept it,
10186         // but report this as a use of an extension for -pedantic.
10187         Diag(Loc, diag::ext_in_class_initializer_non_constant)
10188           << Init->getSourceRange();
10189       } else {
10190         // Otherwise, this is some crazy unknown case.  Report the issue at the
10191         // location provided by the isIntegerConstantExpr failed check.
10192         Diag(Loc, diag::err_in_class_initializer_non_constant)
10193           << Init->getSourceRange();
10194         VDecl->setInvalidDecl();
10195       }
10196 
10197     // We allow foldable floating-point constants as an extension.
10198     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10199       // In C++98, this is a GNU extension. In C++11, it is not, but we support
10200       // it anyway and provide a fixit to add the 'constexpr'.
10201       if (getLangOpts().CPlusPlus11) {
10202         Diag(VDecl->getLocation(),
10203              diag::ext_in_class_initializer_float_type_cxx11)
10204             << DclT << Init->getSourceRange();
10205         Diag(VDecl->getLocStart(),
10206              diag::note_in_class_initializer_float_type_cxx11)
10207             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10208       } else {
10209         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10210           << DclT << Init->getSourceRange();
10211 
10212         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10213           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10214             << Init->getSourceRange();
10215           VDecl->setInvalidDecl();
10216         }
10217       }
10218 
10219     // Suggest adding 'constexpr' in C++11 for literal types.
10220     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10221       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10222         << DclT << Init->getSourceRange()
10223         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10224       VDecl->setConstexpr(true);
10225 
10226     } else {
10227       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10228         << DclT << Init->getSourceRange();
10229       VDecl->setInvalidDecl();
10230     }
10231   } else if (VDecl->isFileVarDecl()) {
10232     // In C, extern is typically used to avoid tentative definitions when
10233     // declaring variables in headers, but adding an intializer makes it a
10234     // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
10235     // In C++, extern is often used to give implictly static const variables
10236     // external linkage, so don't warn in that case. If selectany is present,
10237     // this might be header code intended for C and C++ inclusion, so apply the
10238     // C++ rules.
10239     if (VDecl->getStorageClass() == SC_Extern &&
10240         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10241          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10242         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10243         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10244       Diag(VDecl->getLocation(), diag::warn_extern_init);
10245 
10246     // C99 6.7.8p4. All file scoped initializers need to be constant.
10247     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10248       CheckForConstantInitializer(Init, DclT);
10249   }
10250 
10251   // We will represent direct-initialization similarly to copy-initialization:
10252   //    int x(1);  -as-> int x = 1;
10253   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10254   //
10255   // Clients that want to distinguish between the two forms, can check for
10256   // direct initializer using VarDecl::getInitStyle().
10257   // A major benefit is that clients that don't particularly care about which
10258   // exactly form was it (like the CodeGen) can handle both cases without
10259   // special case code.
10260 
10261   // C++ 8.5p11:
10262   // The form of initialization (using parentheses or '=') is generally
10263   // insignificant, but does matter when the entity being initialized has a
10264   // class type.
10265   if (CXXDirectInit) {
10266     assert(DirectInit && "Call-style initializer must be direct init.");
10267     VDecl->setInitStyle(VarDecl::CallInit);
10268   } else if (DirectInit) {
10269     // This must be list-initialization. No other way is direct-initialization.
10270     VDecl->setInitStyle(VarDecl::ListInit);
10271   }
10272 
10273   CheckCompleteVariableDeclaration(VDecl);
10274 }
10275 
10276 /// ActOnInitializerError - Given that there was an error parsing an
10277 /// initializer for the given declaration, try to return to some form
10278 /// of sanity.
10279 void Sema::ActOnInitializerError(Decl *D) {
10280   // Our main concern here is re-establishing invariants like "a
10281   // variable's type is either dependent or complete".
10282   if (!D || D->isInvalidDecl()) return;
10283 
10284   VarDecl *VD = dyn_cast<VarDecl>(D);
10285   if (!VD) return;
10286 
10287   // Bindings are not usable if we can't make sense of the initializer.
10288   if (auto *DD = dyn_cast<DecompositionDecl>(D))
10289     for (auto *BD : DD->bindings())
10290       BD->setInvalidDecl();
10291 
10292   // Auto types are meaningless if we can't make sense of the initializer.
10293   if (ParsingInitForAutoVars.count(D)) {
10294     D->setInvalidDecl();
10295     return;
10296   }
10297 
10298   QualType Ty = VD->getType();
10299   if (Ty->isDependentType()) return;
10300 
10301   // Require a complete type.
10302   if (RequireCompleteType(VD->getLocation(),
10303                           Context.getBaseElementType(Ty),
10304                           diag::err_typecheck_decl_incomplete_type)) {
10305     VD->setInvalidDecl();
10306     return;
10307   }
10308 
10309   // Require a non-abstract type.
10310   if (RequireNonAbstractType(VD->getLocation(), Ty,
10311                              diag::err_abstract_type_in_decl,
10312                              AbstractVariableType)) {
10313     VD->setInvalidDecl();
10314     return;
10315   }
10316 
10317   // Don't bother complaining about constructors or destructors,
10318   // though.
10319 }
10320 
10321 /// Checks if an object of the given type can be initialized with parenthesized
10322 /// init-list.
10323 ///
10324 /// \param TargetType Type of object being initialized.
10325 ///
10326 /// The function is used to detect wrong initializations, such as 'int({0})'.
10327 ///
10328 bool Sema::canInitializeWithParenthesizedList(QualType TargetType) {
10329   return TargetType->isDependentType() || TargetType->isRecordType() ||
10330          TargetType->getContainedAutoType();
10331 }
10332 
10333 void Sema::ActOnUninitializedDecl(Decl *RealDecl) {
10334   // If there is no declaration, there was an error parsing it. Just ignore it.
10335   if (!RealDecl)
10336     return;
10337 
10338   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
10339     QualType Type = Var->getType();
10340 
10341     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
10342     if (isa<DecompositionDecl>(RealDecl)) {
10343       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
10344       Var->setInvalidDecl();
10345       return;
10346     }
10347 
10348     // C++11 [dcl.spec.auto]p3
10349     if (Type->isUndeducedType()) {
10350       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
10351         << Var->getDeclName() << Type;
10352       Var->setInvalidDecl();
10353       return;
10354     }
10355 
10356     // C++11 [class.static.data]p3: A static data member can be declared with
10357     // the constexpr specifier; if so, its declaration shall specify
10358     // a brace-or-equal-initializer.
10359     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10360     // the definition of a variable [...] or the declaration of a static data
10361     // member.
10362     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
10363         !Var->isThisDeclarationADemotedDefinition()) {
10364       if (Var->isStaticDataMember()) {
10365         // C++1z removes the relevant rule; the in-class declaration is always
10366         // a definition there.
10367         if (!getLangOpts().CPlusPlus1z) {
10368           Diag(Var->getLocation(),
10369                diag::err_constexpr_static_mem_var_requires_init)
10370             << Var->getDeclName();
10371           Var->setInvalidDecl();
10372           return;
10373         }
10374       } else {
10375         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10376         Var->setInvalidDecl();
10377         return;
10378       }
10379     }
10380 
10381     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
10382     // definition having the concept specifier is called a variable concept. A
10383     // concept definition refers to [...] a variable concept and its initializer.
10384     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10385       if (VTD->isConcept()) {
10386         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10387         Var->setInvalidDecl();
10388         return;
10389       }
10390     }
10391 
10392     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10393     // be initialized.
10394     if (!Var->isInvalidDecl() &&
10395         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10396         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10397       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10398       Var->setInvalidDecl();
10399       return;
10400     }
10401 
10402     switch (Var->isThisDeclarationADefinition()) {
10403     case VarDecl::Definition:
10404       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10405         break;
10406 
10407       // We have an out-of-line definition of a static data member
10408       // that has an in-class initializer, so we type-check this like
10409       // a declaration.
10410       //
10411       // Fall through
10412 
10413     case VarDecl::DeclarationOnly:
10414       // It's only a declaration.
10415 
10416       // Block scope. C99 6.7p7: If an identifier for an object is
10417       // declared with no linkage (C99 6.2.2p6), the type for the
10418       // object shall be complete.
10419       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10420           !Var->hasLinkage() && !Var->isInvalidDecl() &&
10421           RequireCompleteType(Var->getLocation(), Type,
10422                               diag::err_typecheck_decl_incomplete_type))
10423         Var->setInvalidDecl();
10424 
10425       // Make sure that the type is not abstract.
10426       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10427           RequireNonAbstractType(Var->getLocation(), Type,
10428                                  diag::err_abstract_type_in_decl,
10429                                  AbstractVariableType))
10430         Var->setInvalidDecl();
10431       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10432           Var->getStorageClass() == SC_PrivateExtern) {
10433         Diag(Var->getLocation(), diag::warn_private_extern);
10434         Diag(Var->getLocation(), diag::note_private_extern);
10435       }
10436 
10437       return;
10438 
10439     case VarDecl::TentativeDefinition:
10440       // File scope. C99 6.9.2p2: A declaration of an identifier for an
10441       // object that has file scope without an initializer, and without a
10442       // storage-class specifier or with the storage-class specifier "static",
10443       // constitutes a tentative definition. Note: A tentative definition with
10444       // external linkage is valid (C99 6.2.2p5).
10445       if (!Var->isInvalidDecl()) {
10446         if (const IncompleteArrayType *ArrayT
10447                                     = Context.getAsIncompleteArrayType(Type)) {
10448           if (RequireCompleteType(Var->getLocation(),
10449                                   ArrayT->getElementType(),
10450                                   diag::err_illegal_decl_array_incomplete_type))
10451             Var->setInvalidDecl();
10452         } else if (Var->getStorageClass() == SC_Static) {
10453           // C99 6.9.2p3: If the declaration of an identifier for an object is
10454           // a tentative definition and has internal linkage (C99 6.2.2p3), the
10455           // declared type shall not be an incomplete type.
10456           // NOTE: code such as the following
10457           //     static struct s;
10458           //     struct s { int a; };
10459           // is accepted by gcc. Hence here we issue a warning instead of
10460           // an error and we do not invalidate the static declaration.
10461           // NOTE: to avoid multiple warnings, only check the first declaration.
10462           if (Var->isFirstDecl())
10463             RequireCompleteType(Var->getLocation(), Type,
10464                                 diag::ext_typecheck_decl_incomplete_type);
10465         }
10466       }
10467 
10468       // Record the tentative definition; we're done.
10469       if (!Var->isInvalidDecl())
10470         TentativeDefinitions.push_back(Var);
10471       return;
10472     }
10473 
10474     // Provide a specific diagnostic for uninitialized variable
10475     // definitions with incomplete array type.
10476     if (Type->isIncompleteArrayType()) {
10477       Diag(Var->getLocation(),
10478            diag::err_typecheck_incomplete_array_needs_initializer);
10479       Var->setInvalidDecl();
10480       return;
10481     }
10482 
10483     // Provide a specific diagnostic for uninitialized variable
10484     // definitions with reference type.
10485     if (Type->isReferenceType()) {
10486       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10487         << Var->getDeclName()
10488         << SourceRange(Var->getLocation(), Var->getLocation());
10489       Var->setInvalidDecl();
10490       return;
10491     }
10492 
10493     // Do not attempt to type-check the default initializer for a
10494     // variable with dependent type.
10495     if (Type->isDependentType())
10496       return;
10497 
10498     if (Var->isInvalidDecl())
10499       return;
10500 
10501     if (!Var->hasAttr<AliasAttr>()) {
10502       if (RequireCompleteType(Var->getLocation(),
10503                               Context.getBaseElementType(Type),
10504                               diag::err_typecheck_decl_incomplete_type)) {
10505         Var->setInvalidDecl();
10506         return;
10507       }
10508     } else {
10509       return;
10510     }
10511 
10512     // The variable can not have an abstract class type.
10513     if (RequireNonAbstractType(Var->getLocation(), Type,
10514                                diag::err_abstract_type_in_decl,
10515                                AbstractVariableType)) {
10516       Var->setInvalidDecl();
10517       return;
10518     }
10519 
10520     // Check for jumps past the implicit initializer.  C++0x
10521     // clarifies that this applies to a "variable with automatic
10522     // storage duration", not a "local variable".
10523     // C++11 [stmt.dcl]p3
10524     //   A program that jumps from a point where a variable with automatic
10525     //   storage duration is not in scope to a point where it is in scope is
10526     //   ill-formed unless the variable has scalar type, class type with a
10527     //   trivial default constructor and a trivial destructor, a cv-qualified
10528     //   version of one of these types, or an array of one of the preceding
10529     //   types and is declared without an initializer.
10530     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10531       if (const RecordType *Record
10532             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10533         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10534         // Mark the function for further checking even if the looser rules of
10535         // C++11 do not require such checks, so that we can diagnose
10536         // incompatibilities with C++98.
10537         if (!CXXRecord->isPOD())
10538           getCurFunction()->setHasBranchProtectedScope();
10539       }
10540     }
10541 
10542     // C++03 [dcl.init]p9:
10543     //   If no initializer is specified for an object, and the
10544     //   object is of (possibly cv-qualified) non-POD class type (or
10545     //   array thereof), the object shall be default-initialized; if
10546     //   the object is of const-qualified type, the underlying class
10547     //   type shall have a user-declared default
10548     //   constructor. Otherwise, if no initializer is specified for
10549     //   a non- static object, the object and its subobjects, if
10550     //   any, have an indeterminate initial value); if the object
10551     //   or any of its subobjects are of const-qualified type, the
10552     //   program is ill-formed.
10553     // C++0x [dcl.init]p11:
10554     //   If no initializer is specified for an object, the object is
10555     //   default-initialized; [...].
10556     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10557     InitializationKind Kind
10558       = InitializationKind::CreateDefault(Var->getLocation());
10559 
10560     InitializationSequence InitSeq(*this, Entity, Kind, None);
10561     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10562     if (Init.isInvalid())
10563       Var->setInvalidDecl();
10564     else if (Init.get()) {
10565       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10566       // This is important for template substitution.
10567       Var->setInitStyle(VarDecl::CallInit);
10568     }
10569 
10570     CheckCompleteVariableDeclaration(Var);
10571   }
10572 }
10573 
10574 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10575   // If there is no declaration, there was an error parsing it. Ignore it.
10576   if (!D)
10577     return;
10578 
10579   VarDecl *VD = dyn_cast<VarDecl>(D);
10580   if (!VD) {
10581     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10582     D->setInvalidDecl();
10583     return;
10584   }
10585 
10586   VD->setCXXForRangeDecl(true);
10587 
10588   // for-range-declaration cannot be given a storage class specifier.
10589   int Error = -1;
10590   switch (VD->getStorageClass()) {
10591   case SC_None:
10592     break;
10593   case SC_Extern:
10594     Error = 0;
10595     break;
10596   case SC_Static:
10597     Error = 1;
10598     break;
10599   case SC_PrivateExtern:
10600     Error = 2;
10601     break;
10602   case SC_Auto:
10603     Error = 3;
10604     break;
10605   case SC_Register:
10606     Error = 4;
10607     break;
10608   }
10609   if (Error != -1) {
10610     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10611       << VD->getDeclName() << Error;
10612     D->setInvalidDecl();
10613   }
10614 }
10615 
10616 StmtResult
10617 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10618                                  IdentifierInfo *Ident,
10619                                  ParsedAttributes &Attrs,
10620                                  SourceLocation AttrEnd) {
10621   // C++1y [stmt.iter]p1:
10622   //   A range-based for statement of the form
10623   //      for ( for-range-identifier : for-range-initializer ) statement
10624   //   is equivalent to
10625   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
10626   DeclSpec DS(Attrs.getPool().getFactory());
10627 
10628   const char *PrevSpec;
10629   unsigned DiagID;
10630   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10631                      getPrintingPolicy());
10632 
10633   Declarator D(DS, Declarator::ForContext);
10634   D.SetIdentifier(Ident, IdentLoc);
10635   D.takeAttributes(Attrs, AttrEnd);
10636 
10637   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10638   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10639                 EmptyAttrs, IdentLoc);
10640   Decl *Var = ActOnDeclarator(S, D);
10641   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10642   FinalizeDeclaration(Var);
10643   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10644                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
10645 }
10646 
10647 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10648   if (var->isInvalidDecl()) return;
10649 
10650   if (getLangOpts().OpenCL) {
10651     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10652     // initialiser
10653     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10654         !var->hasInit()) {
10655       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10656           << 1 /*Init*/;
10657       var->setInvalidDecl();
10658       return;
10659     }
10660   }
10661 
10662   // In Objective-C, don't allow jumps past the implicit initialization of a
10663   // local retaining variable.
10664   if (getLangOpts().ObjC1 &&
10665       var->hasLocalStorage()) {
10666     switch (var->getType().getObjCLifetime()) {
10667     case Qualifiers::OCL_None:
10668     case Qualifiers::OCL_ExplicitNone:
10669     case Qualifiers::OCL_Autoreleasing:
10670       break;
10671 
10672     case Qualifiers::OCL_Weak:
10673     case Qualifiers::OCL_Strong:
10674       getCurFunction()->setHasBranchProtectedScope();
10675       break;
10676     }
10677   }
10678 
10679   // Warn about externally-visible variables being defined without a
10680   // prior declaration.  We only want to do this for global
10681   // declarations, but we also specifically need to avoid doing it for
10682   // class members because the linkage of an anonymous class can
10683   // change if it's later given a typedef name.
10684   if (var->isThisDeclarationADefinition() &&
10685       var->getDeclContext()->getRedeclContext()->isFileContext() &&
10686       var->isExternallyVisible() && var->hasLinkage() &&
10687       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10688                                   var->getLocation())) {
10689     // Find a previous declaration that's not a definition.
10690     VarDecl *prev = var->getPreviousDecl();
10691     while (prev && prev->isThisDeclarationADefinition())
10692       prev = prev->getPreviousDecl();
10693 
10694     if (!prev)
10695       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10696   }
10697 
10698   // Cache the result of checking for constant initialization.
10699   Optional<bool> CacheHasConstInit;
10700   const Expr *CacheCulprit;
10701   auto checkConstInit = [&]() mutable {
10702     if (!CacheHasConstInit)
10703       CacheHasConstInit = var->getInit()->isConstantInitializer(
10704             Context, var->getType()->isReferenceType(), &CacheCulprit);
10705     return *CacheHasConstInit;
10706   };
10707 
10708   if (var->getTLSKind() == VarDecl::TLS_Static) {
10709     if (var->getType().isDestructedType()) {
10710       // GNU C++98 edits for __thread, [basic.start.term]p3:
10711       //   The type of an object with thread storage duration shall not
10712       //   have a non-trivial destructor.
10713       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10714       if (getLangOpts().CPlusPlus11)
10715         Diag(var->getLocation(), diag::note_use_thread_local);
10716     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
10717       if (!checkConstInit()) {
10718         // GNU C++98 edits for __thread, [basic.start.init]p4:
10719         //   An object of thread storage duration shall not require dynamic
10720         //   initialization.
10721         // FIXME: Need strict checking here.
10722         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
10723           << CacheCulprit->getSourceRange();
10724         if (getLangOpts().CPlusPlus11)
10725           Diag(var->getLocation(), diag::note_use_thread_local);
10726       }
10727     }
10728   }
10729 
10730   // Apply section attributes and pragmas to global variables.
10731   bool GlobalStorage = var->hasGlobalStorage();
10732   if (GlobalStorage && var->isThisDeclarationADefinition() &&
10733       ActiveTemplateInstantiations.empty()) {
10734     PragmaStack<StringLiteral *> *Stack = nullptr;
10735     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10736     if (var->getType().isConstQualified())
10737       Stack = &ConstSegStack;
10738     else if (!var->getInit()) {
10739       Stack = &BSSSegStack;
10740       SectionFlags |= ASTContext::PSF_Write;
10741     } else {
10742       Stack = &DataSegStack;
10743       SectionFlags |= ASTContext::PSF_Write;
10744     }
10745     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10746       var->addAttr(SectionAttr::CreateImplicit(
10747           Context, SectionAttr::Declspec_allocate,
10748           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10749     }
10750     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10751       if (UnifySection(SA->getName(), SectionFlags, var))
10752         var->dropAttr<SectionAttr>();
10753 
10754     // Apply the init_seg attribute if this has an initializer.  If the
10755     // initializer turns out to not be dynamic, we'll end up ignoring this
10756     // attribute.
10757     if (CurInitSeg && var->getInit())
10758       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10759                                                CurInitSegLoc));
10760   }
10761 
10762   // All the following checks are C++ only.
10763   if (!getLangOpts().CPlusPlus) {
10764       // If this variable must be emitted, add it as an initializer for the
10765       // current module.
10766      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
10767        Context.addModuleInitializer(ModuleScopes.back().Module, var);
10768      return;
10769   }
10770 
10771   if (auto *DD = dyn_cast<DecompositionDecl>(var))
10772     CheckCompleteDecompositionDeclaration(DD);
10773 
10774   QualType type = var->getType();
10775   if (type->isDependentType()) return;
10776 
10777   // __block variables might require us to capture a copy-initializer.
10778   if (var->hasAttr<BlocksAttr>()) {
10779     // It's currently invalid to ever have a __block variable with an
10780     // array type; should we diagnose that here?
10781 
10782     // Regardless, we don't want to ignore array nesting when
10783     // constructing this copy.
10784     if (type->isStructureOrClassType()) {
10785       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10786       SourceLocation poi = var->getLocation();
10787       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10788       ExprResult result
10789         = PerformMoveOrCopyInitialization(
10790             InitializedEntity::InitializeBlock(poi, type, false),
10791             var, var->getType(), varRef, /*AllowNRVO=*/true);
10792       if (!result.isInvalid()) {
10793         result = MaybeCreateExprWithCleanups(result);
10794         Expr *init = result.getAs<Expr>();
10795         Context.setBlockVarCopyInits(var, init);
10796       }
10797     }
10798   }
10799 
10800   Expr *Init = var->getInit();
10801   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10802   QualType baseType = Context.getBaseElementType(type);
10803 
10804   if (!var->getDeclContext()->isDependentContext() &&
10805       Init && !Init->isValueDependent()) {
10806 
10807     if (var->isConstexpr()) {
10808       SmallVector<PartialDiagnosticAt, 8> Notes;
10809       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10810         SourceLocation DiagLoc = var->getLocation();
10811         // If the note doesn't add any useful information other than a source
10812         // location, fold it into the primary diagnostic.
10813         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10814               diag::note_invalid_subexpr_in_const_expr) {
10815           DiagLoc = Notes[0].first;
10816           Notes.clear();
10817         }
10818         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10819           << var << Init->getSourceRange();
10820         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10821           Diag(Notes[I].first, Notes[I].second);
10822       }
10823     } else if (var->isUsableInConstantExpressions(Context)) {
10824       // Check whether the initializer of a const variable of integral or
10825       // enumeration type is an ICE now, since we can't tell whether it was
10826       // initialized by a constant expression if we check later.
10827       var->checkInitIsICE();
10828     }
10829 
10830     // Don't emit further diagnostics about constexpr globals since they
10831     // were just diagnosed.
10832     if (!var->isConstexpr() && GlobalStorage &&
10833             var->hasAttr<RequireConstantInitAttr>()) {
10834       // FIXME: Need strict checking in C++03 here.
10835       bool DiagErr = getLangOpts().CPlusPlus11
10836           ? !var->checkInitIsICE() : !checkConstInit();
10837       if (DiagErr) {
10838         auto attr = var->getAttr<RequireConstantInitAttr>();
10839         Diag(var->getLocation(), diag::err_require_constant_init_failed)
10840           << Init->getSourceRange();
10841         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
10842           << attr->getRange();
10843       }
10844     }
10845     else if (!var->isConstexpr() && IsGlobal &&
10846              !getDiagnostics().isIgnored(diag::warn_global_constructor,
10847                                     var->getLocation())) {
10848       // Warn about globals which don't have a constant initializer.  Don't
10849       // warn about globals with a non-trivial destructor because we already
10850       // warned about them.
10851       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10852       if (!(RD && !RD->hasTrivialDestructor())) {
10853         if (!checkConstInit())
10854           Diag(var->getLocation(), diag::warn_global_constructor)
10855             << Init->getSourceRange();
10856       }
10857     }
10858   }
10859 
10860   // Require the destructor.
10861   if (const RecordType *recordType = baseType->getAs<RecordType>())
10862     FinalizeVarWithDestructor(var, recordType);
10863 
10864   // If this variable must be emitted, add it as an initializer for the current
10865   // module.
10866   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
10867     Context.addModuleInitializer(ModuleScopes.back().Module, var);
10868 }
10869 
10870 /// \brief Determines if a variable's alignment is dependent.
10871 static bool hasDependentAlignment(VarDecl *VD) {
10872   if (VD->getType()->isDependentType())
10873     return true;
10874   for (auto *I : VD->specific_attrs<AlignedAttr>())
10875     if (I->isAlignmentDependent())
10876       return true;
10877   return false;
10878 }
10879 
10880 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10881 /// any semantic actions necessary after any initializer has been attached.
10882 void
10883 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10884   // Note that we are no longer parsing the initializer for this declaration.
10885   ParsingInitForAutoVars.erase(ThisDecl);
10886 
10887   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10888   if (!VD)
10889     return;
10890 
10891   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
10892     for (auto *BD : DD->bindings()) {
10893       FinalizeDeclaration(BD);
10894     }
10895   }
10896 
10897   checkAttributesAfterMerging(*this, *VD);
10898 
10899   // Perform TLS alignment check here after attributes attached to the variable
10900   // which may affect the alignment have been processed. Only perform the check
10901   // if the target has a maximum TLS alignment (zero means no constraints).
10902   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
10903     // Protect the check so that it's not performed on dependent types and
10904     // dependent alignments (we can't determine the alignment in that case).
10905     if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
10906       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
10907       if (Context.getDeclAlign(VD) > MaxAlignChars) {
10908         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
10909           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
10910           << (unsigned)MaxAlignChars.getQuantity();
10911       }
10912     }
10913   }
10914 
10915   if (VD->isStaticLocal()) {
10916     if (FunctionDecl *FD =
10917             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
10918       // Static locals inherit dll attributes from their function.
10919       if (Attr *A = getDLLAttr(FD)) {
10920         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
10921         NewAttr->setInherited(true);
10922         VD->addAttr(NewAttr);
10923       }
10924       // CUDA E.2.9.4: Within the body of a __device__ or __global__
10925       // function, only __shared__ variables may be declared with
10926       // static storage class.
10927       if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
10928           CUDADiagIfDeviceCode(VD->getLocation(),
10929                                diag::err_device_static_local_var)
10930               << CurrentCUDATarget())
10931         VD->setInvalidDecl();
10932     }
10933   }
10934 
10935   // Perform check for initializers of device-side global variables.
10936   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
10937   // 7.5). We must also apply the same checks to all __shared__
10938   // variables whether they are local or not. CUDA also allows
10939   // constant initializers for __constant__ and __device__ variables.
10940   if (getLangOpts().CUDA) {
10941     const Expr *Init = VD->getInit();
10942     if (Init && VD->hasGlobalStorage()) {
10943       if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
10944           VD->hasAttr<CUDASharedAttr>()) {
10945         assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
10946         bool AllowedInit = false;
10947         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
10948           AllowedInit =
10949               isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
10950         // We'll allow constant initializers even if it's a non-empty
10951         // constructor according to CUDA rules. This deviates from NVCC,
10952         // but allows us to handle things like constexpr constructors.
10953         if (!AllowedInit &&
10954             (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
10955           AllowedInit = VD->getInit()->isConstantInitializer(
10956               Context, VD->getType()->isReferenceType());
10957 
10958         // Also make sure that destructor, if there is one, is empty.
10959         if (AllowedInit)
10960           if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
10961             AllowedInit =
10962                 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
10963 
10964         if (!AllowedInit) {
10965           Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
10966                                       ? diag::err_shared_var_init
10967                                       : diag::err_dynamic_var_init)
10968               << Init->getSourceRange();
10969           VD->setInvalidDecl();
10970         }
10971       } else {
10972         // This is a host-side global variable.  Check that the initializer is
10973         // callable from the host side.
10974         const FunctionDecl *InitFn = nullptr;
10975         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
10976           InitFn = CE->getConstructor();
10977         } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
10978           InitFn = CE->getDirectCallee();
10979         }
10980         if (InitFn) {
10981           CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
10982           if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
10983             Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
10984                 << InitFnTarget << InitFn;
10985             Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
10986             VD->setInvalidDecl();
10987           }
10988         }
10989       }
10990     }
10991   }
10992 
10993   // Grab the dllimport or dllexport attribute off of the VarDecl.
10994   const InheritableAttr *DLLAttr = getDLLAttr(VD);
10995 
10996   // Imported static data members cannot be defined out-of-line.
10997   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
10998     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
10999         VD->isThisDeclarationADefinition()) {
11000       // We allow definitions of dllimport class template static data members
11001       // with a warning.
11002       CXXRecordDecl *Context =
11003         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
11004       bool IsClassTemplateMember =
11005           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
11006           Context->getDescribedClassTemplate();
11007 
11008       Diag(VD->getLocation(),
11009            IsClassTemplateMember
11010                ? diag::warn_attribute_dllimport_static_field_definition
11011                : diag::err_attribute_dllimport_static_field_definition);
11012       Diag(IA->getLocation(), diag::note_attribute);
11013       if (!IsClassTemplateMember)
11014         VD->setInvalidDecl();
11015     }
11016   }
11017 
11018   // dllimport/dllexport variables cannot be thread local, their TLS index
11019   // isn't exported with the variable.
11020   if (DLLAttr && VD->getTLSKind()) {
11021     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
11022     if (F && getDLLAttr(F)) {
11023       assert(VD->isStaticLocal());
11024       // But if this is a static local in a dlimport/dllexport function, the
11025       // function will never be inlined, which means the var would never be
11026       // imported, so having it marked import/export is safe.
11027     } else {
11028       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
11029                                                                     << DLLAttr;
11030       VD->setInvalidDecl();
11031     }
11032   }
11033 
11034   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
11035     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
11036       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
11037       VD->dropAttr<UsedAttr>();
11038     }
11039   }
11040 
11041   const DeclContext *DC = VD->getDeclContext();
11042   // If there's a #pragma GCC visibility in scope, and this isn't a class
11043   // member, set the visibility of this variable.
11044   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
11045     AddPushedVisibilityAttribute(VD);
11046 
11047   // FIXME: Warn on unused templates.
11048   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
11049       !isa<VarTemplatePartialSpecializationDecl>(VD))
11050     MarkUnusedFileScopedDecl(VD);
11051 
11052   // Now we have parsed the initializer and can update the table of magic
11053   // tag values.
11054   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
11055       !VD->getType()->isIntegralOrEnumerationType())
11056     return;
11057 
11058   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
11059     const Expr *MagicValueExpr = VD->getInit();
11060     if (!MagicValueExpr) {
11061       continue;
11062     }
11063     llvm::APSInt MagicValueInt;
11064     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
11065       Diag(I->getRange().getBegin(),
11066            diag::err_type_tag_for_datatype_not_ice)
11067         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11068       continue;
11069     }
11070     if (MagicValueInt.getActiveBits() > 64) {
11071       Diag(I->getRange().getBegin(),
11072            diag::err_type_tag_for_datatype_too_large)
11073         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
11074       continue;
11075     }
11076     uint64_t MagicValue = MagicValueInt.getZExtValue();
11077     RegisterTypeTagForDatatype(I->getArgumentKind(),
11078                                MagicValue,
11079                                I->getMatchingCType(),
11080                                I->getLayoutCompatible(),
11081                                I->getMustBeNull());
11082   }
11083 }
11084 
11085 static bool hasDeducedAuto(DeclaratorDecl *DD) {
11086   auto *VD = dyn_cast<VarDecl>(DD);
11087   return VD && !VD->getType()->hasAutoForTrailingReturnType();
11088 }
11089 
11090 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
11091                                                    ArrayRef<Decl *> Group) {
11092   SmallVector<Decl*, 8> Decls;
11093 
11094   if (DS.isTypeSpecOwned())
11095     Decls.push_back(DS.getRepAsDecl());
11096 
11097   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
11098   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11099   bool DiagnosedMultipleDecomps = false;
11100   DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
11101   bool DiagnosedNonDeducedAuto = false;
11102 
11103   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11104     if (Decl *D = Group[i]) {
11105       // For declarators, there are some additional syntactic-ish checks we need
11106       // to perform.
11107       if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11108         if (!FirstDeclaratorInGroup)
11109           FirstDeclaratorInGroup = DD;
11110         if (!FirstDecompDeclaratorInGroup)
11111           FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
11112         if (!FirstNonDeducedAutoInGroup && DS.containsPlaceholderType() &&
11113             !hasDeducedAuto(DD))
11114           FirstNonDeducedAutoInGroup = DD;
11115 
11116         if (FirstDeclaratorInGroup != DD) {
11117           // A decomposition declaration cannot be combined with any other
11118           // declaration in the same group.
11119           if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
11120             Diag(FirstDecompDeclaratorInGroup->getLocation(),
11121                  diag::err_decomp_decl_not_alone)
11122                 << FirstDeclaratorInGroup->getSourceRange()
11123                 << DD->getSourceRange();
11124             DiagnosedMultipleDecomps = true;
11125           }
11126 
11127           // A declarator that uses 'auto' in any way other than to declare a
11128           // variable with a deduced type cannot be combined with any other
11129           // declarator in the same group.
11130           if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
11131             Diag(FirstNonDeducedAutoInGroup->getLocation(),
11132                  diag::err_auto_non_deduced_not_alone)
11133                 << FirstNonDeducedAutoInGroup->getType()
11134                        ->hasAutoForTrailingReturnType()
11135                 << FirstDeclaratorInGroup->getSourceRange()
11136                 << DD->getSourceRange();
11137             DiagnosedNonDeducedAuto = true;
11138           }
11139         }
11140       }
11141 
11142       Decls.push_back(D);
11143     }
11144   }
11145 
11146   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11147     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11148       handleTagNumbering(Tag, S);
11149       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11150           getLangOpts().CPlusPlus)
11151         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11152     }
11153   }
11154 
11155   return BuildDeclaratorGroup(Decls);
11156 }
11157 
11158 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11159 /// group, performing any necessary semantic checking.
11160 Sema::DeclGroupPtrTy
11161 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group) {
11162   // C++14 [dcl.spec.auto]p7: (DR1347)
11163   //   If the type that replaces the placeholder type is not the same in each
11164   //   deduction, the program is ill-formed.
11165   if (Group.size() > 1) {
11166     QualType Deduced;
11167     VarDecl *DeducedDecl = nullptr;
11168     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11169       VarDecl *D = dyn_cast<VarDecl>(Group[i]);
11170       if (!D || D->isInvalidDecl())
11171         break;
11172       AutoType *AT = D->getType()->getContainedAutoType();
11173       if (!AT || AT->getDeducedType().isNull())
11174         continue;
11175       if (Deduced.isNull()) {
11176         Deduced = AT->getDeducedType();
11177         DeducedDecl = D;
11178       } else if (!Context.hasSameType(AT->getDeducedType(), Deduced)) {
11179         Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11180              diag::err_auto_different_deductions)
11181           << (unsigned)AT->getKeyword()
11182           << Deduced << DeducedDecl->getDeclName()
11183           << AT->getDeducedType() << D->getDeclName()
11184           << DeducedDecl->getInit()->getSourceRange()
11185           << D->getInit()->getSourceRange();
11186         D->setInvalidDecl();
11187         break;
11188       }
11189     }
11190   }
11191 
11192   ActOnDocumentableDecls(Group);
11193 
11194   return DeclGroupPtrTy::make(
11195       DeclGroupRef::Create(Context, Group.data(), Group.size()));
11196 }
11197 
11198 void Sema::ActOnDocumentableDecl(Decl *D) {
11199   ActOnDocumentableDecls(D);
11200 }
11201 
11202 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11203   // Don't parse the comment if Doxygen diagnostics are ignored.
11204   if (Group.empty() || !Group[0])
11205     return;
11206 
11207   if (Diags.isIgnored(diag::warn_doc_param_not_found,
11208                       Group[0]->getLocation()) &&
11209       Diags.isIgnored(diag::warn_unknown_comment_command_name,
11210                       Group[0]->getLocation()))
11211     return;
11212 
11213   if (Group.size() >= 2) {
11214     // This is a decl group.  Normally it will contain only declarations
11215     // produced from declarator list.  But in case we have any definitions or
11216     // additional declaration references:
11217     //   'typedef struct S {} S;'
11218     //   'typedef struct S *S;'
11219     //   'struct S *pS;'
11220     // FinalizeDeclaratorGroup adds these as separate declarations.
11221     Decl *MaybeTagDecl = Group[0];
11222     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11223       Group = Group.slice(1);
11224     }
11225   }
11226 
11227   // See if there are any new comments that are not attached to a decl.
11228   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11229   if (!Comments.empty() &&
11230       !Comments.back()->isAttached()) {
11231     // There is at least one comment that not attached to a decl.
11232     // Maybe it should be attached to one of these decls?
11233     //
11234     // Note that this way we pick up not only comments that precede the
11235     // declaration, but also comments that *follow* the declaration -- thanks to
11236     // the lookahead in the lexer: we've consumed the semicolon and looked
11237     // ahead through comments.
11238     for (unsigned i = 0, e = Group.size(); i != e; ++i)
11239       Context.getCommentForDecl(Group[i], &PP);
11240   }
11241 }
11242 
11243 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11244 /// to introduce parameters into function prototype scope.
11245 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11246   const DeclSpec &DS = D.getDeclSpec();
11247 
11248   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11249 
11250   // C++03 [dcl.stc]p2 also permits 'auto'.
11251   StorageClass SC = SC_None;
11252   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11253     SC = SC_Register;
11254   } else if (getLangOpts().CPlusPlus &&
11255              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11256     SC = SC_Auto;
11257   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11258     Diag(DS.getStorageClassSpecLoc(),
11259          diag::err_invalid_storage_class_in_func_decl);
11260     D.getMutableDeclSpec().ClearStorageClassSpecs();
11261   }
11262 
11263   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11264     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11265       << DeclSpec::getSpecifierName(TSCS);
11266   if (DS.isInlineSpecified())
11267     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11268         << getLangOpts().CPlusPlus1z;
11269   if (DS.isConstexprSpecified())
11270     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11271       << 0;
11272   if (DS.isConceptSpecified())
11273     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
11274 
11275   DiagnoseFunctionSpecifiers(DS);
11276 
11277   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11278   QualType parmDeclType = TInfo->getType();
11279 
11280   if (getLangOpts().CPlusPlus) {
11281     // Check that there are no default arguments inside the type of this
11282     // parameter.
11283     CheckExtraCXXDefaultArguments(D);
11284 
11285     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11286     if (D.getCXXScopeSpec().isSet()) {
11287       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11288         << D.getCXXScopeSpec().getRange();
11289       D.getCXXScopeSpec().clear();
11290     }
11291   }
11292 
11293   // Ensure we have a valid name
11294   IdentifierInfo *II = nullptr;
11295   if (D.hasName()) {
11296     II = D.getIdentifier();
11297     if (!II) {
11298       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11299         << GetNameForDeclarator(D).getName();
11300       D.setInvalidType(true);
11301     }
11302   }
11303 
11304   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11305   if (II) {
11306     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
11307                    ForRedeclaration);
11308     LookupName(R, S);
11309     if (R.isSingleResult()) {
11310       NamedDecl *PrevDecl = R.getFoundDecl();
11311       if (PrevDecl->isTemplateParameter()) {
11312         // Maybe we will complain about the shadowed template parameter.
11313         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11314         // Just pretend that we didn't see the previous declaration.
11315         PrevDecl = nullptr;
11316       } else if (S->isDeclScope(PrevDecl)) {
11317         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
11318         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11319 
11320         // Recover by removing the name
11321         II = nullptr;
11322         D.SetIdentifier(nullptr, D.getIdentifierLoc());
11323         D.setInvalidType(true);
11324       }
11325     }
11326   }
11327 
11328   // Temporarily put parameter variables in the translation unit, not
11329   // the enclosing context.  This prevents them from accidentally
11330   // looking like class members in C++.
11331   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
11332                                     D.getLocStart(),
11333                                     D.getIdentifierLoc(), II,
11334                                     parmDeclType, TInfo,
11335                                     SC);
11336 
11337   if (D.isInvalidType())
11338     New->setInvalidDecl();
11339 
11340   assert(S->isFunctionPrototypeScope());
11341   assert(S->getFunctionPrototypeDepth() >= 1);
11342   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
11343                     S->getNextFunctionPrototypeIndex());
11344 
11345   // Add the parameter declaration into this scope.
11346   S->AddDecl(New);
11347   if (II)
11348     IdResolver.AddDecl(New);
11349 
11350   ProcessDeclAttributes(S, New, D);
11351 
11352   if (D.getDeclSpec().isModulePrivateSpecified())
11353     Diag(New->getLocation(), diag::err_module_private_local)
11354       << 1 << New->getDeclName()
11355       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11356       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11357 
11358   if (New->hasAttr<BlocksAttr>()) {
11359     Diag(New->getLocation(), diag::err_block_on_nonlocal);
11360   }
11361   return New;
11362 }
11363 
11364 /// \brief Synthesizes a variable for a parameter arising from a
11365 /// typedef.
11366 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
11367                                               SourceLocation Loc,
11368                                               QualType T) {
11369   /* FIXME: setting StartLoc == Loc.
11370      Would it be worth to modify callers so as to provide proper source
11371      location for the unnamed parameters, embedding the parameter's type? */
11372   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
11373                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
11374                                            SC_None, nullptr);
11375   Param->setImplicit();
11376   return Param;
11377 }
11378 
11379 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
11380   // Don't diagnose unused-parameter errors in template instantiations; we
11381   // will already have done so in the template itself.
11382   if (!ActiveTemplateInstantiations.empty())
11383     return;
11384 
11385   for (const ParmVarDecl *Parameter : Parameters) {
11386     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
11387         !Parameter->hasAttr<UnusedAttr>()) {
11388       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
11389         << Parameter->getDeclName();
11390     }
11391   }
11392 }
11393 
11394 void Sema::DiagnoseSizeOfParametersAndReturnValue(
11395     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
11396   if (LangOpts.NumLargeByValueCopy == 0) // No check.
11397     return;
11398 
11399   // Warn if the return value is pass-by-value and larger than the specified
11400   // threshold.
11401   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
11402     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
11403     if (Size > LangOpts.NumLargeByValueCopy)
11404       Diag(D->getLocation(), diag::warn_return_value_size)
11405           << D->getDeclName() << Size;
11406   }
11407 
11408   // Warn if any parameter is pass-by-value and larger than the specified
11409   // threshold.
11410   for (const ParmVarDecl *Parameter : Parameters) {
11411     QualType T = Parameter->getType();
11412     if (T->isDependentType() || !T.isPODType(Context))
11413       continue;
11414     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
11415     if (Size > LangOpts.NumLargeByValueCopy)
11416       Diag(Parameter->getLocation(), diag::warn_parameter_size)
11417           << Parameter->getDeclName() << Size;
11418   }
11419 }
11420 
11421 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
11422                                   SourceLocation NameLoc, IdentifierInfo *Name,
11423                                   QualType T, TypeSourceInfo *TSInfo,
11424                                   StorageClass SC) {
11425   // In ARC, infer a lifetime qualifier for appropriate parameter types.
11426   if (getLangOpts().ObjCAutoRefCount &&
11427       T.getObjCLifetime() == Qualifiers::OCL_None &&
11428       T->isObjCLifetimeType()) {
11429 
11430     Qualifiers::ObjCLifetime lifetime;
11431 
11432     // Special cases for arrays:
11433     //   - if it's const, use __unsafe_unretained
11434     //   - otherwise, it's an error
11435     if (T->isArrayType()) {
11436       if (!T.isConstQualified()) {
11437         DelayedDiagnostics.add(
11438             sema::DelayedDiagnostic::makeForbiddenType(
11439             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
11440       }
11441       lifetime = Qualifiers::OCL_ExplicitNone;
11442     } else {
11443       lifetime = T->getObjCARCImplicitLifetime();
11444     }
11445     T = Context.getLifetimeQualifiedType(T, lifetime);
11446   }
11447 
11448   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
11449                                          Context.getAdjustedParameterType(T),
11450                                          TSInfo, SC, nullptr);
11451 
11452   // Parameters can not be abstract class types.
11453   // For record types, this is done by the AbstractClassUsageDiagnoser once
11454   // the class has been completely parsed.
11455   if (!CurContext->isRecord() &&
11456       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11457                              AbstractParamType))
11458     New->setInvalidDecl();
11459 
11460   // Parameter declarators cannot be interface types. All ObjC objects are
11461   // passed by reference.
11462   if (T->isObjCObjectType()) {
11463     SourceLocation TypeEndLoc =
11464         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11465     Diag(NameLoc,
11466          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11467       << FixItHint::CreateInsertion(TypeEndLoc, "*");
11468     T = Context.getObjCObjectPointerType(T);
11469     New->setType(T);
11470   }
11471 
11472   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11473   // duration shall not be qualified by an address-space qualifier."
11474   // Since all parameters have automatic store duration, they can not have
11475   // an address space.
11476   if (T.getAddressSpace() != 0) {
11477     // OpenCL allows function arguments declared to be an array of a type
11478     // to be qualified with an address space.
11479     if (!(getLangOpts().OpenCL && T->isArrayType())) {
11480       Diag(NameLoc, diag::err_arg_with_address_space);
11481       New->setInvalidDecl();
11482     }
11483   }
11484 
11485   return New;
11486 }
11487 
11488 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11489                                            SourceLocation LocAfterDecls) {
11490   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11491 
11492   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11493   // for a K&R function.
11494   if (!FTI.hasPrototype) {
11495     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11496       --i;
11497       if (FTI.Params[i].Param == nullptr) {
11498         SmallString<256> Code;
11499         llvm::raw_svector_ostream(Code)
11500             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
11501         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11502             << FTI.Params[i].Ident
11503             << FixItHint::CreateInsertion(LocAfterDecls, Code);
11504 
11505         // Implicitly declare the argument as type 'int' for lack of a better
11506         // type.
11507         AttributeFactory attrs;
11508         DeclSpec DS(attrs);
11509         const char* PrevSpec; // unused
11510         unsigned DiagID; // unused
11511         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11512                            DiagID, Context.getPrintingPolicy());
11513         // Use the identifier location for the type source range.
11514         DS.SetRangeStart(FTI.Params[i].IdentLoc);
11515         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11516         Declarator ParamD(DS, Declarator::KNRTypeListContext);
11517         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11518         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11519       }
11520     }
11521   }
11522 }
11523 
11524 Decl *
11525 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11526                               MultiTemplateParamsArg TemplateParameterLists,
11527                               SkipBodyInfo *SkipBody) {
11528   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11529   assert(D.isFunctionDeclarator() && "Not a function declarator!");
11530   Scope *ParentScope = FnBodyScope->getParent();
11531 
11532   D.setFunctionDefinitionKind(FDK_Definition);
11533   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11534   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11535 }
11536 
11537 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11538   Consumer.HandleInlineFunctionDefinition(D);
11539 }
11540 
11541 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11542                              const FunctionDecl*& PossibleZeroParamPrototype) {
11543   // Don't warn about invalid declarations.
11544   if (FD->isInvalidDecl())
11545     return false;
11546 
11547   // Or declarations that aren't global.
11548   if (!FD->isGlobal())
11549     return false;
11550 
11551   // Don't warn about C++ member functions.
11552   if (isa<CXXMethodDecl>(FD))
11553     return false;
11554 
11555   // Don't warn about 'main'.
11556   if (FD->isMain())
11557     return false;
11558 
11559   // Don't warn about inline functions.
11560   if (FD->isInlined())
11561     return false;
11562 
11563   // Don't warn about function templates.
11564   if (FD->getDescribedFunctionTemplate())
11565     return false;
11566 
11567   // Don't warn about function template specializations.
11568   if (FD->isFunctionTemplateSpecialization())
11569     return false;
11570 
11571   // Don't warn for OpenCL kernels.
11572   if (FD->hasAttr<OpenCLKernelAttr>())
11573     return false;
11574 
11575   // Don't warn on explicitly deleted functions.
11576   if (FD->isDeleted())
11577     return false;
11578 
11579   bool MissingPrototype = true;
11580   for (const FunctionDecl *Prev = FD->getPreviousDecl();
11581        Prev; Prev = Prev->getPreviousDecl()) {
11582     // Ignore any declarations that occur in function or method
11583     // scope, because they aren't visible from the header.
11584     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11585       continue;
11586 
11587     MissingPrototype = !Prev->getType()->isFunctionProtoType();
11588     if (FD->getNumParams() == 0)
11589       PossibleZeroParamPrototype = Prev;
11590     break;
11591   }
11592 
11593   return MissingPrototype;
11594 }
11595 
11596 void
11597 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11598                                    const FunctionDecl *EffectiveDefinition,
11599                                    SkipBodyInfo *SkipBody) {
11600   // Don't complain if we're in GNU89 mode and the previous definition
11601   // was an extern inline function.
11602   const FunctionDecl *Definition = EffectiveDefinition;
11603   if (!Definition)
11604     if (!FD->isDefined(Definition))
11605       return;
11606 
11607   if (canRedefineFunction(Definition, getLangOpts()))
11608     return;
11609 
11610   // If we don't have a visible definition of the function, and it's inline or
11611   // a template, skip the new definition.
11612   if (SkipBody && !hasVisibleDefinition(Definition) &&
11613       (Definition->getFormalLinkage() == InternalLinkage ||
11614        Definition->isInlined() ||
11615        Definition->getDescribedFunctionTemplate() ||
11616        Definition->getNumTemplateParameterLists())) {
11617     SkipBody->ShouldSkip = true;
11618     if (auto *TD = Definition->getDescribedFunctionTemplate())
11619       makeMergedDefinitionVisible(TD, FD->getLocation());
11620     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
11621                                 FD->getLocation());
11622     return;
11623   }
11624 
11625   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11626       Definition->getStorageClass() == SC_Extern)
11627     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11628         << FD->getDeclName() << getLangOpts().CPlusPlus;
11629   else
11630     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11631 
11632   Diag(Definition->getLocation(), diag::note_previous_definition);
11633   FD->setInvalidDecl();
11634 }
11635 
11636 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11637                                    Sema &S) {
11638   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11639 
11640   LambdaScopeInfo *LSI = S.PushLambdaScope();
11641   LSI->CallOperator = CallOperator;
11642   LSI->Lambda = LambdaClass;
11643   LSI->ReturnType = CallOperator->getReturnType();
11644   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11645 
11646   if (LCD == LCD_None)
11647     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
11648   else if (LCD == LCD_ByCopy)
11649     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
11650   else if (LCD == LCD_ByRef)
11651     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
11652   DeclarationNameInfo DNI = CallOperator->getNameInfo();
11653 
11654   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
11655   LSI->Mutable = !CallOperator->isConst();
11656 
11657   // Add the captures to the LSI so they can be noted as already
11658   // captured within tryCaptureVar.
11659   auto I = LambdaClass->field_begin();
11660   for (const auto &C : LambdaClass->captures()) {
11661     if (C.capturesVariable()) {
11662       VarDecl *VD = C.getCapturedVar();
11663       if (VD->isInitCapture())
11664         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11665       QualType CaptureType = VD->getType();
11666       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11667       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11668           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11669           /*EllipsisLoc*/C.isPackExpansion()
11670                          ? C.getEllipsisLoc() : SourceLocation(),
11671           CaptureType, /*Expr*/ nullptr);
11672 
11673     } else if (C.capturesThis()) {
11674       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11675                               /*Expr*/ nullptr,
11676                               C.getCaptureKind() == LCK_StarThis);
11677     } else {
11678       LSI->addVLATypeCapture(C.getLocation(), I->getType());
11679     }
11680     ++I;
11681   }
11682 }
11683 
11684 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
11685                                     SkipBodyInfo *SkipBody) {
11686   // Clear the last template instantiation error context.
11687   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
11688 
11689   if (!D)
11690     return D;
11691   FunctionDecl *FD = nullptr;
11692 
11693   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
11694     FD = FunTmpl->getTemplatedDecl();
11695   else
11696     FD = cast<FunctionDecl>(D);
11697 
11698   // See if this is a redefinition.
11699   if (!FD->isLateTemplateParsed()) {
11700     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
11701 
11702     // If we're skipping the body, we're done. Don't enter the scope.
11703     if (SkipBody && SkipBody->ShouldSkip)
11704       return D;
11705   }
11706 
11707   // Mark this function as "will have a body eventually".  This lets users to
11708   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
11709   // this function.
11710   FD->setWillHaveBody();
11711 
11712   // If we are instantiating a generic lambda call operator, push
11713   // a LambdaScopeInfo onto the function stack.  But use the information
11714   // that's already been calculated (ActOnLambdaExpr) to prime the current
11715   // LambdaScopeInfo.
11716   // When the template operator is being specialized, the LambdaScopeInfo,
11717   // has to be properly restored so that tryCaptureVariable doesn't try
11718   // and capture any new variables. In addition when calculating potential
11719   // captures during transformation of nested lambdas, it is necessary to
11720   // have the LSI properly restored.
11721   if (isGenericLambdaCallOperatorSpecialization(FD)) {
11722     assert(ActiveTemplateInstantiations.size() &&
11723       "There should be an active template instantiation on the stack "
11724       "when instantiating a generic lambda!");
11725     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
11726   }
11727   else
11728     // Enter a new function scope
11729     PushFunctionScope();
11730 
11731   // Builtin functions cannot be defined.
11732   if (unsigned BuiltinID = FD->getBuiltinID()) {
11733     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
11734         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
11735       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
11736       FD->setInvalidDecl();
11737     }
11738   }
11739 
11740   // The return type of a function definition must be complete
11741   // (C99 6.9.1p3, C++ [dcl.fct]p6).
11742   QualType ResultType = FD->getReturnType();
11743   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
11744       !FD->isInvalidDecl() &&
11745       RequireCompleteType(FD->getLocation(), ResultType,
11746                           diag::err_func_def_incomplete_result))
11747     FD->setInvalidDecl();
11748 
11749   if (FnBodyScope)
11750     PushDeclContext(FnBodyScope, FD);
11751 
11752   // Check the validity of our function parameters
11753   CheckParmsForFunctionDef(FD->parameters(),
11754                            /*CheckParameterNames=*/true);
11755 
11756   // Add non-parameter declarations already in the function to the current
11757   // scope.
11758   if (FnBodyScope) {
11759     for (Decl *NPD : FD->decls()) {
11760       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
11761       if (!NonParmDecl)
11762         continue;
11763       assert(!isa<ParmVarDecl>(NonParmDecl) &&
11764              "parameters should not be in newly created FD yet");
11765 
11766       // If the decl has a name, make it accessible in the current scope.
11767       if (NonParmDecl->getDeclName())
11768         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
11769 
11770       // Similarly, dive into enums and fish their constants out, making them
11771       // accessible in this scope.
11772       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
11773         for (auto *EI : ED->enumerators())
11774           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
11775       }
11776     }
11777   }
11778 
11779   // Introduce our parameters into the function scope
11780   for (auto Param : FD->parameters()) {
11781     Param->setOwningFunction(FD);
11782 
11783     // If this has an identifier, add it to the scope stack.
11784     if (Param->getIdentifier() && FnBodyScope) {
11785       CheckShadow(FnBodyScope, Param);
11786 
11787       PushOnScopeChains(Param, FnBodyScope);
11788     }
11789   }
11790 
11791   // Ensure that the function's exception specification is instantiated.
11792   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
11793     ResolveExceptionSpec(D->getLocation(), FPT);
11794 
11795   // dllimport cannot be applied to non-inline function definitions.
11796   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
11797       !FD->isTemplateInstantiation()) {
11798     assert(!FD->hasAttr<DLLExportAttr>());
11799     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
11800     FD->setInvalidDecl();
11801     return D;
11802   }
11803   // We want to attach documentation to original Decl (which might be
11804   // a function template).
11805   ActOnDocumentableDecl(D);
11806   if (getCurLexicalContext()->isObjCContainer() &&
11807       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
11808       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
11809     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
11810 
11811   return D;
11812 }
11813 
11814 /// \brief Given the set of return statements within a function body,
11815 /// compute the variables that are subject to the named return value
11816 /// optimization.
11817 ///
11818 /// Each of the variables that is subject to the named return value
11819 /// optimization will be marked as NRVO variables in the AST, and any
11820 /// return statement that has a marked NRVO variable as its NRVO candidate can
11821 /// use the named return value optimization.
11822 ///
11823 /// This function applies a very simplistic algorithm for NRVO: if every return
11824 /// statement in the scope of a variable has the same NRVO candidate, that
11825 /// candidate is an NRVO variable.
11826 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
11827   ReturnStmt **Returns = Scope->Returns.data();
11828 
11829   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
11830     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
11831       if (!NRVOCandidate->isNRVOVariable())
11832         Returns[I]->setNRVOCandidate(nullptr);
11833     }
11834   }
11835 }
11836 
11837 bool Sema::canDelayFunctionBody(const Declarator &D) {
11838   // We can't delay parsing the body of a constexpr function template (yet).
11839   if (D.getDeclSpec().isConstexprSpecified())
11840     return false;
11841 
11842   // We can't delay parsing the body of a function template with a deduced
11843   // return type (yet).
11844   if (D.getDeclSpec().containsPlaceholderType()) {
11845     // If the placeholder introduces a non-deduced trailing return type,
11846     // we can still delay parsing it.
11847     if (D.getNumTypeObjects()) {
11848       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11849       if (Outer.Kind == DeclaratorChunk::Function &&
11850           Outer.Fun.hasTrailingReturnType()) {
11851         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11852         return Ty.isNull() || !Ty->isUndeducedType();
11853       }
11854     }
11855     return false;
11856   }
11857 
11858   return true;
11859 }
11860 
11861 bool Sema::canSkipFunctionBody(Decl *D) {
11862   // We cannot skip the body of a function (or function template) which is
11863   // constexpr, since we may need to evaluate its body in order to parse the
11864   // rest of the file.
11865   // We cannot skip the body of a function with an undeduced return type,
11866   // because any callers of that function need to know the type.
11867   if (const FunctionDecl *FD = D->getAsFunction())
11868     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11869       return false;
11870   return Consumer.shouldSkipFunctionBody(D);
11871 }
11872 
11873 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11874   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11875     FD->setHasSkippedBody();
11876   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11877     MD->setHasSkippedBody();
11878   return Decl;
11879 }
11880 
11881 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11882   return ActOnFinishFunctionBody(D, BodyArg, false);
11883 }
11884 
11885 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
11886                                     bool IsInstantiation) {
11887   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
11888 
11889   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11890   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
11891 
11892   if (getLangOpts().CoroutinesTS && !getCurFunction()->CoroutineStmts.empty())
11893     CheckCompletedCoroutineBody(FD, Body);
11894 
11895   if (FD) {
11896     FD->setBody(Body);
11897 
11898     if (getLangOpts().CPlusPlus14) {
11899       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
11900           FD->getReturnType()->isUndeducedType()) {
11901         // If the function has a deduced result type but contains no 'return'
11902         // statements, the result type as written must be exactly 'auto', and
11903         // the deduced result type is 'void'.
11904         if (!FD->getReturnType()->getAs<AutoType>()) {
11905           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
11906               << FD->getReturnType();
11907           FD->setInvalidDecl();
11908         } else {
11909           // Substitute 'void' for the 'auto' in the type.
11910           TypeLoc ResultType = getReturnTypeLoc(FD);
11911           Context.adjustDeducedFunctionResultType(
11912               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
11913         }
11914       }
11915     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
11916       // In C++11, we don't use 'auto' deduction rules for lambda call
11917       // operators because we don't support return type deduction.
11918       auto *LSI = getCurLambda();
11919       if (LSI->HasImplicitReturnType) {
11920         deduceClosureReturnType(*LSI);
11921 
11922         // C++11 [expr.prim.lambda]p4:
11923         //   [...] if there are no return statements in the compound-statement
11924         //   [the deduced type is] the type void
11925         QualType RetType =
11926             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
11927 
11928         // Update the return type to the deduced type.
11929         const FunctionProtoType *Proto =
11930             FD->getType()->getAs<FunctionProtoType>();
11931         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
11932                                             Proto->getExtProtoInfo()));
11933       }
11934     }
11935 
11936     // The only way to be included in UndefinedButUsed is if there is an
11937     // ODR use before the definition. Avoid the expensive map lookup if this
11938     // is the first declaration.
11939     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
11940       if (!FD->isExternallyVisible())
11941         UndefinedButUsed.erase(FD);
11942       else if (FD->isInlined() &&
11943                !LangOpts.GNUInline &&
11944                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
11945         UndefinedButUsed.erase(FD);
11946     }
11947 
11948     // If the function implicitly returns zero (like 'main') or is naked,
11949     // don't complain about missing return statements.
11950     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
11951       WP.disableCheckFallThrough();
11952 
11953     // MSVC permits the use of pure specifier (=0) on function definition,
11954     // defined at class scope, warn about this non-standard construct.
11955     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
11956       Diag(FD->getLocation(), diag::ext_pure_function_definition);
11957 
11958     if (!FD->isInvalidDecl()) {
11959       // Don't diagnose unused parameters of defaulted or deleted functions.
11960       if (!FD->isDeleted() && !FD->isDefaulted())
11961         DiagnoseUnusedParameters(FD->parameters());
11962       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
11963                                              FD->getReturnType(), FD);
11964 
11965       // If this is a structor, we need a vtable.
11966       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
11967         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
11968       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
11969         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
11970 
11971       // Try to apply the named return value optimization. We have to check
11972       // if we can do this here because lambdas keep return statements around
11973       // to deduce an implicit return type.
11974       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
11975           !FD->isDependentContext())
11976         computeNRVO(Body, getCurFunction());
11977     }
11978 
11979     // GNU warning -Wmissing-prototypes:
11980     //   Warn if a global function is defined without a previous
11981     //   prototype declaration. This warning is issued even if the
11982     //   definition itself provides a prototype. The aim is to detect
11983     //   global functions that fail to be declared in header files.
11984     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
11985     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
11986       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
11987 
11988       if (PossibleZeroParamPrototype) {
11989         // We found a declaration that is not a prototype,
11990         // but that could be a zero-parameter prototype
11991         if (TypeSourceInfo *TI =
11992                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
11993           TypeLoc TL = TI->getTypeLoc();
11994           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
11995             Diag(PossibleZeroParamPrototype->getLocation(),
11996                  diag::note_declaration_not_a_prototype)
11997                 << PossibleZeroParamPrototype
11998                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
11999         }
12000       }
12001 
12002       // GNU warning -Wstrict-prototypes
12003       //   Warn if K&R function is defined without a previous declaration.
12004       //   This warning is issued only if the definition itself does not provide
12005       //   a prototype. Only K&R definitions do not provide a prototype.
12006       //   An empty list in a function declarator that is part of a definition
12007       //   of that function specifies that the function has no parameters
12008       //   (C99 6.7.5.3p14)
12009       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
12010           !LangOpts.CPlusPlus) {
12011         TypeSourceInfo *TI = FD->getTypeSourceInfo();
12012         TypeLoc TL = TI->getTypeLoc();
12013         FunctionTypeLoc FTL = TL.castAs<FunctionTypeLoc>();
12014         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 1;
12015       }
12016     }
12017 
12018     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
12019       const CXXMethodDecl *KeyFunction;
12020       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
12021           MD->isVirtual() &&
12022           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
12023           MD == KeyFunction->getCanonicalDecl()) {
12024         // Update the key-function state if necessary for this ABI.
12025         if (FD->isInlined() &&
12026             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
12027           Context.setNonKeyFunction(MD);
12028 
12029           // If the newly-chosen key function is already defined, then we
12030           // need to mark the vtable as used retroactively.
12031           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
12032           const FunctionDecl *Definition;
12033           if (KeyFunction && KeyFunction->isDefined(Definition))
12034             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
12035         } else {
12036           // We just defined they key function; mark the vtable as used.
12037           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
12038         }
12039       }
12040     }
12041 
12042     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
12043            "Function parsing confused");
12044   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
12045     assert(MD == getCurMethodDecl() && "Method parsing confused");
12046     MD->setBody(Body);
12047     if (!MD->isInvalidDecl()) {
12048       DiagnoseUnusedParameters(MD->parameters());
12049       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
12050                                              MD->getReturnType(), MD);
12051 
12052       if (Body)
12053         computeNRVO(Body, getCurFunction());
12054     }
12055     if (getCurFunction()->ObjCShouldCallSuper) {
12056       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
12057         << MD->getSelector().getAsString();
12058       getCurFunction()->ObjCShouldCallSuper = false;
12059     }
12060     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
12061       const ObjCMethodDecl *InitMethod = nullptr;
12062       bool isDesignated =
12063           MD->isDesignatedInitializerForTheInterface(&InitMethod);
12064       assert(isDesignated && InitMethod);
12065       (void)isDesignated;
12066 
12067       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
12068         auto IFace = MD->getClassInterface();
12069         if (!IFace)
12070           return false;
12071         auto SuperD = IFace->getSuperClass();
12072         if (!SuperD)
12073           return false;
12074         return SuperD->getIdentifier() ==
12075             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
12076       };
12077       // Don't issue this warning for unavailable inits or direct subclasses
12078       // of NSObject.
12079       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
12080         Diag(MD->getLocation(),
12081              diag::warn_objc_designated_init_missing_super_call);
12082         Diag(InitMethod->getLocation(),
12083              diag::note_objc_designated_init_marked_here);
12084       }
12085       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
12086     }
12087     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
12088       // Don't issue this warning for unavaialable inits.
12089       if (!MD->isUnavailable())
12090         Diag(MD->getLocation(),
12091              diag::warn_objc_secondary_init_missing_init_call);
12092       getCurFunction()->ObjCWarnForNoInitDelegation = false;
12093     }
12094   } else {
12095     return nullptr;
12096   }
12097 
12098   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
12099     DiagnoseUnguardedAvailabilityViolations(dcl);
12100 
12101   assert(!getCurFunction()->ObjCShouldCallSuper &&
12102          "This should only be set for ObjC methods, which should have been "
12103          "handled in the block above.");
12104 
12105   // Verify and clean out per-function state.
12106   if (Body && (!FD || !FD->isDefaulted())) {
12107     // C++ constructors that have function-try-blocks can't have return
12108     // statements in the handlers of that block. (C++ [except.handle]p14)
12109     // Verify this.
12110     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12111       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12112 
12113     // Verify that gotos and switch cases don't jump into scopes illegally.
12114     if (getCurFunction()->NeedsScopeChecking() &&
12115         !PP.isCodeCompletionEnabled())
12116       DiagnoseInvalidJumps(Body);
12117 
12118     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12119       if (!Destructor->getParent()->isDependentType())
12120         CheckDestructor(Destructor);
12121 
12122       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12123                                              Destructor->getParent());
12124     }
12125 
12126     // If any errors have occurred, clear out any temporaries that may have
12127     // been leftover. This ensures that these temporaries won't be picked up for
12128     // deletion in some later function.
12129     if (getDiagnostics().hasErrorOccurred() ||
12130         getDiagnostics().getSuppressAllDiagnostics()) {
12131       DiscardCleanupsInEvaluationContext();
12132     }
12133     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12134         !isa<FunctionTemplateDecl>(dcl)) {
12135       // Since the body is valid, issue any analysis-based warnings that are
12136       // enabled.
12137       ActivePolicy = &WP;
12138     }
12139 
12140     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12141         (!CheckConstexprFunctionDecl(FD) ||
12142          !CheckConstexprFunctionBody(FD, Body)))
12143       FD->setInvalidDecl();
12144 
12145     if (FD && FD->hasAttr<NakedAttr>()) {
12146       for (const Stmt *S : Body->children()) {
12147         // Allow local register variables without initializer as they don't
12148         // require prologue.
12149         bool RegisterVariables = false;
12150         if (auto *DS = dyn_cast<DeclStmt>(S)) {
12151           for (const auto *Decl : DS->decls()) {
12152             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12153               RegisterVariables =
12154                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12155               if (!RegisterVariables)
12156                 break;
12157             }
12158           }
12159         }
12160         if (RegisterVariables)
12161           continue;
12162         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12163           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12164           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12165           FD->setInvalidDecl();
12166           break;
12167         }
12168       }
12169     }
12170 
12171     assert(ExprCleanupObjects.size() ==
12172                ExprEvalContexts.back().NumCleanupObjects &&
12173            "Leftover temporaries in function");
12174     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12175     assert(MaybeODRUseExprs.empty() &&
12176            "Leftover expressions for odr-use checking");
12177   }
12178 
12179   if (!IsInstantiation)
12180     PopDeclContext();
12181 
12182   PopFunctionScopeInfo(ActivePolicy, dcl);
12183   // If any errors have occurred, clear out any temporaries that may have
12184   // been leftover. This ensures that these temporaries won't be picked up for
12185   // deletion in some later function.
12186   if (getDiagnostics().hasErrorOccurred()) {
12187     DiscardCleanupsInEvaluationContext();
12188   }
12189 
12190   return dcl;
12191 }
12192 
12193 /// When we finish delayed parsing of an attribute, we must attach it to the
12194 /// relevant Decl.
12195 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12196                                        ParsedAttributes &Attrs) {
12197   // Always attach attributes to the underlying decl.
12198   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12199     D = TD->getTemplatedDecl();
12200   ProcessDeclAttributeList(S, D, Attrs.getList());
12201 
12202   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12203     if (Method->isStatic())
12204       checkThisInStaticMemberFunctionAttributes(Method);
12205 }
12206 
12207 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12208 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12209 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12210                                           IdentifierInfo &II, Scope *S) {
12211   // Before we produce a declaration for an implicitly defined
12212   // function, see whether there was a locally-scoped declaration of
12213   // this name as a function or variable. If so, use that
12214   // (non-visible) declaration, and complain about it.
12215   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
12216     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
12217     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12218     return ExternCPrev;
12219   }
12220 
12221   // Extension in C99.  Legal in C90, but warn about it.
12222   unsigned diag_id;
12223   if (II.getName().startswith("__builtin_"))
12224     diag_id = diag::warn_builtin_unknown;
12225   else if (getLangOpts().C99)
12226     diag_id = diag::ext_implicit_function_decl;
12227   else
12228     diag_id = diag::warn_implicit_function_decl;
12229   Diag(Loc, diag_id) << &II;
12230 
12231   // Because typo correction is expensive, only do it if the implicit
12232   // function declaration is going to be treated as an error.
12233   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
12234     TypoCorrection Corrected;
12235     if (S &&
12236         (Corrected = CorrectTypo(
12237              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
12238              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
12239       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
12240                    /*ErrorRecovery*/false);
12241   }
12242 
12243   // Set a Declarator for the implicit definition: int foo();
12244   const char *Dummy;
12245   AttributeFactory attrFactory;
12246   DeclSpec DS(attrFactory);
12247   unsigned DiagID;
12248   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
12249                                   Context.getPrintingPolicy());
12250   (void)Error; // Silence warning.
12251   assert(!Error && "Error setting up implicit decl!");
12252   SourceLocation NoLoc;
12253   Declarator D(DS, Declarator::BlockContext);
12254   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
12255                                              /*IsAmbiguous=*/false,
12256                                              /*LParenLoc=*/NoLoc,
12257                                              /*Params=*/nullptr,
12258                                              /*NumParams=*/0,
12259                                              /*EllipsisLoc=*/NoLoc,
12260                                              /*RParenLoc=*/NoLoc,
12261                                              /*TypeQuals=*/0,
12262                                              /*RefQualifierIsLvalueRef=*/true,
12263                                              /*RefQualifierLoc=*/NoLoc,
12264                                              /*ConstQualifierLoc=*/NoLoc,
12265                                              /*VolatileQualifierLoc=*/NoLoc,
12266                                              /*RestrictQualifierLoc=*/NoLoc,
12267                                              /*MutableLoc=*/NoLoc,
12268                                              EST_None,
12269                                              /*ESpecRange=*/SourceRange(),
12270                                              /*Exceptions=*/nullptr,
12271                                              /*ExceptionRanges=*/nullptr,
12272                                              /*NumExceptions=*/0,
12273                                              /*NoexceptExpr=*/nullptr,
12274                                              /*ExceptionSpecTokens=*/nullptr,
12275                                              /*DeclsInPrototype=*/None,
12276                                              Loc, Loc, D),
12277                 DS.getAttributes(),
12278                 SourceLocation());
12279   D.SetIdentifier(&II, Loc);
12280 
12281   // Insert this function into translation-unit scope.
12282 
12283   DeclContext *PrevDC = CurContext;
12284   CurContext = Context.getTranslationUnitDecl();
12285 
12286   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
12287   FD->setImplicit();
12288 
12289   CurContext = PrevDC;
12290 
12291   AddKnownFunctionAttributes(FD);
12292 
12293   return FD;
12294 }
12295 
12296 /// \brief Adds any function attributes that we know a priori based on
12297 /// the declaration of this function.
12298 ///
12299 /// These attributes can apply both to implicitly-declared builtins
12300 /// (like __builtin___printf_chk) or to library-declared functions
12301 /// like NSLog or printf.
12302 ///
12303 /// We need to check for duplicate attributes both here and where user-written
12304 /// attributes are applied to declarations.
12305 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
12306   if (FD->isInvalidDecl())
12307     return;
12308 
12309   // If this is a built-in function, map its builtin attributes to
12310   // actual attributes.
12311   if (unsigned BuiltinID = FD->getBuiltinID()) {
12312     // Handle printf-formatting attributes.
12313     unsigned FormatIdx;
12314     bool HasVAListArg;
12315     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
12316       if (!FD->hasAttr<FormatAttr>()) {
12317         const char *fmt = "printf";
12318         unsigned int NumParams = FD->getNumParams();
12319         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
12320             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
12321           fmt = "NSString";
12322         FD->addAttr(FormatAttr::CreateImplicit(Context,
12323                                                &Context.Idents.get(fmt),
12324                                                FormatIdx+1,
12325                                                HasVAListArg ? 0 : FormatIdx+2,
12326                                                FD->getLocation()));
12327       }
12328     }
12329     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
12330                                              HasVAListArg)) {
12331      if (!FD->hasAttr<FormatAttr>())
12332        FD->addAttr(FormatAttr::CreateImplicit(Context,
12333                                               &Context.Idents.get("scanf"),
12334                                               FormatIdx+1,
12335                                               HasVAListArg ? 0 : FormatIdx+2,
12336                                               FD->getLocation()));
12337     }
12338 
12339     // Mark const if we don't care about errno and that is the only
12340     // thing preventing the function from being const. This allows
12341     // IRgen to use LLVM intrinsics for such functions.
12342     if (!getLangOpts().MathErrno &&
12343         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
12344       if (!FD->hasAttr<ConstAttr>())
12345         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12346     }
12347 
12348     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
12349         !FD->hasAttr<ReturnsTwiceAttr>())
12350       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
12351                                          FD->getLocation()));
12352     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
12353       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12354     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
12355       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
12356     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
12357       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12358     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
12359         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
12360       // Add the appropriate attribute, depending on the CUDA compilation mode
12361       // and which target the builtin belongs to. For example, during host
12362       // compilation, aux builtins are __device__, while the rest are __host__.
12363       if (getLangOpts().CUDAIsDevice !=
12364           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
12365         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
12366       else
12367         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
12368     }
12369   }
12370 
12371   // If C++ exceptions are enabled but we are told extern "C" functions cannot
12372   // throw, add an implicit nothrow attribute to any extern "C" function we come
12373   // across.
12374   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
12375       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
12376     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
12377     if (!FPT || FPT->getExceptionSpecType() == EST_None)
12378       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12379   }
12380 
12381   IdentifierInfo *Name = FD->getIdentifier();
12382   if (!Name)
12383     return;
12384   if ((!getLangOpts().CPlusPlus &&
12385        FD->getDeclContext()->isTranslationUnit()) ||
12386       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
12387        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
12388        LinkageSpecDecl::lang_c)) {
12389     // Okay: this could be a libc/libm/Objective-C function we know
12390     // about.
12391   } else
12392     return;
12393 
12394   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
12395     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
12396     // target-specific builtins, perhaps?
12397     if (!FD->hasAttr<FormatAttr>())
12398       FD->addAttr(FormatAttr::CreateImplicit(Context,
12399                                              &Context.Idents.get("printf"), 2,
12400                                              Name->isStr("vasprintf") ? 0 : 3,
12401                                              FD->getLocation()));
12402   }
12403 
12404   if (Name->isStr("__CFStringMakeConstantString")) {
12405     // We already have a __builtin___CFStringMakeConstantString,
12406     // but builds that use -fno-constant-cfstrings don't go through that.
12407     if (!FD->hasAttr<FormatArgAttr>())
12408       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
12409                                                 FD->getLocation()));
12410   }
12411 }
12412 
12413 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
12414                                     TypeSourceInfo *TInfo) {
12415   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
12416   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
12417 
12418   if (!TInfo) {
12419     assert(D.isInvalidType() && "no declarator info for valid type");
12420     TInfo = Context.getTrivialTypeSourceInfo(T);
12421   }
12422 
12423   // Scope manipulation handled by caller.
12424   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
12425                                            D.getLocStart(),
12426                                            D.getIdentifierLoc(),
12427                                            D.getIdentifier(),
12428                                            TInfo);
12429 
12430   // Bail out immediately if we have an invalid declaration.
12431   if (D.isInvalidType()) {
12432     NewTD->setInvalidDecl();
12433     return NewTD;
12434   }
12435 
12436   if (D.getDeclSpec().isModulePrivateSpecified()) {
12437     if (CurContext->isFunctionOrMethod())
12438       Diag(NewTD->getLocation(), diag::err_module_private_local)
12439         << 2 << NewTD->getDeclName()
12440         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12441         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12442     else
12443       NewTD->setModulePrivate();
12444   }
12445 
12446   // C++ [dcl.typedef]p8:
12447   //   If the typedef declaration defines an unnamed class (or
12448   //   enum), the first typedef-name declared by the declaration
12449   //   to be that class type (or enum type) is used to denote the
12450   //   class type (or enum type) for linkage purposes only.
12451   // We need to check whether the type was declared in the declaration.
12452   switch (D.getDeclSpec().getTypeSpecType()) {
12453   case TST_enum:
12454   case TST_struct:
12455   case TST_interface:
12456   case TST_union:
12457   case TST_class: {
12458     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
12459     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
12460     break;
12461   }
12462 
12463   default:
12464     break;
12465   }
12466 
12467   return NewTD;
12468 }
12469 
12470 /// \brief Check that this is a valid underlying type for an enum declaration.
12471 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
12472   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
12473   QualType T = TI->getType();
12474 
12475   if (T->isDependentType())
12476     return false;
12477 
12478   if (const BuiltinType *BT = T->getAs<BuiltinType>())
12479     if (BT->isInteger())
12480       return false;
12481 
12482   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12483   return true;
12484 }
12485 
12486 /// Check whether this is a valid redeclaration of a previous enumeration.
12487 /// \return true if the redeclaration was invalid.
12488 bool Sema::CheckEnumRedeclaration(
12489     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12490     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12491   bool IsFixed = !EnumUnderlyingTy.isNull();
12492 
12493   if (IsScoped != Prev->isScoped()) {
12494     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12495       << Prev->isScoped();
12496     Diag(Prev->getLocation(), diag::note_previous_declaration);
12497     return true;
12498   }
12499 
12500   if (IsFixed && Prev->isFixed()) {
12501     if (!EnumUnderlyingTy->isDependentType() &&
12502         !Prev->getIntegerType()->isDependentType() &&
12503         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12504                                         Prev->getIntegerType())) {
12505       // TODO: Highlight the underlying type of the redeclaration.
12506       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12507         << EnumUnderlyingTy << Prev->getIntegerType();
12508       Diag(Prev->getLocation(), diag::note_previous_declaration)
12509           << Prev->getIntegerTypeRange();
12510       return true;
12511     }
12512   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12513     ;
12514   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12515     ;
12516   } else if (IsFixed != Prev->isFixed()) {
12517     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12518       << Prev->isFixed();
12519     Diag(Prev->getLocation(), diag::note_previous_declaration);
12520     return true;
12521   }
12522 
12523   return false;
12524 }
12525 
12526 /// \brief Get diagnostic %select index for tag kind for
12527 /// redeclaration diagnostic message.
12528 /// WARNING: Indexes apply to particular diagnostics only!
12529 ///
12530 /// \returns diagnostic %select index.
12531 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12532   switch (Tag) {
12533   case TTK_Struct: return 0;
12534   case TTK_Interface: return 1;
12535   case TTK_Class:  return 2;
12536   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12537   }
12538 }
12539 
12540 /// \brief Determine if tag kind is a class-key compatible with
12541 /// class for redeclaration (class, struct, or __interface).
12542 ///
12543 /// \returns true iff the tag kind is compatible.
12544 static bool isClassCompatTagKind(TagTypeKind Tag)
12545 {
12546   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12547 }
12548 
12549 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
12550                                              TagTypeKind TTK) {
12551   if (isa<TypedefDecl>(PrevDecl))
12552     return NTK_Typedef;
12553   else if (isa<TypeAliasDecl>(PrevDecl))
12554     return NTK_TypeAlias;
12555   else if (isa<ClassTemplateDecl>(PrevDecl))
12556     return NTK_Template;
12557   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
12558     return NTK_TypeAliasTemplate;
12559   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
12560     return NTK_TemplateTemplateArgument;
12561   switch (TTK) {
12562   case TTK_Struct:
12563   case TTK_Interface:
12564   case TTK_Class:
12565     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
12566   case TTK_Union:
12567     return NTK_NonUnion;
12568   case TTK_Enum:
12569     return NTK_NonEnum;
12570   }
12571   llvm_unreachable("invalid TTK");
12572 }
12573 
12574 /// \brief Determine whether a tag with a given kind is acceptable
12575 /// as a redeclaration of the given tag declaration.
12576 ///
12577 /// \returns true if the new tag kind is acceptable, false otherwise.
12578 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12579                                         TagTypeKind NewTag, bool isDefinition,
12580                                         SourceLocation NewTagLoc,
12581                                         const IdentifierInfo *Name) {
12582   // C++ [dcl.type.elab]p3:
12583   //   The class-key or enum keyword present in the
12584   //   elaborated-type-specifier shall agree in kind with the
12585   //   declaration to which the name in the elaborated-type-specifier
12586   //   refers. This rule also applies to the form of
12587   //   elaborated-type-specifier that declares a class-name or
12588   //   friend class since it can be construed as referring to the
12589   //   definition of the class. Thus, in any
12590   //   elaborated-type-specifier, the enum keyword shall be used to
12591   //   refer to an enumeration (7.2), the union class-key shall be
12592   //   used to refer to a union (clause 9), and either the class or
12593   //   struct class-key shall be used to refer to a class (clause 9)
12594   //   declared using the class or struct class-key.
12595   TagTypeKind OldTag = Previous->getTagKind();
12596   if (!isDefinition || !isClassCompatTagKind(NewTag))
12597     if (OldTag == NewTag)
12598       return true;
12599 
12600   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
12601     // Warn about the struct/class tag mismatch.
12602     bool isTemplate = false;
12603     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
12604       isTemplate = Record->getDescribedClassTemplate();
12605 
12606     if (!ActiveTemplateInstantiations.empty()) {
12607       // In a template instantiation, do not offer fix-its for tag mismatches
12608       // since they usually mess up the template instead of fixing the problem.
12609       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12610         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12611         << getRedeclDiagFromTagKind(OldTag);
12612       return true;
12613     }
12614 
12615     if (isDefinition) {
12616       // On definitions, check previous tags and issue a fix-it for each
12617       // one that doesn't match the current tag.
12618       if (Previous->getDefinition()) {
12619         // Don't suggest fix-its for redefinitions.
12620         return true;
12621       }
12622 
12623       bool previousMismatch = false;
12624       for (auto I : Previous->redecls()) {
12625         if (I->getTagKind() != NewTag) {
12626           if (!previousMismatch) {
12627             previousMismatch = true;
12628             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
12629               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12630               << getRedeclDiagFromTagKind(I->getTagKind());
12631           }
12632           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
12633             << getRedeclDiagFromTagKind(NewTag)
12634             << FixItHint::CreateReplacement(I->getInnerLocStart(),
12635                  TypeWithKeyword::getTagTypeKindName(NewTag));
12636         }
12637       }
12638       return true;
12639     }
12640 
12641     // Check for a previous definition.  If current tag and definition
12642     // are same type, do nothing.  If no definition, but disagree with
12643     // with previous tag type, give a warning, but no fix-it.
12644     const TagDecl *Redecl = Previous->getDefinition() ?
12645                             Previous->getDefinition() : Previous;
12646     if (Redecl->getTagKind() == NewTag) {
12647       return true;
12648     }
12649 
12650     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12651       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12652       << getRedeclDiagFromTagKind(OldTag);
12653     Diag(Redecl->getLocation(), diag::note_previous_use);
12654 
12655     // If there is a previous definition, suggest a fix-it.
12656     if (Previous->getDefinition()) {
12657         Diag(NewTagLoc, diag::note_struct_class_suggestion)
12658           << getRedeclDiagFromTagKind(Redecl->getTagKind())
12659           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
12660                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
12661     }
12662 
12663     return true;
12664   }
12665   return false;
12666 }
12667 
12668 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
12669 /// from an outer enclosing namespace or file scope inside a friend declaration.
12670 /// This should provide the commented out code in the following snippet:
12671 ///   namespace N {
12672 ///     struct X;
12673 ///     namespace M {
12674 ///       struct Y { friend struct /*N::*/ X; };
12675 ///     }
12676 ///   }
12677 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
12678                                          SourceLocation NameLoc) {
12679   // While the decl is in a namespace, do repeated lookup of that name and see
12680   // if we get the same namespace back.  If we do not, continue until
12681   // translation unit scope, at which point we have a fully qualified NNS.
12682   SmallVector<IdentifierInfo *, 4> Namespaces;
12683   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12684   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
12685     // This tag should be declared in a namespace, which can only be enclosed by
12686     // other namespaces.  Bail if there's an anonymous namespace in the chain.
12687     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
12688     if (!Namespace || Namespace->isAnonymousNamespace())
12689       return FixItHint();
12690     IdentifierInfo *II = Namespace->getIdentifier();
12691     Namespaces.push_back(II);
12692     NamedDecl *Lookup = SemaRef.LookupSingleName(
12693         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
12694     if (Lookup == Namespace)
12695       break;
12696   }
12697 
12698   // Once we have all the namespaces, reverse them to go outermost first, and
12699   // build an NNS.
12700   SmallString<64> Insertion;
12701   llvm::raw_svector_ostream OS(Insertion);
12702   if (DC->isTranslationUnit())
12703     OS << "::";
12704   std::reverse(Namespaces.begin(), Namespaces.end());
12705   for (auto *II : Namespaces)
12706     OS << II->getName() << "::";
12707   return FixItHint::CreateInsertion(NameLoc, Insertion);
12708 }
12709 
12710 /// \brief Determine whether a tag originally declared in context \p OldDC can
12711 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
12712 /// found a declaration in \p OldDC as a previous decl, perhaps through a
12713 /// using-declaration).
12714 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
12715                                          DeclContext *NewDC) {
12716   OldDC = OldDC->getRedeclContext();
12717   NewDC = NewDC->getRedeclContext();
12718 
12719   if (OldDC->Equals(NewDC))
12720     return true;
12721 
12722   // In MSVC mode, we allow a redeclaration if the contexts are related (either
12723   // encloses the other).
12724   if (S.getLangOpts().MSVCCompat &&
12725       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
12726     return true;
12727 
12728   return false;
12729 }
12730 
12731 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
12732 /// former case, Name will be non-null.  In the later case, Name will be null.
12733 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
12734 /// reference/declaration/definition of a tag.
12735 ///
12736 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
12737 /// trailing-type-specifier) other than one in an alias-declaration.
12738 ///
12739 /// \param SkipBody If non-null, will be set to indicate if the caller should
12740 /// skip the definition of this tag and treat it as if it were a declaration.
12741 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12742                      SourceLocation KWLoc, CXXScopeSpec &SS,
12743                      IdentifierInfo *Name, SourceLocation NameLoc,
12744                      AttributeList *Attr, AccessSpecifier AS,
12745                      SourceLocation ModulePrivateLoc,
12746                      MultiTemplateParamsArg TemplateParameterLists,
12747                      bool &OwnedDecl, bool &IsDependent,
12748                      SourceLocation ScopedEnumKWLoc,
12749                      bool ScopedEnumUsesClassTag,
12750                      TypeResult UnderlyingType,
12751                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
12752   // If this is not a definition, it must have a name.
12753   IdentifierInfo *OrigName = Name;
12754   assert((Name != nullptr || TUK == TUK_Definition) &&
12755          "Nameless record must be a definition!");
12756   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
12757 
12758   OwnedDecl = false;
12759   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12760   bool ScopedEnum = ScopedEnumKWLoc.isValid();
12761 
12762   // FIXME: Check explicit specializations more carefully.
12763   bool isExplicitSpecialization = false;
12764   bool Invalid = false;
12765 
12766   // We only need to do this matching if we have template parameters
12767   // or a scope specifier, which also conveniently avoids this work
12768   // for non-C++ cases.
12769   if (TemplateParameterLists.size() > 0 ||
12770       (SS.isNotEmpty() && TUK != TUK_Reference)) {
12771     if (TemplateParameterList *TemplateParams =
12772             MatchTemplateParametersToScopeSpecifier(
12773                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
12774                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
12775       if (Kind == TTK_Enum) {
12776         Diag(KWLoc, diag::err_enum_template);
12777         return nullptr;
12778       }
12779 
12780       if (TemplateParams->size() > 0) {
12781         // This is a declaration or definition of a class template (which may
12782         // be a member of another template).
12783 
12784         if (Invalid)
12785           return nullptr;
12786 
12787         OwnedDecl = false;
12788         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
12789                                                SS, Name, NameLoc, Attr,
12790                                                TemplateParams, AS,
12791                                                ModulePrivateLoc,
12792                                                /*FriendLoc*/SourceLocation(),
12793                                                TemplateParameterLists.size()-1,
12794                                                TemplateParameterLists.data(),
12795                                                SkipBody);
12796         return Result.get();
12797       } else {
12798         // The "template<>" header is extraneous.
12799         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12800           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12801         isExplicitSpecialization = true;
12802       }
12803     }
12804   }
12805 
12806   // Figure out the underlying type if this a enum declaration. We need to do
12807   // this early, because it's needed to detect if this is an incompatible
12808   // redeclaration.
12809   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
12810   bool EnumUnderlyingIsImplicit = false;
12811 
12812   if (Kind == TTK_Enum) {
12813     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
12814       // No underlying type explicitly specified, or we failed to parse the
12815       // type, default to int.
12816       EnumUnderlying = Context.IntTy.getTypePtr();
12817     else if (UnderlyingType.get()) {
12818       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
12819       // integral type; any cv-qualification is ignored.
12820       TypeSourceInfo *TI = nullptr;
12821       GetTypeFromParser(UnderlyingType.get(), &TI);
12822       EnumUnderlying = TI;
12823 
12824       if (CheckEnumUnderlyingType(TI))
12825         // Recover by falling back to int.
12826         EnumUnderlying = Context.IntTy.getTypePtr();
12827 
12828       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
12829                                           UPPC_FixedUnderlyingType))
12830         EnumUnderlying = Context.IntTy.getTypePtr();
12831 
12832     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12833       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
12834         // Microsoft enums are always of int type.
12835         EnumUnderlying = Context.IntTy.getTypePtr();
12836         EnumUnderlyingIsImplicit = true;
12837       }
12838     }
12839   }
12840 
12841   DeclContext *SearchDC = CurContext;
12842   DeclContext *DC = CurContext;
12843   bool isStdBadAlloc = false;
12844   bool isStdAlignValT = false;
12845 
12846   RedeclarationKind Redecl = ForRedeclaration;
12847   if (TUK == TUK_Friend || TUK == TUK_Reference)
12848     Redecl = NotForRedeclaration;
12849 
12850   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
12851   if (Name && SS.isNotEmpty()) {
12852     // We have a nested-name tag ('struct foo::bar').
12853 
12854     // Check for invalid 'foo::'.
12855     if (SS.isInvalid()) {
12856       Name = nullptr;
12857       goto CreateNewDecl;
12858     }
12859 
12860     // If this is a friend or a reference to a class in a dependent
12861     // context, don't try to make a decl for it.
12862     if (TUK == TUK_Friend || TUK == TUK_Reference) {
12863       DC = computeDeclContext(SS, false);
12864       if (!DC) {
12865         IsDependent = true;
12866         return nullptr;
12867       }
12868     } else {
12869       DC = computeDeclContext(SS, true);
12870       if (!DC) {
12871         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
12872           << SS.getRange();
12873         return nullptr;
12874       }
12875     }
12876 
12877     if (RequireCompleteDeclContext(SS, DC))
12878       return nullptr;
12879 
12880     SearchDC = DC;
12881     // Look-up name inside 'foo::'.
12882     LookupQualifiedName(Previous, DC);
12883 
12884     if (Previous.isAmbiguous())
12885       return nullptr;
12886 
12887     if (Previous.empty()) {
12888       // Name lookup did not find anything. However, if the
12889       // nested-name-specifier refers to the current instantiation,
12890       // and that current instantiation has any dependent base
12891       // classes, we might find something at instantiation time: treat
12892       // this as a dependent elaborated-type-specifier.
12893       // But this only makes any sense for reference-like lookups.
12894       if (Previous.wasNotFoundInCurrentInstantiation() &&
12895           (TUK == TUK_Reference || TUK == TUK_Friend)) {
12896         IsDependent = true;
12897         return nullptr;
12898       }
12899 
12900       // A tag 'foo::bar' must already exist.
12901       Diag(NameLoc, diag::err_not_tag_in_scope)
12902         << Kind << Name << DC << SS.getRange();
12903       Name = nullptr;
12904       Invalid = true;
12905       goto CreateNewDecl;
12906     }
12907   } else if (Name) {
12908     // C++14 [class.mem]p14:
12909     //   If T is the name of a class, then each of the following shall have a
12910     //   name different from T:
12911     //    -- every member of class T that is itself a type
12912     if (TUK != TUK_Reference && TUK != TUK_Friend &&
12913         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
12914       return nullptr;
12915 
12916     // If this is a named struct, check to see if there was a previous forward
12917     // declaration or definition.
12918     // FIXME: We're looking into outer scopes here, even when we
12919     // shouldn't be. Doing so can result in ambiguities that we
12920     // shouldn't be diagnosing.
12921     LookupName(Previous, S);
12922 
12923     // When declaring or defining a tag, ignore ambiguities introduced
12924     // by types using'ed into this scope.
12925     if (Previous.isAmbiguous() &&
12926         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
12927       LookupResult::Filter F = Previous.makeFilter();
12928       while (F.hasNext()) {
12929         NamedDecl *ND = F.next();
12930         if (!ND->getDeclContext()->getRedeclContext()->Equals(
12931                 SearchDC->getRedeclContext()))
12932           F.erase();
12933       }
12934       F.done();
12935     }
12936 
12937     // C++11 [namespace.memdef]p3:
12938     //   If the name in a friend declaration is neither qualified nor
12939     //   a template-id and the declaration is a function or an
12940     //   elaborated-type-specifier, the lookup to determine whether
12941     //   the entity has been previously declared shall not consider
12942     //   any scopes outside the innermost enclosing namespace.
12943     //
12944     // MSVC doesn't implement the above rule for types, so a friend tag
12945     // declaration may be a redeclaration of a type declared in an enclosing
12946     // scope.  They do implement this rule for friend functions.
12947     //
12948     // Does it matter that this should be by scope instead of by
12949     // semantic context?
12950     if (!Previous.empty() && TUK == TUK_Friend) {
12951       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
12952       LookupResult::Filter F = Previous.makeFilter();
12953       bool FriendSawTagOutsideEnclosingNamespace = false;
12954       while (F.hasNext()) {
12955         NamedDecl *ND = F.next();
12956         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12957         if (DC->isFileContext() &&
12958             !EnclosingNS->Encloses(ND->getDeclContext())) {
12959           if (getLangOpts().MSVCCompat)
12960             FriendSawTagOutsideEnclosingNamespace = true;
12961           else
12962             F.erase();
12963         }
12964       }
12965       F.done();
12966 
12967       // Diagnose this MSVC extension in the easy case where lookup would have
12968       // unambiguously found something outside the enclosing namespace.
12969       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
12970         NamedDecl *ND = Previous.getFoundDecl();
12971         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
12972             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
12973       }
12974     }
12975 
12976     // Note:  there used to be some attempt at recovery here.
12977     if (Previous.isAmbiguous())
12978       return nullptr;
12979 
12980     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
12981       // FIXME: This makes sure that we ignore the contexts associated
12982       // with C structs, unions, and enums when looking for a matching
12983       // tag declaration or definition. See the similar lookup tweak
12984       // in Sema::LookupName; is there a better way to deal with this?
12985       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
12986         SearchDC = SearchDC->getParent();
12987     }
12988   }
12989 
12990   if (Previous.isSingleResult() &&
12991       Previous.getFoundDecl()->isTemplateParameter()) {
12992     // Maybe we will complain about the shadowed template parameter.
12993     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
12994     // Just pretend that we didn't see the previous declaration.
12995     Previous.clear();
12996   }
12997 
12998   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
12999       DC->Equals(getStdNamespace())) {
13000     if (Name->isStr("bad_alloc")) {
13001       // This is a declaration of or a reference to "std::bad_alloc".
13002       isStdBadAlloc = true;
13003 
13004       // If std::bad_alloc has been implicitly declared (but made invisible to
13005       // name lookup), fill in this implicit declaration as the previous
13006       // declaration, so that the declarations get chained appropriately.
13007       if (Previous.empty() && StdBadAlloc)
13008         Previous.addDecl(getStdBadAlloc());
13009     } else if (Name->isStr("align_val_t")) {
13010       isStdAlignValT = true;
13011       if (Previous.empty() && StdAlignValT)
13012         Previous.addDecl(getStdAlignValT());
13013     }
13014   }
13015 
13016   // If we didn't find a previous declaration, and this is a reference
13017   // (or friend reference), move to the correct scope.  In C++, we
13018   // also need to do a redeclaration lookup there, just in case
13019   // there's a shadow friend decl.
13020   if (Name && Previous.empty() &&
13021       (TUK == TUK_Reference || TUK == TUK_Friend)) {
13022     if (Invalid) goto CreateNewDecl;
13023     assert(SS.isEmpty());
13024 
13025     if (TUK == TUK_Reference) {
13026       // C++ [basic.scope.pdecl]p5:
13027       //   -- for an elaborated-type-specifier of the form
13028       //
13029       //          class-key identifier
13030       //
13031       //      if the elaborated-type-specifier is used in the
13032       //      decl-specifier-seq or parameter-declaration-clause of a
13033       //      function defined in namespace scope, the identifier is
13034       //      declared as a class-name in the namespace that contains
13035       //      the declaration; otherwise, except as a friend
13036       //      declaration, the identifier is declared in the smallest
13037       //      non-class, non-function-prototype scope that contains the
13038       //      declaration.
13039       //
13040       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
13041       // C structs and unions.
13042       //
13043       // It is an error in C++ to declare (rather than define) an enum
13044       // type, including via an elaborated type specifier.  We'll
13045       // diagnose that later; for now, declare the enum in the same
13046       // scope as we would have picked for any other tag type.
13047       //
13048       // GNU C also supports this behavior as part of its incomplete
13049       // enum types extension, while GNU C++ does not.
13050       //
13051       // Find the context where we'll be declaring the tag.
13052       // FIXME: We would like to maintain the current DeclContext as the
13053       // lexical context,
13054       SearchDC = getTagInjectionContext(SearchDC);
13055 
13056       // Find the scope where we'll be declaring the tag.
13057       S = getTagInjectionScope(S, getLangOpts());
13058     } else {
13059       assert(TUK == TUK_Friend);
13060       // C++ [namespace.memdef]p3:
13061       //   If a friend declaration in a non-local class first declares a
13062       //   class or function, the friend class or function is a member of
13063       //   the innermost enclosing namespace.
13064       SearchDC = SearchDC->getEnclosingNamespaceContext();
13065     }
13066 
13067     // In C++, we need to do a redeclaration lookup to properly
13068     // diagnose some problems.
13069     // FIXME: redeclaration lookup is also used (with and without C++) to find a
13070     // hidden declaration so that we don't get ambiguity errors when using a
13071     // type declared by an elaborated-type-specifier.  In C that is not correct
13072     // and we should instead merge compatible types found by lookup.
13073     if (getLangOpts().CPlusPlus) {
13074       Previous.setRedeclarationKind(ForRedeclaration);
13075       LookupQualifiedName(Previous, SearchDC);
13076     } else {
13077       Previous.setRedeclarationKind(ForRedeclaration);
13078       LookupName(Previous, S);
13079     }
13080   }
13081 
13082   // If we have a known previous declaration to use, then use it.
13083   if (Previous.empty() && SkipBody && SkipBody->Previous)
13084     Previous.addDecl(SkipBody->Previous);
13085 
13086   if (!Previous.empty()) {
13087     NamedDecl *PrevDecl = Previous.getFoundDecl();
13088     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13089 
13090     // It's okay to have a tag decl in the same scope as a typedef
13091     // which hides a tag decl in the same scope.  Finding this
13092     // insanity with a redeclaration lookup can only actually happen
13093     // in C++.
13094     //
13095     // This is also okay for elaborated-type-specifiers, which is
13096     // technically forbidden by the current standard but which is
13097     // okay according to the likely resolution of an open issue;
13098     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13099     if (getLangOpts().CPlusPlus) {
13100       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13101         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13102           TagDecl *Tag = TT->getDecl();
13103           if (Tag->getDeclName() == Name &&
13104               Tag->getDeclContext()->getRedeclContext()
13105                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
13106             PrevDecl = Tag;
13107             Previous.clear();
13108             Previous.addDecl(Tag);
13109             Previous.resolveKind();
13110           }
13111         }
13112       }
13113     }
13114 
13115     // If this is a redeclaration of a using shadow declaration, it must
13116     // declare a tag in the same context. In MSVC mode, we allow a
13117     // redefinition if either context is within the other.
13118     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13119       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13120       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13121           isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
13122           !(OldTag && isAcceptableTagRedeclContext(
13123                           *this, OldTag->getDeclContext(), SearchDC))) {
13124         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13125         Diag(Shadow->getTargetDecl()->getLocation(),
13126              diag::note_using_decl_target);
13127         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13128             << 0;
13129         // Recover by ignoring the old declaration.
13130         Previous.clear();
13131         goto CreateNewDecl;
13132       }
13133     }
13134 
13135     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13136       // If this is a use of a previous tag, or if the tag is already declared
13137       // in the same scope (so that the definition/declaration completes or
13138       // rementions the tag), reuse the decl.
13139       if (TUK == TUK_Reference || TUK == TUK_Friend ||
13140           isDeclInScope(DirectPrevDecl, SearchDC, S,
13141                         SS.isNotEmpty() || isExplicitSpecialization)) {
13142         // Make sure that this wasn't declared as an enum and now used as a
13143         // struct or something similar.
13144         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13145                                           TUK == TUK_Definition, KWLoc,
13146                                           Name)) {
13147           bool SafeToContinue
13148             = (PrevTagDecl->getTagKind() != TTK_Enum &&
13149                Kind != TTK_Enum);
13150           if (SafeToContinue)
13151             Diag(KWLoc, diag::err_use_with_wrong_tag)
13152               << Name
13153               << FixItHint::CreateReplacement(SourceRange(KWLoc),
13154                                               PrevTagDecl->getKindName());
13155           else
13156             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13157           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13158 
13159           if (SafeToContinue)
13160             Kind = PrevTagDecl->getTagKind();
13161           else {
13162             // Recover by making this an anonymous redefinition.
13163             Name = nullptr;
13164             Previous.clear();
13165             Invalid = true;
13166           }
13167         }
13168 
13169         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
13170           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
13171 
13172           // If this is an elaborated-type-specifier for a scoped enumeration,
13173           // the 'class' keyword is not necessary and not permitted.
13174           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13175             if (ScopedEnum)
13176               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
13177                 << PrevEnum->isScoped()
13178                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
13179             return PrevTagDecl;
13180           }
13181 
13182           QualType EnumUnderlyingTy;
13183           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13184             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
13185           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
13186             EnumUnderlyingTy = QualType(T, 0);
13187 
13188           // All conflicts with previous declarations are recovered by
13189           // returning the previous declaration, unless this is a definition,
13190           // in which case we want the caller to bail out.
13191           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
13192                                      ScopedEnum, EnumUnderlyingTy,
13193                                      EnumUnderlyingIsImplicit, PrevEnum))
13194             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
13195         }
13196 
13197         // C++11 [class.mem]p1:
13198         //   A member shall not be declared twice in the member-specification,
13199         //   except that a nested class or member class template can be declared
13200         //   and then later defined.
13201         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
13202             S->isDeclScope(PrevDecl)) {
13203           Diag(NameLoc, diag::ext_member_redeclared);
13204           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
13205         }
13206 
13207         if (!Invalid) {
13208           // If this is a use, just return the declaration we found, unless
13209           // we have attributes.
13210           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13211             if (Attr) {
13212               // FIXME: Diagnose these attributes. For now, we create a new
13213               // declaration to hold them.
13214             } else if (TUK == TUK_Reference &&
13215                        (PrevTagDecl->getFriendObjectKind() ==
13216                             Decl::FOK_Undeclared ||
13217                         PP.getModuleContainingLocation(
13218                             PrevDecl->getLocation()) !=
13219                             PP.getModuleContainingLocation(KWLoc)) &&
13220                        SS.isEmpty()) {
13221               // This declaration is a reference to an existing entity, but
13222               // has different visibility from that entity: it either makes
13223               // a friend visible or it makes a type visible in a new module.
13224               // In either case, create a new declaration. We only do this if
13225               // the declaration would have meant the same thing if no prior
13226               // declaration were found, that is, if it was found in the same
13227               // scope where we would have injected a declaration.
13228               if (!getTagInjectionContext(CurContext)->getRedeclContext()
13229                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
13230                 return PrevTagDecl;
13231               // This is in the injected scope, create a new declaration in
13232               // that scope.
13233               S = getTagInjectionScope(S, getLangOpts());
13234             } else {
13235               return PrevTagDecl;
13236             }
13237           }
13238 
13239           // Diagnose attempts to redefine a tag.
13240           if (TUK == TUK_Definition) {
13241             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
13242               // If we're defining a specialization and the previous definition
13243               // is from an implicit instantiation, don't emit an error
13244               // here; we'll catch this in the general case below.
13245               bool IsExplicitSpecializationAfterInstantiation = false;
13246               if (isExplicitSpecialization) {
13247                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
13248                   IsExplicitSpecializationAfterInstantiation =
13249                     RD->getTemplateSpecializationKind() !=
13250                     TSK_ExplicitSpecialization;
13251                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
13252                   IsExplicitSpecializationAfterInstantiation =
13253                     ED->getTemplateSpecializationKind() !=
13254                     TSK_ExplicitSpecialization;
13255               }
13256 
13257               NamedDecl *Hidden = nullptr;
13258               if (SkipBody && getLangOpts().CPlusPlus &&
13259                   !hasVisibleDefinition(Def, &Hidden)) {
13260                 // There is a definition of this tag, but it is not visible. We
13261                 // explicitly make use of C++'s one definition rule here, and
13262                 // assume that this definition is identical to the hidden one
13263                 // we already have. Make the existing definition visible and
13264                 // use it in place of this one.
13265                 SkipBody->ShouldSkip = true;
13266                 makeMergedDefinitionVisible(Hidden, KWLoc);
13267                 return Def;
13268               } else if (!IsExplicitSpecializationAfterInstantiation) {
13269                 // A redeclaration in function prototype scope in C isn't
13270                 // visible elsewhere, so merely issue a warning.
13271                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
13272                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
13273                 else
13274                   Diag(NameLoc, diag::err_redefinition) << Name;
13275                 Diag(Def->getLocation(), diag::note_previous_definition);
13276                 // If this is a redefinition, recover by making this
13277                 // struct be anonymous, which will make any later
13278                 // references get the previous definition.
13279                 Name = nullptr;
13280                 Previous.clear();
13281                 Invalid = true;
13282               }
13283             } else {
13284               // If the type is currently being defined, complain
13285               // about a nested redefinition.
13286               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
13287               if (TD->isBeingDefined()) {
13288                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
13289                 Diag(PrevTagDecl->getLocation(),
13290                      diag::note_previous_definition);
13291                 Name = nullptr;
13292                 Previous.clear();
13293                 Invalid = true;
13294               }
13295             }
13296 
13297             // Okay, this is definition of a previously declared or referenced
13298             // tag. We're going to create a new Decl for it.
13299           }
13300 
13301           // Okay, we're going to make a redeclaration.  If this is some kind
13302           // of reference, make sure we build the redeclaration in the same DC
13303           // as the original, and ignore the current access specifier.
13304           if (TUK == TUK_Friend || TUK == TUK_Reference) {
13305             SearchDC = PrevTagDecl->getDeclContext();
13306             AS = AS_none;
13307           }
13308         }
13309         // If we get here we have (another) forward declaration or we
13310         // have a definition.  Just create a new decl.
13311 
13312       } else {
13313         // If we get here, this is a definition of a new tag type in a nested
13314         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
13315         // new decl/type.  We set PrevDecl to NULL so that the entities
13316         // have distinct types.
13317         Previous.clear();
13318       }
13319       // If we get here, we're going to create a new Decl. If PrevDecl
13320       // is non-NULL, it's a definition of the tag declared by
13321       // PrevDecl. If it's NULL, we have a new definition.
13322 
13323     // Otherwise, PrevDecl is not a tag, but was found with tag
13324     // lookup.  This is only actually possible in C++, where a few
13325     // things like templates still live in the tag namespace.
13326     } else {
13327       // Use a better diagnostic if an elaborated-type-specifier
13328       // found the wrong kind of type on the first
13329       // (non-redeclaration) lookup.
13330       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
13331           !Previous.isForRedeclaration()) {
13332         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13333         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
13334                                                        << Kind;
13335         Diag(PrevDecl->getLocation(), diag::note_declared_at);
13336         Invalid = true;
13337 
13338       // Otherwise, only diagnose if the declaration is in scope.
13339       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
13340                                 SS.isNotEmpty() || isExplicitSpecialization)) {
13341         // do nothing
13342 
13343       // Diagnose implicit declarations introduced by elaborated types.
13344       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
13345         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13346         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
13347         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13348         Invalid = true;
13349 
13350       // Otherwise it's a declaration.  Call out a particularly common
13351       // case here.
13352       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13353         unsigned Kind = 0;
13354         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
13355         Diag(NameLoc, diag::err_tag_definition_of_typedef)
13356           << Name << Kind << TND->getUnderlyingType();
13357         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13358         Invalid = true;
13359 
13360       // Otherwise, diagnose.
13361       } else {
13362         // The tag name clashes with something else in the target scope,
13363         // issue an error and recover by making this tag be anonymous.
13364         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
13365         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13366         Name = nullptr;
13367         Invalid = true;
13368       }
13369 
13370       // The existing declaration isn't relevant to us; we're in a
13371       // new scope, so clear out the previous declaration.
13372       Previous.clear();
13373     }
13374   }
13375 
13376 CreateNewDecl:
13377 
13378   TagDecl *PrevDecl = nullptr;
13379   if (Previous.isSingleResult())
13380     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
13381 
13382   // If there is an identifier, use the location of the identifier as the
13383   // location of the decl, otherwise use the location of the struct/union
13384   // keyword.
13385   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13386 
13387   // Otherwise, create a new declaration. If there is a previous
13388   // declaration of the same entity, the two will be linked via
13389   // PrevDecl.
13390   TagDecl *New;
13391 
13392   bool IsForwardReference = false;
13393   if (Kind == TTK_Enum) {
13394     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13395     // enum X { A, B, C } D;    D should chain to X.
13396     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
13397                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
13398                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
13399 
13400     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
13401       StdAlignValT = cast<EnumDecl>(New);
13402 
13403     // If this is an undefined enum, warn.
13404     if (TUK != TUK_Definition && !Invalid) {
13405       TagDecl *Def;
13406       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
13407           cast<EnumDecl>(New)->isFixed()) {
13408         // C++0x: 7.2p2: opaque-enum-declaration.
13409         // Conflicts are diagnosed above. Do nothing.
13410       }
13411       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
13412         Diag(Loc, diag::ext_forward_ref_enum_def)
13413           << New;
13414         Diag(Def->getLocation(), diag::note_previous_definition);
13415       } else {
13416         unsigned DiagID = diag::ext_forward_ref_enum;
13417         if (getLangOpts().MSVCCompat)
13418           DiagID = diag::ext_ms_forward_ref_enum;
13419         else if (getLangOpts().CPlusPlus)
13420           DiagID = diag::err_forward_ref_enum;
13421         Diag(Loc, DiagID);
13422 
13423         // If this is a forward-declared reference to an enumeration, make a
13424         // note of it; we won't actually be introducing the declaration into
13425         // the declaration context.
13426         if (TUK == TUK_Reference)
13427           IsForwardReference = true;
13428       }
13429     }
13430 
13431     if (EnumUnderlying) {
13432       EnumDecl *ED = cast<EnumDecl>(New);
13433       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13434         ED->setIntegerTypeSourceInfo(TI);
13435       else
13436         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
13437       ED->setPromotionType(ED->getIntegerType());
13438     }
13439   } else {
13440     // struct/union/class
13441 
13442     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13443     // struct X { int A; } D;    D should chain to X.
13444     if (getLangOpts().CPlusPlus) {
13445       // FIXME: Look for a way to use RecordDecl for simple structs.
13446       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13447                                   cast_or_null<CXXRecordDecl>(PrevDecl));
13448 
13449       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
13450         StdBadAlloc = cast<CXXRecordDecl>(New);
13451     } else
13452       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13453                                cast_or_null<RecordDecl>(PrevDecl));
13454   }
13455 
13456   // C++11 [dcl.type]p3:
13457   //   A type-specifier-seq shall not define a class or enumeration [...].
13458   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
13459     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
13460       << Context.getTagDeclType(New);
13461     Invalid = true;
13462   }
13463 
13464   // Maybe add qualifier info.
13465   if (SS.isNotEmpty()) {
13466     if (SS.isSet()) {
13467       // If this is either a declaration or a definition, check the
13468       // nested-name-specifier against the current context. We don't do this
13469       // for explicit specializations, because they have similar checking
13470       // (with more specific diagnostics) in the call to
13471       // CheckMemberSpecialization, below.
13472       if (!isExplicitSpecialization &&
13473           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
13474           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
13475         Invalid = true;
13476 
13477       New->setQualifierInfo(SS.getWithLocInContext(Context));
13478       if (TemplateParameterLists.size() > 0) {
13479         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
13480       }
13481     }
13482     else
13483       Invalid = true;
13484   }
13485 
13486   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13487     // Add alignment attributes if necessary; these attributes are checked when
13488     // the ASTContext lays out the structure.
13489     //
13490     // It is important for implementing the correct semantics that this
13491     // happen here (in act on tag decl). The #pragma pack stack is
13492     // maintained as a result of parser callbacks which can occur at
13493     // many points during the parsing of a struct declaration (because
13494     // the #pragma tokens are effectively skipped over during the
13495     // parsing of the struct).
13496     if (TUK == TUK_Definition) {
13497       AddAlignmentAttributesForRecord(RD);
13498       AddMsStructLayoutForRecord(RD);
13499     }
13500   }
13501 
13502   if (ModulePrivateLoc.isValid()) {
13503     if (isExplicitSpecialization)
13504       Diag(New->getLocation(), diag::err_module_private_specialization)
13505         << 2
13506         << FixItHint::CreateRemoval(ModulePrivateLoc);
13507     // __module_private__ does not apply to local classes. However, we only
13508     // diagnose this as an error when the declaration specifiers are
13509     // freestanding. Here, we just ignore the __module_private__.
13510     else if (!SearchDC->isFunctionOrMethod())
13511       New->setModulePrivate();
13512   }
13513 
13514   // If this is a specialization of a member class (of a class template),
13515   // check the specialization.
13516   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
13517     Invalid = true;
13518 
13519   // If we're declaring or defining a tag in function prototype scope in C,
13520   // note that this type can only be used within the function and add it to
13521   // the list of decls to inject into the function definition scope.
13522   if ((Name || Kind == TTK_Enum) &&
13523       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
13524     if (getLangOpts().CPlusPlus) {
13525       // C++ [dcl.fct]p6:
13526       //   Types shall not be defined in return or parameter types.
13527       if (TUK == TUK_Definition && !IsTypeSpecifier) {
13528         Diag(Loc, diag::err_type_defined_in_param_type)
13529             << Name;
13530         Invalid = true;
13531       }
13532     } else if (!PrevDecl) {
13533       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
13534     }
13535   }
13536 
13537   if (Invalid)
13538     New->setInvalidDecl();
13539 
13540   if (Attr)
13541     ProcessDeclAttributeList(S, New, Attr);
13542 
13543   // Set the lexical context. If the tag has a C++ scope specifier, the
13544   // lexical context will be different from the semantic context.
13545   New->setLexicalDeclContext(CurContext);
13546 
13547   // Mark this as a friend decl if applicable.
13548   // In Microsoft mode, a friend declaration also acts as a forward
13549   // declaration so we always pass true to setObjectOfFriendDecl to make
13550   // the tag name visible.
13551   if (TUK == TUK_Friend)
13552     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
13553 
13554   // Set the access specifier.
13555   if (!Invalid && SearchDC->isRecord())
13556     SetMemberAccessSpecifier(New, PrevDecl, AS);
13557 
13558   if (TUK == TUK_Definition)
13559     New->startDefinition();
13560 
13561   // If this has an identifier, add it to the scope stack.
13562   if (TUK == TUK_Friend) {
13563     // We might be replacing an existing declaration in the lookup tables;
13564     // if so, borrow its access specifier.
13565     if (PrevDecl)
13566       New->setAccess(PrevDecl->getAccess());
13567 
13568     DeclContext *DC = New->getDeclContext()->getRedeclContext();
13569     DC->makeDeclVisibleInContext(New);
13570     if (Name) // can be null along some error paths
13571       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13572         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
13573   } else if (Name) {
13574     S = getNonFieldDeclScope(S);
13575     PushOnScopeChains(New, S, !IsForwardReference);
13576     if (IsForwardReference)
13577       SearchDC->makeDeclVisibleInContext(New);
13578   } else {
13579     CurContext->addDecl(New);
13580   }
13581 
13582   // If this is the C FILE type, notify the AST context.
13583   if (IdentifierInfo *II = New->getIdentifier())
13584     if (!New->isInvalidDecl() &&
13585         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
13586         II->isStr("FILE"))
13587       Context.setFILEDecl(New);
13588 
13589   if (PrevDecl)
13590     mergeDeclAttributes(New, PrevDecl);
13591 
13592   // If there's a #pragma GCC visibility in scope, set the visibility of this
13593   // record.
13594   AddPushedVisibilityAttribute(New);
13595 
13596   OwnedDecl = true;
13597   // In C++, don't return an invalid declaration. We can't recover well from
13598   // the cases where we make the type anonymous.
13599   if (Invalid && getLangOpts().CPlusPlus) {
13600     if (New->isBeingDefined())
13601       if (auto RD = dyn_cast<RecordDecl>(New))
13602         RD->completeDefinition();
13603     return nullptr;
13604   } else {
13605     return New;
13606   }
13607 }
13608 
13609 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
13610   AdjustDeclIfTemplate(TagD);
13611   TagDecl *Tag = cast<TagDecl>(TagD);
13612 
13613   // Enter the tag context.
13614   PushDeclContext(S, Tag);
13615 
13616   ActOnDocumentableDecl(TagD);
13617 
13618   // If there's a #pragma GCC visibility in scope, set the visibility of this
13619   // record.
13620   AddPushedVisibilityAttribute(Tag);
13621 }
13622 
13623 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
13624   assert(isa<ObjCContainerDecl>(IDecl) &&
13625          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
13626   DeclContext *OCD = cast<DeclContext>(IDecl);
13627   assert(getContainingDC(OCD) == CurContext &&
13628       "The next DeclContext should be lexically contained in the current one.");
13629   CurContext = OCD;
13630   return IDecl;
13631 }
13632 
13633 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
13634                                            SourceLocation FinalLoc,
13635                                            bool IsFinalSpelledSealed,
13636                                            SourceLocation LBraceLoc) {
13637   AdjustDeclIfTemplate(TagD);
13638   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
13639 
13640   FieldCollector->StartClass();
13641 
13642   if (!Record->getIdentifier())
13643     return;
13644 
13645   if (FinalLoc.isValid())
13646     Record->addAttr(new (Context)
13647                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
13648 
13649   // C++ [class]p2:
13650   //   [...] The class-name is also inserted into the scope of the
13651   //   class itself; this is known as the injected-class-name. For
13652   //   purposes of access checking, the injected-class-name is treated
13653   //   as if it were a public member name.
13654   CXXRecordDecl *InjectedClassName
13655     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
13656                             Record->getLocStart(), Record->getLocation(),
13657                             Record->getIdentifier(),
13658                             /*PrevDecl=*/nullptr,
13659                             /*DelayTypeCreation=*/true);
13660   Context.getTypeDeclType(InjectedClassName, Record);
13661   InjectedClassName->setImplicit();
13662   InjectedClassName->setAccess(AS_public);
13663   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
13664       InjectedClassName->setDescribedClassTemplate(Template);
13665   PushOnScopeChains(InjectedClassName, S);
13666   assert(InjectedClassName->isInjectedClassName() &&
13667          "Broken injected-class-name");
13668 }
13669 
13670 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
13671                                     SourceRange BraceRange) {
13672   AdjustDeclIfTemplate(TagD);
13673   TagDecl *Tag = cast<TagDecl>(TagD);
13674   Tag->setBraceRange(BraceRange);
13675 
13676   // Make sure we "complete" the definition even it is invalid.
13677   if (Tag->isBeingDefined()) {
13678     assert(Tag->isInvalidDecl() && "We should already have completed it");
13679     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13680       RD->completeDefinition();
13681   }
13682 
13683   if (isa<CXXRecordDecl>(Tag))
13684     FieldCollector->FinishClass();
13685 
13686   // Exit this scope of this tag's definition.
13687   PopDeclContext();
13688 
13689   if (getCurLexicalContext()->isObjCContainer() &&
13690       Tag->getDeclContext()->isFileContext())
13691     Tag->setTopLevelDeclInObjCContainer();
13692 
13693   // Notify the consumer that we've defined a tag.
13694   if (!Tag->isInvalidDecl())
13695     Consumer.HandleTagDeclDefinition(Tag);
13696 }
13697 
13698 void Sema::ActOnObjCContainerFinishDefinition() {
13699   // Exit this scope of this interface definition.
13700   PopDeclContext();
13701 }
13702 
13703 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
13704   assert(DC == CurContext && "Mismatch of container contexts");
13705   OriginalLexicalContext = DC;
13706   ActOnObjCContainerFinishDefinition();
13707 }
13708 
13709 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
13710   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
13711   OriginalLexicalContext = nullptr;
13712 }
13713 
13714 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
13715   AdjustDeclIfTemplate(TagD);
13716   TagDecl *Tag = cast<TagDecl>(TagD);
13717   Tag->setInvalidDecl();
13718 
13719   // Make sure we "complete" the definition even it is invalid.
13720   if (Tag->isBeingDefined()) {
13721     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13722       RD->completeDefinition();
13723   }
13724 
13725   // We're undoing ActOnTagStartDefinition here, not
13726   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
13727   // the FieldCollector.
13728 
13729   PopDeclContext();
13730 }
13731 
13732 // Note that FieldName may be null for anonymous bitfields.
13733 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
13734                                 IdentifierInfo *FieldName,
13735                                 QualType FieldTy, bool IsMsStruct,
13736                                 Expr *BitWidth, bool *ZeroWidth) {
13737   // Default to true; that shouldn't confuse checks for emptiness
13738   if (ZeroWidth)
13739     *ZeroWidth = true;
13740 
13741   // C99 6.7.2.1p4 - verify the field type.
13742   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
13743   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
13744     // Handle incomplete types with specific error.
13745     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
13746       return ExprError();
13747     if (FieldName)
13748       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
13749         << FieldName << FieldTy << BitWidth->getSourceRange();
13750     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
13751       << FieldTy << BitWidth->getSourceRange();
13752   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
13753                                              UPPC_BitFieldWidth))
13754     return ExprError();
13755 
13756   // If the bit-width is type- or value-dependent, don't try to check
13757   // it now.
13758   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
13759     return BitWidth;
13760 
13761   llvm::APSInt Value;
13762   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
13763   if (ICE.isInvalid())
13764     return ICE;
13765   BitWidth = ICE.get();
13766 
13767   if (Value != 0 && ZeroWidth)
13768     *ZeroWidth = false;
13769 
13770   // Zero-width bitfield is ok for anonymous field.
13771   if (Value == 0 && FieldName)
13772     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
13773 
13774   if (Value.isSigned() && Value.isNegative()) {
13775     if (FieldName)
13776       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
13777                << FieldName << Value.toString(10);
13778     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
13779       << Value.toString(10);
13780   }
13781 
13782   if (!FieldTy->isDependentType()) {
13783     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
13784     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
13785     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
13786 
13787     // Over-wide bitfields are an error in C or when using the MSVC bitfield
13788     // ABI.
13789     bool CStdConstraintViolation =
13790         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
13791     bool MSBitfieldViolation =
13792         Value.ugt(TypeStorageSize) &&
13793         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
13794     if (CStdConstraintViolation || MSBitfieldViolation) {
13795       unsigned DiagWidth =
13796           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
13797       if (FieldName)
13798         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
13799                << FieldName << (unsigned)Value.getZExtValue()
13800                << !CStdConstraintViolation << DiagWidth;
13801 
13802       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
13803              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
13804              << DiagWidth;
13805     }
13806 
13807     // Warn on types where the user might conceivably expect to get all
13808     // specified bits as value bits: that's all integral types other than
13809     // 'bool'.
13810     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
13811       if (FieldName)
13812         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
13813             << FieldName << (unsigned)Value.getZExtValue()
13814             << (unsigned)TypeWidth;
13815       else
13816         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
13817             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
13818     }
13819   }
13820 
13821   return BitWidth;
13822 }
13823 
13824 /// ActOnField - Each field of a C struct/union is passed into this in order
13825 /// to create a FieldDecl object for it.
13826 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
13827                        Declarator &D, Expr *BitfieldWidth) {
13828   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
13829                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
13830                                /*InitStyle=*/ICIS_NoInit, AS_public);
13831   return Res;
13832 }
13833 
13834 /// HandleField - Analyze a field of a C struct or a C++ data member.
13835 ///
13836 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
13837                              SourceLocation DeclStart,
13838                              Declarator &D, Expr *BitWidth,
13839                              InClassInitStyle InitStyle,
13840                              AccessSpecifier AS) {
13841   if (D.isDecompositionDeclarator()) {
13842     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
13843     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
13844       << Decomp.getSourceRange();
13845     return nullptr;
13846   }
13847 
13848   IdentifierInfo *II = D.getIdentifier();
13849   SourceLocation Loc = DeclStart;
13850   if (II) Loc = D.getIdentifierLoc();
13851 
13852   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13853   QualType T = TInfo->getType();
13854   if (getLangOpts().CPlusPlus) {
13855     CheckExtraCXXDefaultArguments(D);
13856 
13857     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13858                                         UPPC_DataMemberType)) {
13859       D.setInvalidType();
13860       T = Context.IntTy;
13861       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13862     }
13863   }
13864 
13865   // TR 18037 does not allow fields to be declared with address spaces.
13866   if (T.getQualifiers().hasAddressSpace()) {
13867     Diag(Loc, diag::err_field_with_address_space);
13868     D.setInvalidType();
13869   }
13870 
13871   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
13872   // used as structure or union field: image, sampler, event or block types.
13873   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
13874                           T->isSamplerT() || T->isBlockPointerType())) {
13875     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
13876     D.setInvalidType();
13877   }
13878 
13879   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13880 
13881   if (D.getDeclSpec().isInlineSpecified())
13882     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
13883         << getLangOpts().CPlusPlus1z;
13884   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13885     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13886          diag::err_invalid_thread)
13887       << DeclSpec::getSpecifierName(TSCS);
13888 
13889   // Check to see if this name was declared as a member previously
13890   NamedDecl *PrevDecl = nullptr;
13891   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13892   LookupName(Previous, S);
13893   switch (Previous.getResultKind()) {
13894     case LookupResult::Found:
13895     case LookupResult::FoundUnresolvedValue:
13896       PrevDecl = Previous.getAsSingle<NamedDecl>();
13897       break;
13898 
13899     case LookupResult::FoundOverloaded:
13900       PrevDecl = Previous.getRepresentativeDecl();
13901       break;
13902 
13903     case LookupResult::NotFound:
13904     case LookupResult::NotFoundInCurrentInstantiation:
13905     case LookupResult::Ambiguous:
13906       break;
13907   }
13908   Previous.suppressDiagnostics();
13909 
13910   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13911     // Maybe we will complain about the shadowed template parameter.
13912     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13913     // Just pretend that we didn't see the previous declaration.
13914     PrevDecl = nullptr;
13915   }
13916 
13917   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13918     PrevDecl = nullptr;
13919 
13920   bool Mutable
13921     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
13922   SourceLocation TSSL = D.getLocStart();
13923   FieldDecl *NewFD
13924     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
13925                      TSSL, AS, PrevDecl, &D);
13926 
13927   if (NewFD->isInvalidDecl())
13928     Record->setInvalidDecl();
13929 
13930   if (D.getDeclSpec().isModulePrivateSpecified())
13931     NewFD->setModulePrivate();
13932 
13933   if (NewFD->isInvalidDecl() && PrevDecl) {
13934     // Don't introduce NewFD into scope; there's already something
13935     // with the same name in the same scope.
13936   } else if (II) {
13937     PushOnScopeChains(NewFD, S);
13938   } else
13939     Record->addDecl(NewFD);
13940 
13941   return NewFD;
13942 }
13943 
13944 /// \brief Build a new FieldDecl and check its well-formedness.
13945 ///
13946 /// This routine builds a new FieldDecl given the fields name, type,
13947 /// record, etc. \p PrevDecl should refer to any previous declaration
13948 /// with the same name and in the same scope as the field to be
13949 /// created.
13950 ///
13951 /// \returns a new FieldDecl.
13952 ///
13953 /// \todo The Declarator argument is a hack. It will be removed once
13954 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
13955                                 TypeSourceInfo *TInfo,
13956                                 RecordDecl *Record, SourceLocation Loc,
13957                                 bool Mutable, Expr *BitWidth,
13958                                 InClassInitStyle InitStyle,
13959                                 SourceLocation TSSL,
13960                                 AccessSpecifier AS, NamedDecl *PrevDecl,
13961                                 Declarator *D) {
13962   IdentifierInfo *II = Name.getAsIdentifierInfo();
13963   bool InvalidDecl = false;
13964   if (D) InvalidDecl = D->isInvalidType();
13965 
13966   // If we receive a broken type, recover by assuming 'int' and
13967   // marking this declaration as invalid.
13968   if (T.isNull()) {
13969     InvalidDecl = true;
13970     T = Context.IntTy;
13971   }
13972 
13973   QualType EltTy = Context.getBaseElementType(T);
13974   if (!EltTy->isDependentType()) {
13975     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
13976       // Fields of incomplete type force their record to be invalid.
13977       Record->setInvalidDecl();
13978       InvalidDecl = true;
13979     } else {
13980       NamedDecl *Def;
13981       EltTy->isIncompleteType(&Def);
13982       if (Def && Def->isInvalidDecl()) {
13983         Record->setInvalidDecl();
13984         InvalidDecl = true;
13985       }
13986     }
13987   }
13988 
13989   // OpenCL v1.2 s6.9.c: bitfields are not supported.
13990   if (BitWidth && getLangOpts().OpenCL) {
13991     Diag(Loc, diag::err_opencl_bitfields);
13992     InvalidDecl = true;
13993   }
13994 
13995   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13996   // than a variably modified type.
13997   if (!InvalidDecl && T->isVariablyModifiedType()) {
13998     bool SizeIsNegative;
13999     llvm::APSInt Oversized;
14000 
14001     TypeSourceInfo *FixedTInfo =
14002       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
14003                                                     SizeIsNegative,
14004                                                     Oversized);
14005     if (FixedTInfo) {
14006       Diag(Loc, diag::warn_illegal_constant_array_size);
14007       TInfo = FixedTInfo;
14008       T = FixedTInfo->getType();
14009     } else {
14010       if (SizeIsNegative)
14011         Diag(Loc, diag::err_typecheck_negative_array_size);
14012       else if (Oversized.getBoolValue())
14013         Diag(Loc, diag::err_array_too_large)
14014           << Oversized.toString(10);
14015       else
14016         Diag(Loc, diag::err_typecheck_field_variable_size);
14017       InvalidDecl = true;
14018     }
14019   }
14020 
14021   // Fields can not have abstract class types
14022   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
14023                                              diag::err_abstract_type_in_decl,
14024                                              AbstractFieldType))
14025     InvalidDecl = true;
14026 
14027   bool ZeroWidth = false;
14028   if (InvalidDecl)
14029     BitWidth = nullptr;
14030   // If this is declared as a bit-field, check the bit-field.
14031   if (BitWidth) {
14032     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
14033                               &ZeroWidth).get();
14034     if (!BitWidth) {
14035       InvalidDecl = true;
14036       BitWidth = nullptr;
14037       ZeroWidth = false;
14038     }
14039   }
14040 
14041   // Check that 'mutable' is consistent with the type of the declaration.
14042   if (!InvalidDecl && Mutable) {
14043     unsigned DiagID = 0;
14044     if (T->isReferenceType())
14045       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
14046                                         : diag::err_mutable_reference;
14047     else if (T.isConstQualified())
14048       DiagID = diag::err_mutable_const;
14049 
14050     if (DiagID) {
14051       SourceLocation ErrLoc = Loc;
14052       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
14053         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
14054       Diag(ErrLoc, DiagID);
14055       if (DiagID != diag::ext_mutable_reference) {
14056         Mutable = false;
14057         InvalidDecl = true;
14058       }
14059     }
14060   }
14061 
14062   // C++11 [class.union]p8 (DR1460):
14063   //   At most one variant member of a union may have a
14064   //   brace-or-equal-initializer.
14065   if (InitStyle != ICIS_NoInit)
14066     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
14067 
14068   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
14069                                        BitWidth, Mutable, InitStyle);
14070   if (InvalidDecl)
14071     NewFD->setInvalidDecl();
14072 
14073   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
14074     Diag(Loc, diag::err_duplicate_member) << II;
14075     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14076     NewFD->setInvalidDecl();
14077   }
14078 
14079   if (!InvalidDecl && getLangOpts().CPlusPlus) {
14080     if (Record->isUnion()) {
14081       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14082         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14083         if (RDecl->getDefinition()) {
14084           // C++ [class.union]p1: An object of a class with a non-trivial
14085           // constructor, a non-trivial copy constructor, a non-trivial
14086           // destructor, or a non-trivial copy assignment operator
14087           // cannot be a member of a union, nor can an array of such
14088           // objects.
14089           if (CheckNontrivialField(NewFD))
14090             NewFD->setInvalidDecl();
14091         }
14092       }
14093 
14094       // C++ [class.union]p1: If a union contains a member of reference type,
14095       // the program is ill-formed, except when compiling with MSVC extensions
14096       // enabled.
14097       if (EltTy->isReferenceType()) {
14098         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14099                                     diag::ext_union_member_of_reference_type :
14100                                     diag::err_union_member_of_reference_type)
14101           << NewFD->getDeclName() << EltTy;
14102         if (!getLangOpts().MicrosoftExt)
14103           NewFD->setInvalidDecl();
14104       }
14105     }
14106   }
14107 
14108   // FIXME: We need to pass in the attributes given an AST
14109   // representation, not a parser representation.
14110   if (D) {
14111     // FIXME: The current scope is almost... but not entirely... correct here.
14112     ProcessDeclAttributes(getCurScope(), NewFD, *D);
14113 
14114     if (NewFD->hasAttrs())
14115       CheckAlignasUnderalignment(NewFD);
14116   }
14117 
14118   // In auto-retain/release, infer strong retension for fields of
14119   // retainable type.
14120   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
14121     NewFD->setInvalidDecl();
14122 
14123   if (T.isObjCGCWeak())
14124     Diag(Loc, diag::warn_attribute_weak_on_field);
14125 
14126   NewFD->setAccess(AS);
14127   return NewFD;
14128 }
14129 
14130 bool Sema::CheckNontrivialField(FieldDecl *FD) {
14131   assert(FD);
14132   assert(getLangOpts().CPlusPlus && "valid check only for C++");
14133 
14134   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
14135     return false;
14136 
14137   QualType EltTy = Context.getBaseElementType(FD->getType());
14138   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14139     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
14140     if (RDecl->getDefinition()) {
14141       // We check for copy constructors before constructors
14142       // because otherwise we'll never get complaints about
14143       // copy constructors.
14144 
14145       CXXSpecialMember member = CXXInvalid;
14146       // We're required to check for any non-trivial constructors. Since the
14147       // implicit default constructor is suppressed if there are any
14148       // user-declared constructors, we just need to check that there is a
14149       // trivial default constructor and a trivial copy constructor. (We don't
14150       // worry about move constructors here, since this is a C++98 check.)
14151       if (RDecl->hasNonTrivialCopyConstructor())
14152         member = CXXCopyConstructor;
14153       else if (!RDecl->hasTrivialDefaultConstructor())
14154         member = CXXDefaultConstructor;
14155       else if (RDecl->hasNonTrivialCopyAssignment())
14156         member = CXXCopyAssignment;
14157       else if (RDecl->hasNonTrivialDestructor())
14158         member = CXXDestructor;
14159 
14160       if (member != CXXInvalid) {
14161         if (!getLangOpts().CPlusPlus11 &&
14162             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
14163           // Objective-C++ ARC: it is an error to have a non-trivial field of
14164           // a union. However, system headers in Objective-C programs
14165           // occasionally have Objective-C lifetime objects within unions,
14166           // and rather than cause the program to fail, we make those
14167           // members unavailable.
14168           SourceLocation Loc = FD->getLocation();
14169           if (getSourceManager().isInSystemHeader(Loc)) {
14170             if (!FD->hasAttr<UnavailableAttr>())
14171               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14172                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
14173             return false;
14174           }
14175         }
14176 
14177         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
14178                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
14179                diag::err_illegal_union_or_anon_struct_member)
14180           << FD->getParent()->isUnion() << FD->getDeclName() << member;
14181         DiagnoseNontrivial(RDecl, member);
14182         return !getLangOpts().CPlusPlus11;
14183       }
14184     }
14185   }
14186 
14187   return false;
14188 }
14189 
14190 /// TranslateIvarVisibility - Translate visibility from a token ID to an
14191 ///  AST enum value.
14192 static ObjCIvarDecl::AccessControl
14193 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
14194   switch (ivarVisibility) {
14195   default: llvm_unreachable("Unknown visitibility kind");
14196   case tok::objc_private: return ObjCIvarDecl::Private;
14197   case tok::objc_public: return ObjCIvarDecl::Public;
14198   case tok::objc_protected: return ObjCIvarDecl::Protected;
14199   case tok::objc_package: return ObjCIvarDecl::Package;
14200   }
14201 }
14202 
14203 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
14204 /// in order to create an IvarDecl object for it.
14205 Decl *Sema::ActOnIvar(Scope *S,
14206                                 SourceLocation DeclStart,
14207                                 Declarator &D, Expr *BitfieldWidth,
14208                                 tok::ObjCKeywordKind Visibility) {
14209 
14210   IdentifierInfo *II = D.getIdentifier();
14211   Expr *BitWidth = (Expr*)BitfieldWidth;
14212   SourceLocation Loc = DeclStart;
14213   if (II) Loc = D.getIdentifierLoc();
14214 
14215   // FIXME: Unnamed fields can be handled in various different ways, for
14216   // example, unnamed unions inject all members into the struct namespace!
14217 
14218   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14219   QualType T = TInfo->getType();
14220 
14221   if (BitWidth) {
14222     // 6.7.2.1p3, 6.7.2.1p4
14223     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
14224     if (!BitWidth)
14225       D.setInvalidType();
14226   } else {
14227     // Not a bitfield.
14228 
14229     // validate II.
14230 
14231   }
14232   if (T->isReferenceType()) {
14233     Diag(Loc, diag::err_ivar_reference_type);
14234     D.setInvalidType();
14235   }
14236   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14237   // than a variably modified type.
14238   else if (T->isVariablyModifiedType()) {
14239     Diag(Loc, diag::err_typecheck_ivar_variable_size);
14240     D.setInvalidType();
14241   }
14242 
14243   // Get the visibility (access control) for this ivar.
14244   ObjCIvarDecl::AccessControl ac =
14245     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
14246                                         : ObjCIvarDecl::None;
14247   // Must set ivar's DeclContext to its enclosing interface.
14248   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
14249   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
14250     return nullptr;
14251   ObjCContainerDecl *EnclosingContext;
14252   if (ObjCImplementationDecl *IMPDecl =
14253       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14254     if (LangOpts.ObjCRuntime.isFragile()) {
14255     // Case of ivar declared in an implementation. Context is that of its class.
14256       EnclosingContext = IMPDecl->getClassInterface();
14257       assert(EnclosingContext && "Implementation has no class interface!");
14258     }
14259     else
14260       EnclosingContext = EnclosingDecl;
14261   } else {
14262     if (ObjCCategoryDecl *CDecl =
14263         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14264       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
14265         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
14266         return nullptr;
14267       }
14268     }
14269     EnclosingContext = EnclosingDecl;
14270   }
14271 
14272   // Construct the decl.
14273   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
14274                                              DeclStart, Loc, II, T,
14275                                              TInfo, ac, (Expr *)BitfieldWidth);
14276 
14277   if (II) {
14278     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
14279                                            ForRedeclaration);
14280     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
14281         && !isa<TagDecl>(PrevDecl)) {
14282       Diag(Loc, diag::err_duplicate_member) << II;
14283       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14284       NewID->setInvalidDecl();
14285     }
14286   }
14287 
14288   // Process attributes attached to the ivar.
14289   ProcessDeclAttributes(S, NewID, D);
14290 
14291   if (D.isInvalidType())
14292     NewID->setInvalidDecl();
14293 
14294   // In ARC, infer 'retaining' for ivars of retainable type.
14295   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
14296     NewID->setInvalidDecl();
14297 
14298   if (D.getDeclSpec().isModulePrivateSpecified())
14299     NewID->setModulePrivate();
14300 
14301   if (II) {
14302     // FIXME: When interfaces are DeclContexts, we'll need to add
14303     // these to the interface.
14304     S->AddDecl(NewID);
14305     IdResolver.AddDecl(NewID);
14306   }
14307 
14308   if (LangOpts.ObjCRuntime.isNonFragile() &&
14309       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
14310     Diag(Loc, diag::warn_ivars_in_interface);
14311 
14312   return NewID;
14313 }
14314 
14315 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
14316 /// class and class extensions. For every class \@interface and class
14317 /// extension \@interface, if the last ivar is a bitfield of any type,
14318 /// then add an implicit `char :0` ivar to the end of that interface.
14319 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
14320                              SmallVectorImpl<Decl *> &AllIvarDecls) {
14321   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
14322     return;
14323 
14324   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
14325   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
14326 
14327   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
14328     return;
14329   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
14330   if (!ID) {
14331     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
14332       if (!CD->IsClassExtension())
14333         return;
14334     }
14335     // No need to add this to end of @implementation.
14336     else
14337       return;
14338   }
14339   // All conditions are met. Add a new bitfield to the tail end of ivars.
14340   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
14341   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
14342 
14343   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
14344                               DeclLoc, DeclLoc, nullptr,
14345                               Context.CharTy,
14346                               Context.getTrivialTypeSourceInfo(Context.CharTy,
14347                                                                DeclLoc),
14348                               ObjCIvarDecl::Private, BW,
14349                               true);
14350   AllIvarDecls.push_back(Ivar);
14351 }
14352 
14353 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
14354                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
14355                        SourceLocation RBrac, AttributeList *Attr) {
14356   assert(EnclosingDecl && "missing record or interface decl");
14357 
14358   // If this is an Objective-C @implementation or category and we have
14359   // new fields here we should reset the layout of the interface since
14360   // it will now change.
14361   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
14362     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
14363     switch (DC->getKind()) {
14364     default: break;
14365     case Decl::ObjCCategory:
14366       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
14367       break;
14368     case Decl::ObjCImplementation:
14369       Context.
14370         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
14371       break;
14372     }
14373   }
14374 
14375   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
14376 
14377   // Start counting up the number of named members; make sure to include
14378   // members of anonymous structs and unions in the total.
14379   unsigned NumNamedMembers = 0;
14380   if (Record) {
14381     for (const auto *I : Record->decls()) {
14382       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
14383         if (IFD->getDeclName())
14384           ++NumNamedMembers;
14385     }
14386   }
14387 
14388   // Verify that all the fields are okay.
14389   SmallVector<FieldDecl*, 32> RecFields;
14390 
14391   bool ARCErrReported = false;
14392   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
14393        i != end; ++i) {
14394     FieldDecl *FD = cast<FieldDecl>(*i);
14395 
14396     // Get the type for the field.
14397     const Type *FDTy = FD->getType().getTypePtr();
14398 
14399     if (!FD->isAnonymousStructOrUnion()) {
14400       // Remember all fields written by the user.
14401       RecFields.push_back(FD);
14402     }
14403 
14404     // If the field is already invalid for some reason, don't emit more
14405     // diagnostics about it.
14406     if (FD->isInvalidDecl()) {
14407       EnclosingDecl->setInvalidDecl();
14408       continue;
14409     }
14410 
14411     // C99 6.7.2.1p2:
14412     //   A structure or union shall not contain a member with
14413     //   incomplete or function type (hence, a structure shall not
14414     //   contain an instance of itself, but may contain a pointer to
14415     //   an instance of itself), except that the last member of a
14416     //   structure with more than one named member may have incomplete
14417     //   array type; such a structure (and any union containing,
14418     //   possibly recursively, a member that is such a structure)
14419     //   shall not be a member of a structure or an element of an
14420     //   array.
14421     if (FDTy->isFunctionType()) {
14422       // Field declared as a function.
14423       Diag(FD->getLocation(), diag::err_field_declared_as_function)
14424         << FD->getDeclName();
14425       FD->setInvalidDecl();
14426       EnclosingDecl->setInvalidDecl();
14427       continue;
14428     } else if (FDTy->isIncompleteArrayType() && Record &&
14429                ((i + 1 == Fields.end() && !Record->isUnion()) ||
14430                 ((getLangOpts().MicrosoftExt ||
14431                   getLangOpts().CPlusPlus) &&
14432                  (i + 1 == Fields.end() || Record->isUnion())))) {
14433       // Flexible array member.
14434       // Microsoft and g++ is more permissive regarding flexible array.
14435       // It will accept flexible array in union and also
14436       // as the sole element of a struct/class.
14437       unsigned DiagID = 0;
14438       if (Record->isUnion())
14439         DiagID = getLangOpts().MicrosoftExt
14440                      ? diag::ext_flexible_array_union_ms
14441                      : getLangOpts().CPlusPlus
14442                            ? diag::ext_flexible_array_union_gnu
14443                            : diag::err_flexible_array_union;
14444       else if (NumNamedMembers < 1)
14445         DiagID = getLangOpts().MicrosoftExt
14446                      ? diag::ext_flexible_array_empty_aggregate_ms
14447                      : getLangOpts().CPlusPlus
14448                            ? diag::ext_flexible_array_empty_aggregate_gnu
14449                            : diag::err_flexible_array_empty_aggregate;
14450 
14451       if (DiagID)
14452         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
14453                                         << Record->getTagKind();
14454       // While the layout of types that contain virtual bases is not specified
14455       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
14456       // virtual bases after the derived members.  This would make a flexible
14457       // array member declared at the end of an object not adjacent to the end
14458       // of the type.
14459       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
14460         if (RD->getNumVBases() != 0)
14461           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
14462             << FD->getDeclName() << Record->getTagKind();
14463       if (!getLangOpts().C99)
14464         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
14465           << FD->getDeclName() << Record->getTagKind();
14466 
14467       // If the element type has a non-trivial destructor, we would not
14468       // implicitly destroy the elements, so disallow it for now.
14469       //
14470       // FIXME: GCC allows this. We should probably either implicitly delete
14471       // the destructor of the containing class, or just allow this.
14472       QualType BaseElem = Context.getBaseElementType(FD->getType());
14473       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
14474         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
14475           << FD->getDeclName() << FD->getType();
14476         FD->setInvalidDecl();
14477         EnclosingDecl->setInvalidDecl();
14478         continue;
14479       }
14480       // Okay, we have a legal flexible array member at the end of the struct.
14481       Record->setHasFlexibleArrayMember(true);
14482     } else if (!FDTy->isDependentType() &&
14483                RequireCompleteType(FD->getLocation(), FD->getType(),
14484                                    diag::err_field_incomplete)) {
14485       // Incomplete type
14486       FD->setInvalidDecl();
14487       EnclosingDecl->setInvalidDecl();
14488       continue;
14489     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
14490       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
14491         // A type which contains a flexible array member is considered to be a
14492         // flexible array member.
14493         Record->setHasFlexibleArrayMember(true);
14494         if (!Record->isUnion()) {
14495           // If this is a struct/class and this is not the last element, reject
14496           // it.  Note that GCC supports variable sized arrays in the middle of
14497           // structures.
14498           if (i + 1 != Fields.end())
14499             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
14500               << FD->getDeclName() << FD->getType();
14501           else {
14502             // We support flexible arrays at the end of structs in
14503             // other structs as an extension.
14504             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
14505               << FD->getDeclName();
14506           }
14507         }
14508       }
14509       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
14510           RequireNonAbstractType(FD->getLocation(), FD->getType(),
14511                                  diag::err_abstract_type_in_decl,
14512                                  AbstractIvarType)) {
14513         // Ivars can not have abstract class types
14514         FD->setInvalidDecl();
14515       }
14516       if (Record && FDTTy->getDecl()->hasObjectMember())
14517         Record->setHasObjectMember(true);
14518       if (Record && FDTTy->getDecl()->hasVolatileMember())
14519         Record->setHasVolatileMember(true);
14520     } else if (FDTy->isObjCObjectType()) {
14521       /// A field cannot be an Objective-c object
14522       Diag(FD->getLocation(), diag::err_statically_allocated_object)
14523         << FixItHint::CreateInsertion(FD->getLocation(), "*");
14524       QualType T = Context.getObjCObjectPointerType(FD->getType());
14525       FD->setType(T);
14526     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
14527                (!getLangOpts().CPlusPlus || Record->isUnion())) {
14528       // It's an error in ARC if a field has lifetime.
14529       // We don't want to report this in a system header, though,
14530       // so we just make the field unavailable.
14531       // FIXME: that's really not sufficient; we need to make the type
14532       // itself invalid to, say, initialize or copy.
14533       QualType T = FD->getType();
14534       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
14535       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
14536         SourceLocation loc = FD->getLocation();
14537         if (getSourceManager().isInSystemHeader(loc)) {
14538           if (!FD->hasAttr<UnavailableAttr>()) {
14539             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14540                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
14541           }
14542         } else {
14543           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
14544             << T->isBlockPointerType() << Record->getTagKind();
14545         }
14546         ARCErrReported = true;
14547       }
14548     } else if (getLangOpts().ObjC1 &&
14549                getLangOpts().getGC() != LangOptions::NonGC &&
14550                Record && !Record->hasObjectMember()) {
14551       if (FD->getType()->isObjCObjectPointerType() ||
14552           FD->getType().isObjCGCStrong())
14553         Record->setHasObjectMember(true);
14554       else if (Context.getAsArrayType(FD->getType())) {
14555         QualType BaseType = Context.getBaseElementType(FD->getType());
14556         if (BaseType->isRecordType() &&
14557             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
14558           Record->setHasObjectMember(true);
14559         else if (BaseType->isObjCObjectPointerType() ||
14560                  BaseType.isObjCGCStrong())
14561                Record->setHasObjectMember(true);
14562       }
14563     }
14564     if (Record && FD->getType().isVolatileQualified())
14565       Record->setHasVolatileMember(true);
14566     // Keep track of the number of named members.
14567     if (FD->getIdentifier())
14568       ++NumNamedMembers;
14569   }
14570 
14571   // Okay, we successfully defined 'Record'.
14572   if (Record) {
14573     bool Completed = false;
14574     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14575       if (!CXXRecord->isInvalidDecl()) {
14576         // Set access bits correctly on the directly-declared conversions.
14577         for (CXXRecordDecl::conversion_iterator
14578                I = CXXRecord->conversion_begin(),
14579                E = CXXRecord->conversion_end(); I != E; ++I)
14580           I.setAccess((*I)->getAccess());
14581       }
14582 
14583       if (!CXXRecord->isDependentType()) {
14584         if (CXXRecord->hasUserDeclaredDestructor()) {
14585           // Adjust user-defined destructor exception spec.
14586           if (getLangOpts().CPlusPlus11)
14587             AdjustDestructorExceptionSpec(CXXRecord,
14588                                           CXXRecord->getDestructor());
14589         }
14590 
14591         if (!CXXRecord->isInvalidDecl()) {
14592           // Add any implicitly-declared members to this class.
14593           AddImplicitlyDeclaredMembersToClass(CXXRecord);
14594 
14595           // If we have virtual base classes, we may end up finding multiple
14596           // final overriders for a given virtual function. Check for this
14597           // problem now.
14598           if (CXXRecord->getNumVBases()) {
14599             CXXFinalOverriderMap FinalOverriders;
14600             CXXRecord->getFinalOverriders(FinalOverriders);
14601 
14602             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
14603                                              MEnd = FinalOverriders.end();
14604                  M != MEnd; ++M) {
14605               for (OverridingMethods::iterator SO = M->second.begin(),
14606                                             SOEnd = M->second.end();
14607                    SO != SOEnd; ++SO) {
14608                 assert(SO->second.size() > 0 &&
14609                        "Virtual function without overridding functions?");
14610                 if (SO->second.size() == 1)
14611                   continue;
14612 
14613                 // C++ [class.virtual]p2:
14614                 //   In a derived class, if a virtual member function of a base
14615                 //   class subobject has more than one final overrider the
14616                 //   program is ill-formed.
14617                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
14618                   << (const NamedDecl *)M->first << Record;
14619                 Diag(M->first->getLocation(),
14620                      diag::note_overridden_virtual_function);
14621                 for (OverridingMethods::overriding_iterator
14622                           OM = SO->second.begin(),
14623                        OMEnd = SO->second.end();
14624                      OM != OMEnd; ++OM)
14625                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
14626                     << (const NamedDecl *)M->first << OM->Method->getParent();
14627 
14628                 Record->setInvalidDecl();
14629               }
14630             }
14631             CXXRecord->completeDefinition(&FinalOverriders);
14632             Completed = true;
14633           }
14634         }
14635       }
14636     }
14637 
14638     if (!Completed)
14639       Record->completeDefinition();
14640 
14641     // We may have deferred checking for a deleted destructor. Check now.
14642     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14643       auto *Dtor = CXXRecord->getDestructor();
14644       if (Dtor && Dtor->isImplicit() &&
14645           ShouldDeleteSpecialMember(Dtor, CXXDestructor))
14646         SetDeclDeleted(Dtor, CXXRecord->getLocation());
14647     }
14648 
14649     if (Record->hasAttrs()) {
14650       CheckAlignasUnderalignment(Record);
14651 
14652       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
14653         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
14654                                            IA->getRange(), IA->getBestCase(),
14655                                            IA->getSemanticSpelling());
14656     }
14657 
14658     // Check if the structure/union declaration is a type that can have zero
14659     // size in C. For C this is a language extension, for C++ it may cause
14660     // compatibility problems.
14661     bool CheckForZeroSize;
14662     if (!getLangOpts().CPlusPlus) {
14663       CheckForZeroSize = true;
14664     } else {
14665       // For C++ filter out types that cannot be referenced in C code.
14666       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
14667       CheckForZeroSize =
14668           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
14669           !CXXRecord->isDependentType() &&
14670           CXXRecord->isCLike();
14671     }
14672     if (CheckForZeroSize) {
14673       bool ZeroSize = true;
14674       bool IsEmpty = true;
14675       unsigned NonBitFields = 0;
14676       for (RecordDecl::field_iterator I = Record->field_begin(),
14677                                       E = Record->field_end();
14678            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
14679         IsEmpty = false;
14680         if (I->isUnnamedBitfield()) {
14681           if (I->getBitWidthValue(Context) > 0)
14682             ZeroSize = false;
14683         } else {
14684           ++NonBitFields;
14685           QualType FieldType = I->getType();
14686           if (FieldType->isIncompleteType() ||
14687               !Context.getTypeSizeInChars(FieldType).isZero())
14688             ZeroSize = false;
14689         }
14690       }
14691 
14692       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
14693       // allowed in C++, but warn if its declaration is inside
14694       // extern "C" block.
14695       if (ZeroSize) {
14696         Diag(RecLoc, getLangOpts().CPlusPlus ?
14697                          diag::warn_zero_size_struct_union_in_extern_c :
14698                          diag::warn_zero_size_struct_union_compat)
14699           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
14700       }
14701 
14702       // Structs without named members are extension in C (C99 6.7.2.1p7),
14703       // but are accepted by GCC.
14704       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
14705         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
14706                                diag::ext_no_named_members_in_struct_union)
14707           << Record->isUnion();
14708       }
14709     }
14710   } else {
14711     ObjCIvarDecl **ClsFields =
14712       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
14713     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
14714       ID->setEndOfDefinitionLoc(RBrac);
14715       // Add ivar's to class's DeclContext.
14716       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14717         ClsFields[i]->setLexicalDeclContext(ID);
14718         ID->addDecl(ClsFields[i]);
14719       }
14720       // Must enforce the rule that ivars in the base classes may not be
14721       // duplicates.
14722       if (ID->getSuperClass())
14723         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
14724     } else if (ObjCImplementationDecl *IMPDecl =
14725                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14726       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
14727       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
14728         // Ivar declared in @implementation never belongs to the implementation.
14729         // Only it is in implementation's lexical context.
14730         ClsFields[I]->setLexicalDeclContext(IMPDecl);
14731       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
14732       IMPDecl->setIvarLBraceLoc(LBrac);
14733       IMPDecl->setIvarRBraceLoc(RBrac);
14734     } else if (ObjCCategoryDecl *CDecl =
14735                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14736       // case of ivars in class extension; all other cases have been
14737       // reported as errors elsewhere.
14738       // FIXME. Class extension does not have a LocEnd field.
14739       // CDecl->setLocEnd(RBrac);
14740       // Add ivar's to class extension's DeclContext.
14741       // Diagnose redeclaration of private ivars.
14742       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
14743       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14744         if (IDecl) {
14745           if (const ObjCIvarDecl *ClsIvar =
14746               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
14747             Diag(ClsFields[i]->getLocation(),
14748                  diag::err_duplicate_ivar_declaration);
14749             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
14750             continue;
14751           }
14752           for (const auto *Ext : IDecl->known_extensions()) {
14753             if (const ObjCIvarDecl *ClsExtIvar
14754                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
14755               Diag(ClsFields[i]->getLocation(),
14756                    diag::err_duplicate_ivar_declaration);
14757               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
14758               continue;
14759             }
14760           }
14761         }
14762         ClsFields[i]->setLexicalDeclContext(CDecl);
14763         CDecl->addDecl(ClsFields[i]);
14764       }
14765       CDecl->setIvarLBraceLoc(LBrac);
14766       CDecl->setIvarRBraceLoc(RBrac);
14767     }
14768   }
14769 
14770   if (Attr)
14771     ProcessDeclAttributeList(S, Record, Attr);
14772 }
14773 
14774 /// \brief Determine whether the given integral value is representable within
14775 /// the given type T.
14776 static bool isRepresentableIntegerValue(ASTContext &Context,
14777                                         llvm::APSInt &Value,
14778                                         QualType T) {
14779   assert(T->isIntegralType(Context) && "Integral type required!");
14780   unsigned BitWidth = Context.getIntWidth(T);
14781 
14782   if (Value.isUnsigned() || Value.isNonNegative()) {
14783     if (T->isSignedIntegerOrEnumerationType())
14784       --BitWidth;
14785     return Value.getActiveBits() <= BitWidth;
14786   }
14787   return Value.getMinSignedBits() <= BitWidth;
14788 }
14789 
14790 // \brief Given an integral type, return the next larger integral type
14791 // (or a NULL type of no such type exists).
14792 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
14793   // FIXME: Int128/UInt128 support, which also needs to be introduced into
14794   // enum checking below.
14795   assert(T->isIntegralType(Context) && "Integral type required!");
14796   const unsigned NumTypes = 4;
14797   QualType SignedIntegralTypes[NumTypes] = {
14798     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
14799   };
14800   QualType UnsignedIntegralTypes[NumTypes] = {
14801     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
14802     Context.UnsignedLongLongTy
14803   };
14804 
14805   unsigned BitWidth = Context.getTypeSize(T);
14806   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
14807                                                         : UnsignedIntegralTypes;
14808   for (unsigned I = 0; I != NumTypes; ++I)
14809     if (Context.getTypeSize(Types[I]) > BitWidth)
14810       return Types[I];
14811 
14812   return QualType();
14813 }
14814 
14815 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
14816                                           EnumConstantDecl *LastEnumConst,
14817                                           SourceLocation IdLoc,
14818                                           IdentifierInfo *Id,
14819                                           Expr *Val) {
14820   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14821   llvm::APSInt EnumVal(IntWidth);
14822   QualType EltTy;
14823 
14824   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
14825     Val = nullptr;
14826 
14827   if (Val)
14828     Val = DefaultLvalueConversion(Val).get();
14829 
14830   if (Val) {
14831     if (Enum->isDependentType() || Val->isTypeDependent())
14832       EltTy = Context.DependentTy;
14833     else {
14834       SourceLocation ExpLoc;
14835       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
14836           !getLangOpts().MSVCCompat) {
14837         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
14838         // constant-expression in the enumerator-definition shall be a converted
14839         // constant expression of the underlying type.
14840         EltTy = Enum->getIntegerType();
14841         ExprResult Converted =
14842           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
14843                                            CCEK_Enumerator);
14844         if (Converted.isInvalid())
14845           Val = nullptr;
14846         else
14847           Val = Converted.get();
14848       } else if (!Val->isValueDependent() &&
14849                  !(Val = VerifyIntegerConstantExpression(Val,
14850                                                          &EnumVal).get())) {
14851         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
14852       } else {
14853         if (Enum->isFixed()) {
14854           EltTy = Enum->getIntegerType();
14855 
14856           // In Obj-C and Microsoft mode, require the enumeration value to be
14857           // representable in the underlying type of the enumeration. In C++11,
14858           // we perform a non-narrowing conversion as part of converted constant
14859           // expression checking.
14860           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14861             if (getLangOpts().MSVCCompat) {
14862               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
14863               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
14864             } else
14865               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
14866           } else
14867             Val = ImpCastExprToType(Val, EltTy,
14868                                     EltTy->isBooleanType() ?
14869                                     CK_IntegralToBoolean : CK_IntegralCast)
14870                     .get();
14871         } else if (getLangOpts().CPlusPlus) {
14872           // C++11 [dcl.enum]p5:
14873           //   If the underlying type is not fixed, the type of each enumerator
14874           //   is the type of its initializing value:
14875           //     - If an initializer is specified for an enumerator, the
14876           //       initializing value has the same type as the expression.
14877           EltTy = Val->getType();
14878         } else {
14879           // C99 6.7.2.2p2:
14880           //   The expression that defines the value of an enumeration constant
14881           //   shall be an integer constant expression that has a value
14882           //   representable as an int.
14883 
14884           // Complain if the value is not representable in an int.
14885           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
14886             Diag(IdLoc, diag::ext_enum_value_not_int)
14887               << EnumVal.toString(10) << Val->getSourceRange()
14888               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
14889           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
14890             // Force the type of the expression to 'int'.
14891             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
14892           }
14893           EltTy = Val->getType();
14894         }
14895       }
14896     }
14897   }
14898 
14899   if (!Val) {
14900     if (Enum->isDependentType())
14901       EltTy = Context.DependentTy;
14902     else if (!LastEnumConst) {
14903       // C++0x [dcl.enum]p5:
14904       //   If the underlying type is not fixed, the type of each enumerator
14905       //   is the type of its initializing value:
14906       //     - If no initializer is specified for the first enumerator, the
14907       //       initializing value has an unspecified integral type.
14908       //
14909       // GCC uses 'int' for its unspecified integral type, as does
14910       // C99 6.7.2.2p3.
14911       if (Enum->isFixed()) {
14912         EltTy = Enum->getIntegerType();
14913       }
14914       else {
14915         EltTy = Context.IntTy;
14916       }
14917     } else {
14918       // Assign the last value + 1.
14919       EnumVal = LastEnumConst->getInitVal();
14920       ++EnumVal;
14921       EltTy = LastEnumConst->getType();
14922 
14923       // Check for overflow on increment.
14924       if (EnumVal < LastEnumConst->getInitVal()) {
14925         // C++0x [dcl.enum]p5:
14926         //   If the underlying type is not fixed, the type of each enumerator
14927         //   is the type of its initializing value:
14928         //
14929         //     - Otherwise the type of the initializing value is the same as
14930         //       the type of the initializing value of the preceding enumerator
14931         //       unless the incremented value is not representable in that type,
14932         //       in which case the type is an unspecified integral type
14933         //       sufficient to contain the incremented value. If no such type
14934         //       exists, the program is ill-formed.
14935         QualType T = getNextLargerIntegralType(Context, EltTy);
14936         if (T.isNull() || Enum->isFixed()) {
14937           // There is no integral type larger enough to represent this
14938           // value. Complain, then allow the value to wrap around.
14939           EnumVal = LastEnumConst->getInitVal();
14940           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
14941           ++EnumVal;
14942           if (Enum->isFixed())
14943             // When the underlying type is fixed, this is ill-formed.
14944             Diag(IdLoc, diag::err_enumerator_wrapped)
14945               << EnumVal.toString(10)
14946               << EltTy;
14947           else
14948             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
14949               << EnumVal.toString(10);
14950         } else {
14951           EltTy = T;
14952         }
14953 
14954         // Retrieve the last enumerator's value, extent that type to the
14955         // type that is supposed to be large enough to represent the incremented
14956         // value, then increment.
14957         EnumVal = LastEnumConst->getInitVal();
14958         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14959         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
14960         ++EnumVal;
14961 
14962         // If we're not in C++, diagnose the overflow of enumerator values,
14963         // which in C99 means that the enumerator value is not representable in
14964         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
14965         // permits enumerator values that are representable in some larger
14966         // integral type.
14967         if (!getLangOpts().CPlusPlus && !T.isNull())
14968           Diag(IdLoc, diag::warn_enum_value_overflow);
14969       } else if (!getLangOpts().CPlusPlus &&
14970                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14971         // Enforce C99 6.7.2.2p2 even when we compute the next value.
14972         Diag(IdLoc, diag::ext_enum_value_not_int)
14973           << EnumVal.toString(10) << 1;
14974       }
14975     }
14976   }
14977 
14978   if (!EltTy->isDependentType()) {
14979     // Make the enumerator value match the signedness and size of the
14980     // enumerator's type.
14981     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
14982     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14983   }
14984 
14985   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
14986                                   Val, EnumVal);
14987 }
14988 
14989 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
14990                                                 SourceLocation IILoc) {
14991   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
14992       !getLangOpts().CPlusPlus)
14993     return SkipBodyInfo();
14994 
14995   // We have an anonymous enum definition. Look up the first enumerator to
14996   // determine if we should merge the definition with an existing one and
14997   // skip the body.
14998   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
14999                                          ForRedeclaration);
15000   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
15001   if (!PrevECD)
15002     return SkipBodyInfo();
15003 
15004   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
15005   NamedDecl *Hidden;
15006   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
15007     SkipBodyInfo Skip;
15008     Skip.Previous = Hidden;
15009     return Skip;
15010   }
15011 
15012   return SkipBodyInfo();
15013 }
15014 
15015 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
15016                               SourceLocation IdLoc, IdentifierInfo *Id,
15017                               AttributeList *Attr,
15018                               SourceLocation EqualLoc, Expr *Val) {
15019   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
15020   EnumConstantDecl *LastEnumConst =
15021     cast_or_null<EnumConstantDecl>(lastEnumConst);
15022 
15023   // The scope passed in may not be a decl scope.  Zip up the scope tree until
15024   // we find one that is.
15025   S = getNonFieldDeclScope(S);
15026 
15027   // Verify that there isn't already something declared with this name in this
15028   // scope.
15029   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
15030                                          ForRedeclaration);
15031   if (PrevDecl && PrevDecl->isTemplateParameter()) {
15032     // Maybe we will complain about the shadowed template parameter.
15033     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
15034     // Just pretend that we didn't see the previous declaration.
15035     PrevDecl = nullptr;
15036   }
15037 
15038   // C++ [class.mem]p15:
15039   // If T is the name of a class, then each of the following shall have a name
15040   // different from T:
15041   // - every enumerator of every member of class T that is an unscoped
15042   // enumerated type
15043   if (!TheEnumDecl->isScoped())
15044     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
15045                             DeclarationNameInfo(Id, IdLoc));
15046 
15047   EnumConstantDecl *New =
15048     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
15049   if (!New)
15050     return nullptr;
15051 
15052   if (PrevDecl) {
15053     // When in C++, we may get a TagDecl with the same name; in this case the
15054     // enum constant will 'hide' the tag.
15055     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
15056            "Received TagDecl when not in C++!");
15057     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
15058         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
15059       if (isa<EnumConstantDecl>(PrevDecl))
15060         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
15061       else
15062         Diag(IdLoc, diag::err_redefinition) << Id;
15063       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
15064       return nullptr;
15065     }
15066   }
15067 
15068   // Process attributes.
15069   if (Attr) ProcessDeclAttributeList(S, New, Attr);
15070 
15071   // Register this decl in the current scope stack.
15072   New->setAccess(TheEnumDecl->getAccess());
15073   PushOnScopeChains(New, S);
15074 
15075   ActOnDocumentableDecl(New);
15076 
15077   return New;
15078 }
15079 
15080 // Returns true when the enum initial expression does not trigger the
15081 // duplicate enum warning.  A few common cases are exempted as follows:
15082 // Element2 = Element1
15083 // Element2 = Element1 + 1
15084 // Element2 = Element1 - 1
15085 // Where Element2 and Element1 are from the same enum.
15086 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
15087   Expr *InitExpr = ECD->getInitExpr();
15088   if (!InitExpr)
15089     return true;
15090   InitExpr = InitExpr->IgnoreImpCasts();
15091 
15092   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
15093     if (!BO->isAdditiveOp())
15094       return true;
15095     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
15096     if (!IL)
15097       return true;
15098     if (IL->getValue() != 1)
15099       return true;
15100 
15101     InitExpr = BO->getLHS();
15102   }
15103 
15104   // This checks if the elements are from the same enum.
15105   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
15106   if (!DRE)
15107     return true;
15108 
15109   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
15110   if (!EnumConstant)
15111     return true;
15112 
15113   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
15114       Enum)
15115     return true;
15116 
15117   return false;
15118 }
15119 
15120 namespace {
15121 struct DupKey {
15122   int64_t val;
15123   bool isTombstoneOrEmptyKey;
15124   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
15125     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
15126 };
15127 
15128 static DupKey GetDupKey(const llvm::APSInt& Val) {
15129   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
15130                 false);
15131 }
15132 
15133 struct DenseMapInfoDupKey {
15134   static DupKey getEmptyKey() { return DupKey(0, true); }
15135   static DupKey getTombstoneKey() { return DupKey(1, true); }
15136   static unsigned getHashValue(const DupKey Key) {
15137     return (unsigned)(Key.val * 37);
15138   }
15139   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
15140     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
15141            LHS.val == RHS.val;
15142   }
15143 };
15144 } // end anonymous namespace
15145 
15146 // Emits a warning when an element is implicitly set a value that
15147 // a previous element has already been set to.
15148 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
15149                                         EnumDecl *Enum,
15150                                         QualType EnumType) {
15151   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
15152     return;
15153   // Avoid anonymous enums
15154   if (!Enum->getIdentifier())
15155     return;
15156 
15157   // Only check for small enums.
15158   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
15159     return;
15160 
15161   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
15162   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
15163 
15164   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
15165   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
15166           ValueToVectorMap;
15167 
15168   DuplicatesVector DupVector;
15169   ValueToVectorMap EnumMap;
15170 
15171   // Populate the EnumMap with all values represented by enum constants without
15172   // an initialier.
15173   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15174     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
15175 
15176     // Null EnumConstantDecl means a previous diagnostic has been emitted for
15177     // this constant.  Skip this enum since it may be ill-formed.
15178     if (!ECD) {
15179       return;
15180     }
15181 
15182     if (ECD->getInitExpr())
15183       continue;
15184 
15185     DupKey Key = GetDupKey(ECD->getInitVal());
15186     DeclOrVector &Entry = EnumMap[Key];
15187 
15188     // First time encountering this value.
15189     if (Entry.isNull())
15190       Entry = ECD;
15191   }
15192 
15193   // Create vectors for any values that has duplicates.
15194   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15195     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
15196     if (!ValidDuplicateEnum(ECD, Enum))
15197       continue;
15198 
15199     DupKey Key = GetDupKey(ECD->getInitVal());
15200 
15201     DeclOrVector& Entry = EnumMap[Key];
15202     if (Entry.isNull())
15203       continue;
15204 
15205     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
15206       // Ensure constants are different.
15207       if (D == ECD)
15208         continue;
15209 
15210       // Create new vector and push values onto it.
15211       ECDVector *Vec = new ECDVector();
15212       Vec->push_back(D);
15213       Vec->push_back(ECD);
15214 
15215       // Update entry to point to the duplicates vector.
15216       Entry = Vec;
15217 
15218       // Store the vector somewhere we can consult later for quick emission of
15219       // diagnostics.
15220       DupVector.push_back(Vec);
15221       continue;
15222     }
15223 
15224     ECDVector *Vec = Entry.get<ECDVector*>();
15225     // Make sure constants are not added more than once.
15226     if (*Vec->begin() == ECD)
15227       continue;
15228 
15229     Vec->push_back(ECD);
15230   }
15231 
15232   // Emit diagnostics.
15233   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
15234                                   DupVectorEnd = DupVector.end();
15235        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
15236     ECDVector *Vec = *DupVectorIter;
15237     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
15238 
15239     // Emit warning for one enum constant.
15240     ECDVector::iterator I = Vec->begin();
15241     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
15242       << (*I)->getName() << (*I)->getInitVal().toString(10)
15243       << (*I)->getSourceRange();
15244     ++I;
15245 
15246     // Emit one note for each of the remaining enum constants with
15247     // the same value.
15248     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
15249       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
15250         << (*I)->getName() << (*I)->getInitVal().toString(10)
15251         << (*I)->getSourceRange();
15252     delete Vec;
15253   }
15254 }
15255 
15256 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
15257                              bool AllowMask) const {
15258   assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
15259   assert(ED->isCompleteDefinition() && "expected enum definition");
15260 
15261   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
15262   llvm::APInt &FlagBits = R.first->second;
15263 
15264   if (R.second) {
15265     for (auto *E : ED->enumerators()) {
15266       const auto &EVal = E->getInitVal();
15267       // Only single-bit enumerators introduce new flag values.
15268       if (EVal.isPowerOf2())
15269         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
15270     }
15271   }
15272 
15273   // A value is in a flag enum if either its bits are a subset of the enum's
15274   // flag bits (the first condition) or we are allowing masks and the same is
15275   // true of its complement (the second condition). When masks are allowed, we
15276   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
15277   //
15278   // While it's true that any value could be used as a mask, the assumption is
15279   // that a mask will have all of the insignificant bits set. Anything else is
15280   // likely a logic error.
15281   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
15282   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
15283 }
15284 
15285 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
15286                          Decl *EnumDeclX,
15287                          ArrayRef<Decl *> Elements,
15288                          Scope *S, AttributeList *Attr) {
15289   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
15290   QualType EnumType = Context.getTypeDeclType(Enum);
15291 
15292   if (Attr)
15293     ProcessDeclAttributeList(S, Enum, Attr);
15294 
15295   if (Enum->isDependentType()) {
15296     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15297       EnumConstantDecl *ECD =
15298         cast_or_null<EnumConstantDecl>(Elements[i]);
15299       if (!ECD) continue;
15300 
15301       ECD->setType(EnumType);
15302     }
15303 
15304     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
15305     return;
15306   }
15307 
15308   // TODO: If the result value doesn't fit in an int, it must be a long or long
15309   // long value.  ISO C does not support this, but GCC does as an extension,
15310   // emit a warning.
15311   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15312   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
15313   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
15314 
15315   // Verify that all the values are okay, compute the size of the values, and
15316   // reverse the list.
15317   unsigned NumNegativeBits = 0;
15318   unsigned NumPositiveBits = 0;
15319 
15320   // Keep track of whether all elements have type int.
15321   bool AllElementsInt = true;
15322 
15323   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15324     EnumConstantDecl *ECD =
15325       cast_or_null<EnumConstantDecl>(Elements[i]);
15326     if (!ECD) continue;  // Already issued a diagnostic.
15327 
15328     const llvm::APSInt &InitVal = ECD->getInitVal();
15329 
15330     // Keep track of the size of positive and negative values.
15331     if (InitVal.isUnsigned() || InitVal.isNonNegative())
15332       NumPositiveBits = std::max(NumPositiveBits,
15333                                  (unsigned)InitVal.getActiveBits());
15334     else
15335       NumNegativeBits = std::max(NumNegativeBits,
15336                                  (unsigned)InitVal.getMinSignedBits());
15337 
15338     // Keep track of whether every enum element has type int (very commmon).
15339     if (AllElementsInt)
15340       AllElementsInt = ECD->getType() == Context.IntTy;
15341   }
15342 
15343   // Figure out the type that should be used for this enum.
15344   QualType BestType;
15345   unsigned BestWidth;
15346 
15347   // C++0x N3000 [conv.prom]p3:
15348   //   An rvalue of an unscoped enumeration type whose underlying
15349   //   type is not fixed can be converted to an rvalue of the first
15350   //   of the following types that can represent all the values of
15351   //   the enumeration: int, unsigned int, long int, unsigned long
15352   //   int, long long int, or unsigned long long int.
15353   // C99 6.4.4.3p2:
15354   //   An identifier declared as an enumeration constant has type int.
15355   // The C99 rule is modified by a gcc extension
15356   QualType BestPromotionType;
15357 
15358   bool Packed = Enum->hasAttr<PackedAttr>();
15359   // -fshort-enums is the equivalent to specifying the packed attribute on all
15360   // enum definitions.
15361   if (LangOpts.ShortEnums)
15362     Packed = true;
15363 
15364   if (Enum->isFixed()) {
15365     BestType = Enum->getIntegerType();
15366     if (BestType->isPromotableIntegerType())
15367       BestPromotionType = Context.getPromotedIntegerType(BestType);
15368     else
15369       BestPromotionType = BestType;
15370 
15371     BestWidth = Context.getIntWidth(BestType);
15372   }
15373   else if (NumNegativeBits) {
15374     // If there is a negative value, figure out the smallest integer type (of
15375     // int/long/longlong) that fits.
15376     // If it's packed, check also if it fits a char or a short.
15377     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
15378       BestType = Context.SignedCharTy;
15379       BestWidth = CharWidth;
15380     } else if (Packed && NumNegativeBits <= ShortWidth &&
15381                NumPositiveBits < ShortWidth) {
15382       BestType = Context.ShortTy;
15383       BestWidth = ShortWidth;
15384     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
15385       BestType = Context.IntTy;
15386       BestWidth = IntWidth;
15387     } else {
15388       BestWidth = Context.getTargetInfo().getLongWidth();
15389 
15390       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
15391         BestType = Context.LongTy;
15392       } else {
15393         BestWidth = Context.getTargetInfo().getLongLongWidth();
15394 
15395         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
15396           Diag(Enum->getLocation(), diag::ext_enum_too_large);
15397         BestType = Context.LongLongTy;
15398       }
15399     }
15400     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
15401   } else {
15402     // If there is no negative value, figure out the smallest type that fits
15403     // all of the enumerator values.
15404     // If it's packed, check also if it fits a char or a short.
15405     if (Packed && NumPositiveBits <= CharWidth) {
15406       BestType = Context.UnsignedCharTy;
15407       BestPromotionType = Context.IntTy;
15408       BestWidth = CharWidth;
15409     } else if (Packed && NumPositiveBits <= ShortWidth) {
15410       BestType = Context.UnsignedShortTy;
15411       BestPromotionType = Context.IntTy;
15412       BestWidth = ShortWidth;
15413     } else if (NumPositiveBits <= IntWidth) {
15414       BestType = Context.UnsignedIntTy;
15415       BestWidth = IntWidth;
15416       BestPromotionType
15417         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15418                            ? Context.UnsignedIntTy : Context.IntTy;
15419     } else if (NumPositiveBits <=
15420                (BestWidth = Context.getTargetInfo().getLongWidth())) {
15421       BestType = Context.UnsignedLongTy;
15422       BestPromotionType
15423         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15424                            ? Context.UnsignedLongTy : Context.LongTy;
15425     } else {
15426       BestWidth = Context.getTargetInfo().getLongLongWidth();
15427       assert(NumPositiveBits <= BestWidth &&
15428              "How could an initializer get larger than ULL?");
15429       BestType = Context.UnsignedLongLongTy;
15430       BestPromotionType
15431         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15432                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
15433     }
15434   }
15435 
15436   // Loop over all of the enumerator constants, changing their types to match
15437   // the type of the enum if needed.
15438   for (auto *D : Elements) {
15439     auto *ECD = cast_or_null<EnumConstantDecl>(D);
15440     if (!ECD) continue;  // Already issued a diagnostic.
15441 
15442     // Standard C says the enumerators have int type, but we allow, as an
15443     // extension, the enumerators to be larger than int size.  If each
15444     // enumerator value fits in an int, type it as an int, otherwise type it the
15445     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
15446     // that X has type 'int', not 'unsigned'.
15447 
15448     // Determine whether the value fits into an int.
15449     llvm::APSInt InitVal = ECD->getInitVal();
15450 
15451     // If it fits into an integer type, force it.  Otherwise force it to match
15452     // the enum decl type.
15453     QualType NewTy;
15454     unsigned NewWidth;
15455     bool NewSign;
15456     if (!getLangOpts().CPlusPlus &&
15457         !Enum->isFixed() &&
15458         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
15459       NewTy = Context.IntTy;
15460       NewWidth = IntWidth;
15461       NewSign = true;
15462     } else if (ECD->getType() == BestType) {
15463       // Already the right type!
15464       if (getLangOpts().CPlusPlus)
15465         // C++ [dcl.enum]p4: Following the closing brace of an
15466         // enum-specifier, each enumerator has the type of its
15467         // enumeration.
15468         ECD->setType(EnumType);
15469       continue;
15470     } else {
15471       NewTy = BestType;
15472       NewWidth = BestWidth;
15473       NewSign = BestType->isSignedIntegerOrEnumerationType();
15474     }
15475 
15476     // Adjust the APSInt value.
15477     InitVal = InitVal.extOrTrunc(NewWidth);
15478     InitVal.setIsSigned(NewSign);
15479     ECD->setInitVal(InitVal);
15480 
15481     // Adjust the Expr initializer and type.
15482     if (ECD->getInitExpr() &&
15483         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
15484       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
15485                                                 CK_IntegralCast,
15486                                                 ECD->getInitExpr(),
15487                                                 /*base paths*/ nullptr,
15488                                                 VK_RValue));
15489     if (getLangOpts().CPlusPlus)
15490       // C++ [dcl.enum]p4: Following the closing brace of an
15491       // enum-specifier, each enumerator has the type of its
15492       // enumeration.
15493       ECD->setType(EnumType);
15494     else
15495       ECD->setType(NewTy);
15496   }
15497 
15498   Enum->completeDefinition(BestType, BestPromotionType,
15499                            NumPositiveBits, NumNegativeBits);
15500 
15501   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
15502 
15503   if (Enum->hasAttr<FlagEnumAttr>()) {
15504     for (Decl *D : Elements) {
15505       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
15506       if (!ECD) continue;  // Already issued a diagnostic.
15507 
15508       llvm::APSInt InitVal = ECD->getInitVal();
15509       if (InitVal != 0 && !InitVal.isPowerOf2() &&
15510           !IsValueInFlagEnum(Enum, InitVal, true))
15511         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
15512           << ECD << Enum;
15513     }
15514   }
15515 
15516   // Now that the enum type is defined, ensure it's not been underaligned.
15517   if (Enum->hasAttrs())
15518     CheckAlignasUnderalignment(Enum);
15519 }
15520 
15521 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
15522                                   SourceLocation StartLoc,
15523                                   SourceLocation EndLoc) {
15524   StringLiteral *AsmString = cast<StringLiteral>(expr);
15525 
15526   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
15527                                                    AsmString, StartLoc,
15528                                                    EndLoc);
15529   CurContext->addDecl(New);
15530   return New;
15531 }
15532 
15533 static void checkModuleImportContext(Sema &S, Module *M,
15534                                      SourceLocation ImportLoc, DeclContext *DC,
15535                                      bool FromInclude = false) {
15536   SourceLocation ExternCLoc;
15537 
15538   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
15539     switch (LSD->getLanguage()) {
15540     case LinkageSpecDecl::lang_c:
15541       if (ExternCLoc.isInvalid())
15542         ExternCLoc = LSD->getLocStart();
15543       break;
15544     case LinkageSpecDecl::lang_cxx:
15545       break;
15546     }
15547     DC = LSD->getParent();
15548   }
15549 
15550   while (isa<LinkageSpecDecl>(DC))
15551     DC = DC->getParent();
15552 
15553   if (!isa<TranslationUnitDecl>(DC)) {
15554     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
15555                           ? diag::ext_module_import_not_at_top_level_noop
15556                           : diag::err_module_import_not_at_top_level_fatal)
15557         << M->getFullModuleName() << DC;
15558     S.Diag(cast<Decl>(DC)->getLocStart(),
15559            diag::note_module_import_not_at_top_level) << DC;
15560   } else if (!M->IsExternC && ExternCLoc.isValid()) {
15561     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
15562       << M->getFullModuleName();
15563     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
15564   }
15565 }
15566 
15567 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation ModuleLoc,
15568                                            ModuleDeclKind MDK,
15569                                            ModuleIdPath Path) {
15570   // 'module implementation' requires that we are not compiling a module of any
15571   // kind. 'module' and 'module partition' require that we are compiling a
15572   // module inteface (not a module map).
15573   auto CMK = getLangOpts().getCompilingModule();
15574   if (MDK == ModuleDeclKind::Implementation
15575           ? CMK != LangOptions::CMK_None
15576           : CMK != LangOptions::CMK_ModuleInterface) {
15577     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
15578       << (unsigned)MDK;
15579     return nullptr;
15580   }
15581 
15582   // FIXME: Create a ModuleDecl and return it.
15583 
15584   // FIXME: Most of this work should be done by the preprocessor rather than
15585   // here, in case we look ahead across something where the current
15586   // module matters (eg a #include).
15587 
15588   // The dots in a module name in the Modules TS are a lie. Unlike Clang's
15589   // hierarchical module map modules, the dots here are just another character
15590   // that can appear in a module name. Flatten down to the actual module name.
15591   std::string ModuleName;
15592   for (auto &Piece : Path) {
15593     if (!ModuleName.empty())
15594       ModuleName += ".";
15595     ModuleName += Piece.first->getName();
15596   }
15597 
15598   // If a module name was explicitly specified on the command line, it must be
15599   // correct.
15600   if (!getLangOpts().CurrentModule.empty() &&
15601       getLangOpts().CurrentModule != ModuleName) {
15602     Diag(Path.front().second, diag::err_current_module_name_mismatch)
15603         << SourceRange(Path.front().second, Path.back().second)
15604         << getLangOpts().CurrentModule;
15605     return nullptr;
15606   }
15607   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
15608 
15609   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
15610 
15611   switch (MDK) {
15612   case ModuleDeclKind::Module: {
15613     // FIXME: Check we're not in a submodule.
15614 
15615     // We can't have imported a definition of this module or parsed a module
15616     // map defining it already.
15617     if (auto *M = Map.findModule(ModuleName)) {
15618       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
15619       if (M->DefinitionLoc.isValid())
15620         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
15621       else if (const auto *FE = M->getASTFile())
15622         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
15623             << FE->getName();
15624       return nullptr;
15625     }
15626 
15627     // Create a Module for the module that we're defining.
15628     Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
15629     assert(Mod && "module creation should not fail");
15630 
15631     // Enter the semantic scope of the module.
15632     ActOnModuleBegin(ModuleLoc, Mod);
15633     return nullptr;
15634   }
15635 
15636   case ModuleDeclKind::Partition:
15637     // FIXME: Check we are in a submodule of the named module.
15638     return nullptr;
15639 
15640   case ModuleDeclKind::Implementation:
15641     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
15642         PP.getIdentifierInfo(ModuleName), Path[0].second);
15643 
15644     DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc);
15645     if (Import.isInvalid())
15646       return nullptr;
15647     return ConvertDeclToDeclGroup(Import.get());
15648   }
15649 
15650   llvm_unreachable("unexpected module decl kind");
15651 }
15652 
15653 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
15654                                    SourceLocation ImportLoc,
15655                                    ModuleIdPath Path) {
15656   Module *Mod =
15657       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
15658                                    /*IsIncludeDirective=*/false);
15659   if (!Mod)
15660     return true;
15661 
15662   VisibleModules.setVisible(Mod, ImportLoc);
15663 
15664   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
15665 
15666   // FIXME: we should support importing a submodule within a different submodule
15667   // of the same top-level module. Until we do, make it an error rather than
15668   // silently ignoring the import.
15669   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
15670   // warn on a redundant import of the current module?
15671   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
15672       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
15673     Diag(ImportLoc, getLangOpts().isCompilingModule()
15674                         ? diag::err_module_self_import
15675                         : diag::err_module_import_in_implementation)
15676         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
15677 
15678   SmallVector<SourceLocation, 2> IdentifierLocs;
15679   Module *ModCheck = Mod;
15680   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
15681     // If we've run out of module parents, just drop the remaining identifiers.
15682     // We need the length to be consistent.
15683     if (!ModCheck)
15684       break;
15685     ModCheck = ModCheck->Parent;
15686 
15687     IdentifierLocs.push_back(Path[I].second);
15688   }
15689 
15690   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15691   ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
15692                                           Mod, IdentifierLocs);
15693   if (!ModuleScopes.empty())
15694     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
15695   TU->addDecl(Import);
15696   return Import;
15697 }
15698 
15699 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15700   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15701   BuildModuleInclude(DirectiveLoc, Mod);
15702 }
15703 
15704 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15705   // Determine whether we're in the #include buffer for a module. The #includes
15706   // in that buffer do not qualify as module imports; they're just an
15707   // implementation detail of us building the module.
15708   //
15709   // FIXME: Should we even get ActOnModuleInclude calls for those?
15710   bool IsInModuleIncludes =
15711       TUKind == TU_Module &&
15712       getSourceManager().isWrittenInMainFile(DirectiveLoc);
15713 
15714   bool ShouldAddImport = !IsInModuleIncludes;
15715 
15716   // If this module import was due to an inclusion directive, create an
15717   // implicit import declaration to capture it in the AST.
15718   if (ShouldAddImport) {
15719     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15720     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15721                                                      DirectiveLoc, Mod,
15722                                                      DirectiveLoc);
15723     if (!ModuleScopes.empty())
15724       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
15725     TU->addDecl(ImportD);
15726     Consumer.HandleImplicitImportDecl(ImportD);
15727   }
15728 
15729   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
15730   VisibleModules.setVisible(Mod, DirectiveLoc);
15731 }
15732 
15733 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
15734   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15735 
15736   ModuleScopes.push_back({});
15737   ModuleScopes.back().Module = Mod;
15738   if (getLangOpts().ModulesLocalVisibility)
15739     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
15740 
15741   VisibleModules.setVisible(Mod, DirectiveLoc);
15742 }
15743 
15744 void Sema::ActOnModuleEnd(SourceLocation EofLoc, Module *Mod) {
15745   if (getLangOpts().ModulesLocalVisibility) {
15746     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
15747     // Leaving a module hides namespace names, so our visible namespace cache
15748     // is now out of date.
15749     VisibleNamespaceCache.clear();
15750   }
15751 
15752   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
15753          "left the wrong module scope");
15754   ModuleScopes.pop_back();
15755 
15756   // We got to the end of processing a #include of a local module. Create an
15757   // ImportDecl as we would for an imported module.
15758   FileID File = getSourceManager().getFileID(EofLoc);
15759   assert(File != getSourceManager().getMainFileID() &&
15760          "end of submodule in main source file");
15761   SourceLocation DirectiveLoc = getSourceManager().getIncludeLoc(File);
15762   BuildModuleInclude(DirectiveLoc, Mod);
15763 }
15764 
15765 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
15766                                                       Module *Mod) {
15767   // Bail if we're not allowed to implicitly import a module here.
15768   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
15769     return;
15770 
15771   // Create the implicit import declaration.
15772   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15773   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15774                                                    Loc, Mod, Loc);
15775   TU->addDecl(ImportD);
15776   Consumer.HandleImplicitImportDecl(ImportD);
15777 
15778   // Make the module visible.
15779   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
15780   VisibleModules.setVisible(Mod, Loc);
15781 }
15782 
15783 /// We have parsed the start of an export declaration, including the '{'
15784 /// (if present).
15785 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
15786                                  SourceLocation LBraceLoc) {
15787   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
15788 
15789   // C++ Modules TS draft:
15790   //   An export-declaration [...] shall not contain more than one
15791   //   export keyword.
15792   //
15793   // The intent here is that an export-declaration cannot appear within another
15794   // export-declaration.
15795   if (D->isExported())
15796     Diag(ExportLoc, diag::err_export_within_export);
15797 
15798   CurContext->addDecl(D);
15799   PushDeclContext(S, D);
15800   return D;
15801 }
15802 
15803 /// Complete the definition of an export declaration.
15804 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
15805   auto *ED = cast<ExportDecl>(D);
15806   if (RBraceLoc.isValid())
15807     ED->setRBraceLoc(RBraceLoc);
15808 
15809   // FIXME: Diagnose export of internal-linkage declaration (including
15810   // anonymous namespace).
15811 
15812   PopDeclContext();
15813   return D;
15814 }
15815 
15816 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
15817                                       IdentifierInfo* AliasName,
15818                                       SourceLocation PragmaLoc,
15819                                       SourceLocation NameLoc,
15820                                       SourceLocation AliasNameLoc) {
15821   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
15822                                          LookupOrdinaryName);
15823   AsmLabelAttr *Attr =
15824       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
15825 
15826   // If a declaration that:
15827   // 1) declares a function or a variable
15828   // 2) has external linkage
15829   // already exists, add a label attribute to it.
15830   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15831     if (isDeclExternC(PrevDecl))
15832       PrevDecl->addAttr(Attr);
15833     else
15834       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
15835           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
15836   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
15837   } else
15838     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
15839 }
15840 
15841 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
15842                              SourceLocation PragmaLoc,
15843                              SourceLocation NameLoc) {
15844   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
15845 
15846   if (PrevDecl) {
15847     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
15848   } else {
15849     (void)WeakUndeclaredIdentifiers.insert(
15850       std::pair<IdentifierInfo*,WeakInfo>
15851         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
15852   }
15853 }
15854 
15855 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
15856                                 IdentifierInfo* AliasName,
15857                                 SourceLocation PragmaLoc,
15858                                 SourceLocation NameLoc,
15859                                 SourceLocation AliasNameLoc) {
15860   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
15861                                     LookupOrdinaryName);
15862   WeakInfo W = WeakInfo(Name, NameLoc);
15863 
15864   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15865     if (!PrevDecl->hasAttr<AliasAttr>())
15866       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
15867         DeclApplyPragmaWeak(TUScope, ND, W);
15868   } else {
15869     (void)WeakUndeclaredIdentifiers.insert(
15870       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
15871   }
15872 }
15873 
15874 Decl *Sema::getObjCDeclContext() const {
15875   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
15876 }
15877