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     DiagnoseUseOfDecl(IIDecl, NameLoc);
429 
430     T = Context.getTypeDeclType(TD);
431     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
432 
433     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
434     // constructor or destructor name (in such a case, the scope specifier
435     // will be attached to the enclosing Expr or Decl node).
436     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
437       if (WantNontrivialTypeSourceInfo) {
438         // Construct a type with type-source information.
439         TypeLocBuilder Builder;
440         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
441 
442         T = getElaboratedType(ETK_None, *SS, T);
443         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
444         ElabTL.setElaboratedKeywordLoc(SourceLocation());
445         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
446         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
447       } else {
448         T = getElaboratedType(ETK_None, *SS, T);
449       }
450     }
451   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
452     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
453     if (!HasTrailingDot)
454       T = Context.getObjCInterfaceType(IDecl);
455   }
456 
457   if (T.isNull()) {
458     // If it's not plausibly a type, suppress diagnostics.
459     Result.suppressDiagnostics();
460     return nullptr;
461   }
462   return ParsedType::make(T);
463 }
464 
465 // Builds a fake NNS for the given decl context.
466 static NestedNameSpecifier *
467 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
468   for (;; DC = DC->getLookupParent()) {
469     DC = DC->getPrimaryContext();
470     auto *ND = dyn_cast<NamespaceDecl>(DC);
471     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
472       return NestedNameSpecifier::Create(Context, nullptr, ND);
473     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
474       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
475                                          RD->getTypeForDecl());
476     else if (isa<TranslationUnitDecl>(DC))
477       return NestedNameSpecifier::GlobalSpecifier(Context);
478   }
479   llvm_unreachable("something isn't in TU scope?");
480 }
481 
482 /// Find the parent class with dependent bases of the innermost enclosing method
483 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
484 /// up allowing unqualified dependent type names at class-level, which MSVC
485 /// correctly rejects.
486 static const CXXRecordDecl *
487 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
488   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
489     DC = DC->getPrimaryContext();
490     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
491       if (MD->getParent()->hasAnyDependentBases())
492         return MD->getParent();
493   }
494   return nullptr;
495 }
496 
497 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
498                                           SourceLocation NameLoc,
499                                           bool IsTemplateTypeArg) {
500   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
501 
502   NestedNameSpecifier *NNS = nullptr;
503   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
504     // If we weren't able to parse a default template argument, delay lookup
505     // until instantiation time by making a non-dependent DependentTypeName. We
506     // pretend we saw a NestedNameSpecifier referring to the current scope, and
507     // lookup is retried.
508     // FIXME: This hurts our diagnostic quality, since we get errors like "no
509     // type named 'Foo' in 'current_namespace'" when the user didn't write any
510     // name specifiers.
511     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
512     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
513   } else if (const CXXRecordDecl *RD =
514                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
515     // Build a DependentNameType that will perform lookup into RD at
516     // instantiation time.
517     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
518                                       RD->getTypeForDecl());
519 
520     // Diagnose that this identifier was undeclared, and retry the lookup during
521     // template instantiation.
522     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
523                                                                       << RD;
524   } else {
525     // This is not a situation that we should recover from.
526     return ParsedType();
527   }
528 
529   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
530 
531   // Build type location information.  We synthesized the qualifier, so we have
532   // to build a fake NestedNameSpecifierLoc.
533   NestedNameSpecifierLocBuilder NNSLocBuilder;
534   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
535   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
536 
537   TypeLocBuilder Builder;
538   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
539   DepTL.setNameLoc(NameLoc);
540   DepTL.setElaboratedKeywordLoc(SourceLocation());
541   DepTL.setQualifierLoc(QualifierLoc);
542   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
543 }
544 
545 /// isTagName() - This method is called *for error recovery purposes only*
546 /// to determine if the specified name is a valid tag name ("struct foo").  If
547 /// so, this returns the TST for the tag corresponding to it (TST_enum,
548 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
549 /// cases in C where the user forgot to specify the tag.
550 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
551   // Do a tag name lookup in this scope.
552   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
553   LookupName(R, S, false);
554   R.suppressDiagnostics();
555   if (R.getResultKind() == LookupResult::Found)
556     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
557       switch (TD->getTagKind()) {
558       case TTK_Struct: return DeclSpec::TST_struct;
559       case TTK_Interface: return DeclSpec::TST_interface;
560       case TTK_Union:  return DeclSpec::TST_union;
561       case TTK_Class:  return DeclSpec::TST_class;
562       case TTK_Enum:   return DeclSpec::TST_enum;
563       }
564     }
565 
566   return DeclSpec::TST_unspecified;
567 }
568 
569 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
570 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
571 /// then downgrade the missing typename error to a warning.
572 /// This is needed for MSVC compatibility; Example:
573 /// @code
574 /// template<class T> class A {
575 /// public:
576 ///   typedef int TYPE;
577 /// };
578 /// template<class T> class B : public A<T> {
579 /// public:
580 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
581 /// };
582 /// @endcode
583 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
584   if (CurContext->isRecord()) {
585     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
586       return true;
587 
588     const Type *Ty = SS->getScopeRep()->getAsType();
589 
590     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
591     for (const auto &Base : RD->bases())
592       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
593         return true;
594     return S->isFunctionPrototypeScope();
595   }
596   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
597 }
598 
599 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
600                                    SourceLocation IILoc,
601                                    Scope *S,
602                                    CXXScopeSpec *SS,
603                                    ParsedType &SuggestedType,
604                                    bool AllowClassTemplates) {
605   // We don't have anything to suggest (yet).
606   SuggestedType = nullptr;
607 
608   // There may have been a typo in the name of the type. Look up typo
609   // results, in case we have something that we can suggest.
610   if (TypoCorrection Corrected =
611           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
612                       llvm::make_unique<TypeNameValidatorCCC>(
613                           false, false, AllowClassTemplates),
614                       CTK_ErrorRecovery)) {
615     if (Corrected.isKeyword()) {
616       // We corrected to a keyword.
617       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
618       II = Corrected.getCorrectionAsIdentifierInfo();
619     } else {
620       // We found a similarly-named type or interface; suggest that.
621       if (!SS || !SS->isSet()) {
622         diagnoseTypo(Corrected,
623                      PDiag(diag::err_unknown_typename_suggest) << II);
624       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
625         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
626         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
627                                 II->getName().equals(CorrectedStr);
628         diagnoseTypo(Corrected,
629                      PDiag(diag::err_unknown_nested_typename_suggest)
630                        << II << DC << DroppedSpecifier << SS->getRange());
631       } else {
632         llvm_unreachable("could not have corrected a typo here");
633       }
634 
635       CXXScopeSpec tmpSS;
636       if (Corrected.getCorrectionSpecifier())
637         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
638                           SourceRange(IILoc));
639       SuggestedType =
640           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
641                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
642                       /*IsCtorOrDtorName=*/false,
643                       /*NonTrivialTypeSourceInfo=*/true);
644     }
645     return;
646   }
647 
648   if (getLangOpts().CPlusPlus) {
649     // See if II is a class template that the user forgot to pass arguments to.
650     UnqualifiedId Name;
651     Name.setIdentifier(II, IILoc);
652     CXXScopeSpec EmptySS;
653     TemplateTy TemplateResult;
654     bool MemberOfUnknownSpecialization;
655     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
656                        Name, nullptr, true, TemplateResult,
657                        MemberOfUnknownSpecialization) == TNK_Type_template) {
658       TemplateName TplName = TemplateResult.get();
659       Diag(IILoc, diag::err_template_missing_args) << TplName;
660       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
661         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
662           << TplDecl->getTemplateParameters()->getSourceRange();
663       }
664       return;
665     }
666   }
667 
668   // FIXME: Should we move the logic that tries to recover from a missing tag
669   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
670 
671   if (!SS || (!SS->isSet() && !SS->isInvalid()))
672     Diag(IILoc, diag::err_unknown_typename) << II;
673   else if (DeclContext *DC = computeDeclContext(*SS, false))
674     Diag(IILoc, diag::err_typename_nested_not_found)
675       << II << DC << SS->getRange();
676   else if (isDependentScopeSpecifier(*SS)) {
677     unsigned DiagID = diag::err_typename_missing;
678     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
679       DiagID = diag::ext_typename_missing;
680 
681     Diag(SS->getRange().getBegin(), DiagID)
682       << SS->getScopeRep() << II->getName()
683       << SourceRange(SS->getRange().getBegin(), IILoc)
684       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
685     SuggestedType = ActOnTypenameType(S, SourceLocation(),
686                                       *SS, *II, IILoc).get();
687   } else {
688     assert(SS && SS->isInvalid() &&
689            "Invalid scope specifier has already been diagnosed");
690   }
691 }
692 
693 /// \brief Determine whether the given result set contains either a type name
694 /// or
695 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
696   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
697                        NextToken.is(tok::less);
698 
699   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
700     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
701       return true;
702 
703     if (CheckTemplate && isa<TemplateDecl>(*I))
704       return true;
705   }
706 
707   return false;
708 }
709 
710 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
711                                     Scope *S, CXXScopeSpec &SS,
712                                     IdentifierInfo *&Name,
713                                     SourceLocation NameLoc) {
714   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
715   SemaRef.LookupParsedName(R, S, &SS);
716   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
717     StringRef FixItTagName;
718     switch (Tag->getTagKind()) {
719       case TTK_Class:
720         FixItTagName = "class ";
721         break;
722 
723       case TTK_Enum:
724         FixItTagName = "enum ";
725         break;
726 
727       case TTK_Struct:
728         FixItTagName = "struct ";
729         break;
730 
731       case TTK_Interface:
732         FixItTagName = "__interface ";
733         break;
734 
735       case TTK_Union:
736         FixItTagName = "union ";
737         break;
738     }
739 
740     StringRef TagName = FixItTagName.drop_back();
741     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
742       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
743       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
744 
745     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
746          I != IEnd; ++I)
747       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
748         << Name << TagName;
749 
750     // Replace lookup results with just the tag decl.
751     Result.clear(Sema::LookupTagName);
752     SemaRef.LookupParsedName(Result, S, &SS);
753     return true;
754   }
755 
756   return false;
757 }
758 
759 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
760 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
761                                   QualType T, SourceLocation NameLoc) {
762   ASTContext &Context = S.Context;
763 
764   TypeLocBuilder Builder;
765   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
766 
767   T = S.getElaboratedType(ETK_None, SS, T);
768   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
769   ElabTL.setElaboratedKeywordLoc(SourceLocation());
770   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
771   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
772 }
773 
774 Sema::NameClassification
775 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
776                    SourceLocation NameLoc, const Token &NextToken,
777                    bool IsAddressOfOperand,
778                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
779   DeclarationNameInfo NameInfo(Name, NameLoc);
780   ObjCMethodDecl *CurMethod = getCurMethodDecl();
781 
782   if (NextToken.is(tok::coloncolon)) {
783     NestedNameSpecInfo IdInfo(Name, NameLoc, NextToken.getLocation());
784     BuildCXXNestedNameSpecifier(S, IdInfo, false, SS, nullptr, false);
785   }
786 
787   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
788   LookupParsedName(Result, S, &SS, !CurMethod);
789 
790   // For unqualified lookup in a class template in MSVC mode, look into
791   // dependent base classes where the primary class template is known.
792   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
793     if (ParsedType TypeInBase =
794             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
795       return TypeInBase;
796   }
797 
798   // Perform lookup for Objective-C instance variables (including automatically
799   // synthesized instance variables), if we're in an Objective-C method.
800   // FIXME: This lookup really, really needs to be folded in to the normal
801   // unqualified lookup mechanism.
802   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
803     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
804     if (E.get() || E.isInvalid())
805       return E;
806   }
807 
808   bool SecondTry = false;
809   bool IsFilteredTemplateName = false;
810 
811 Corrected:
812   switch (Result.getResultKind()) {
813   case LookupResult::NotFound:
814     // If an unqualified-id is followed by a '(', then we have a function
815     // call.
816     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
817       // In C++, this is an ADL-only call.
818       // FIXME: Reference?
819       if (getLangOpts().CPlusPlus)
820         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
821 
822       // C90 6.3.2.2:
823       //   If the expression that precedes the parenthesized argument list in a
824       //   function call consists solely of an identifier, and if no
825       //   declaration is visible for this identifier, the identifier is
826       //   implicitly declared exactly as if, in the innermost block containing
827       //   the function call, the declaration
828       //
829       //     extern int identifier ();
830       //
831       //   appeared.
832       //
833       // We also allow this in C99 as an extension.
834       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
835         Result.addDecl(D);
836         Result.resolveKind();
837         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
838       }
839     }
840 
841     // In C, we first see whether there is a tag type by the same name, in
842     // which case it's likely that the user just forgot to write "enum",
843     // "struct", or "union".
844     if (!getLangOpts().CPlusPlus && !SecondTry &&
845         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
846       break;
847     }
848 
849     // Perform typo correction to determine if there is another name that is
850     // close to this name.
851     if (!SecondTry && CCC) {
852       SecondTry = true;
853       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
854                                                  Result.getLookupKind(), S,
855                                                  &SS, std::move(CCC),
856                                                  CTK_ErrorRecovery)) {
857         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
858         unsigned QualifiedDiag = diag::err_no_member_suggest;
859 
860         NamedDecl *FirstDecl = Corrected.getFoundDecl();
861         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
862         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
863             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
864           UnqualifiedDiag = diag::err_no_template_suggest;
865           QualifiedDiag = diag::err_no_member_template_suggest;
866         } else if (UnderlyingFirstDecl &&
867                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
868                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
869                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
870           UnqualifiedDiag = diag::err_unknown_typename_suggest;
871           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
872         }
873 
874         if (SS.isEmpty()) {
875           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
876         } else {// FIXME: is this even reachable? Test it.
877           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
878           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
879                                   Name->getName().equals(CorrectedStr);
880           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
881                                     << Name << computeDeclContext(SS, false)
882                                     << DroppedSpecifier << SS.getRange());
883         }
884 
885         // Update the name, so that the caller has the new name.
886         Name = Corrected.getCorrectionAsIdentifierInfo();
887 
888         // Typo correction corrected to a keyword.
889         if (Corrected.isKeyword())
890           return Name;
891 
892         // Also update the LookupResult...
893         // FIXME: This should probably go away at some point
894         Result.clear();
895         Result.setLookupName(Corrected.getCorrection());
896         if (FirstDecl)
897           Result.addDecl(FirstDecl);
898 
899         // If we found an Objective-C instance variable, let
900         // LookupInObjCMethod build the appropriate expression to
901         // reference the ivar.
902         // FIXME: This is a gross hack.
903         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
904           Result.clear();
905           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
906           return E;
907         }
908 
909         goto Corrected;
910       }
911     }
912 
913     // We failed to correct; just fall through and let the parser deal with it.
914     Result.suppressDiagnostics();
915     return NameClassification::Unknown();
916 
917   case LookupResult::NotFoundInCurrentInstantiation: {
918     // We performed name lookup into the current instantiation, and there were
919     // dependent bases, so we treat this result the same way as any other
920     // dependent nested-name-specifier.
921 
922     // C++ [temp.res]p2:
923     //   A name used in a template declaration or definition and that is
924     //   dependent on a template-parameter is assumed not to name a type
925     //   unless the applicable name lookup finds a type name or the name is
926     //   qualified by the keyword typename.
927     //
928     // FIXME: If the next token is '<', we might want to ask the parser to
929     // perform some heroics to see if we actually have a
930     // template-argument-list, which would indicate a missing 'template'
931     // keyword here.
932     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
933                                       NameInfo, IsAddressOfOperand,
934                                       /*TemplateArgs=*/nullptr);
935   }
936 
937   case LookupResult::Found:
938   case LookupResult::FoundOverloaded:
939   case LookupResult::FoundUnresolvedValue:
940     break;
941 
942   case LookupResult::Ambiguous:
943     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
944         hasAnyAcceptableTemplateNames(Result)) {
945       // C++ [temp.local]p3:
946       //   A lookup that finds an injected-class-name (10.2) can result in an
947       //   ambiguity in certain cases (for example, if it is found in more than
948       //   one base class). If all of the injected-class-names that are found
949       //   refer to specializations of the same class template, and if the name
950       //   is followed by a template-argument-list, the reference refers to the
951       //   class template itself and not a specialization thereof, and is not
952       //   ambiguous.
953       //
954       // This filtering can make an ambiguous result into an unambiguous one,
955       // so try again after filtering out template names.
956       FilterAcceptableTemplateNames(Result);
957       if (!Result.isAmbiguous()) {
958         IsFilteredTemplateName = true;
959         break;
960       }
961     }
962 
963     // Diagnose the ambiguity and return an error.
964     return NameClassification::Error();
965   }
966 
967   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
968       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
969     // C++ [temp.names]p3:
970     //   After name lookup (3.4) finds that a name is a template-name or that
971     //   an operator-function-id or a literal- operator-id refers to a set of
972     //   overloaded functions any member of which is a function template if
973     //   this is followed by a <, the < is always taken as the delimiter of a
974     //   template-argument-list and never as the less-than operator.
975     if (!IsFilteredTemplateName)
976       FilterAcceptableTemplateNames(Result);
977 
978     if (!Result.empty()) {
979       bool IsFunctionTemplate;
980       bool IsVarTemplate;
981       TemplateName Template;
982       if (Result.end() - Result.begin() > 1) {
983         IsFunctionTemplate = true;
984         Template = Context.getOverloadedTemplateName(Result.begin(),
985                                                      Result.end());
986       } else {
987         TemplateDecl *TD
988           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
989         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
990         IsVarTemplate = isa<VarTemplateDecl>(TD);
991 
992         if (SS.isSet() && !SS.isInvalid())
993           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
994                                                     /*TemplateKeyword=*/false,
995                                                       TD);
996         else
997           Template = TemplateName(TD);
998       }
999 
1000       if (IsFunctionTemplate) {
1001         // Function templates always go through overload resolution, at which
1002         // point we'll perform the various checks (e.g., accessibility) we need
1003         // to based on which function we selected.
1004         Result.suppressDiagnostics();
1005 
1006         return NameClassification::FunctionTemplate(Template);
1007       }
1008 
1009       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1010                            : NameClassification::TypeTemplate(Template);
1011     }
1012   }
1013 
1014   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1015   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1016     DiagnoseUseOfDecl(Type, NameLoc);
1017     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1018     QualType T = Context.getTypeDeclType(Type);
1019     if (SS.isNotEmpty())
1020       return buildNestedType(*this, SS, T, NameLoc);
1021     return ParsedType::make(T);
1022   }
1023 
1024   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1025   if (!Class) {
1026     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1027     if (ObjCCompatibleAliasDecl *Alias =
1028             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1029       Class = Alias->getClassInterface();
1030   }
1031 
1032   if (Class) {
1033     DiagnoseUseOfDecl(Class, NameLoc);
1034 
1035     if (NextToken.is(tok::period)) {
1036       // Interface. <something> is parsed as a property reference expression.
1037       // Just return "unknown" as a fall-through for now.
1038       Result.suppressDiagnostics();
1039       return NameClassification::Unknown();
1040     }
1041 
1042     QualType T = Context.getObjCInterfaceType(Class);
1043     return ParsedType::make(T);
1044   }
1045 
1046   // We can have a type template here if we're classifying a template argument.
1047   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
1048     return NameClassification::TypeTemplate(
1049         TemplateName(cast<TemplateDecl>(FirstDecl)));
1050 
1051   // Check for a tag type hidden by a non-type decl in a few cases where it
1052   // seems likely a type is wanted instead of the non-type that was found.
1053   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1054   if ((NextToken.is(tok::identifier) ||
1055        (NextIsOp &&
1056         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1057       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1058     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1059     DiagnoseUseOfDecl(Type, NameLoc);
1060     QualType T = Context.getTypeDeclType(Type);
1061     if (SS.isNotEmpty())
1062       return buildNestedType(*this, SS, T, NameLoc);
1063     return ParsedType::make(T);
1064   }
1065 
1066   if (FirstDecl->isCXXClassMember())
1067     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1068                                            nullptr, S);
1069 
1070   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1071   return BuildDeclarationNameExpr(SS, Result, ADL);
1072 }
1073 
1074 // Determines the context to return to after temporarily entering a
1075 // context.  This depends in an unnecessarily complicated way on the
1076 // exact ordering of callbacks from the parser.
1077 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1078 
1079   // Functions defined inline within classes aren't parsed until we've
1080   // finished parsing the top-level class, so the top-level class is
1081   // the context we'll need to return to.
1082   // A Lambda call operator whose parent is a class must not be treated
1083   // as an inline member function.  A Lambda can be used legally
1084   // either as an in-class member initializer or a default argument.  These
1085   // are parsed once the class has been marked complete and so the containing
1086   // context would be the nested class (when the lambda is defined in one);
1087   // If the class is not complete, then the lambda is being used in an
1088   // ill-formed fashion (such as to specify the width of a bit-field, or
1089   // in an array-bound) - in which case we still want to return the
1090   // lexically containing DC (which could be a nested class).
1091   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1092     DC = DC->getLexicalParent();
1093 
1094     // A function not defined within a class will always return to its
1095     // lexical context.
1096     if (!isa<CXXRecordDecl>(DC))
1097       return DC;
1098 
1099     // A C++ inline method/friend is parsed *after* the topmost class
1100     // it was declared in is fully parsed ("complete");  the topmost
1101     // class is the context we need to return to.
1102     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1103       DC = RD;
1104 
1105     // Return the declaration context of the topmost class the inline method is
1106     // declared in.
1107     return DC;
1108   }
1109 
1110   return DC->getLexicalParent();
1111 }
1112 
1113 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1114   assert(getContainingDC(DC) == CurContext &&
1115       "The next DeclContext should be lexically contained in the current one.");
1116   CurContext = DC;
1117   S->setEntity(DC);
1118 }
1119 
1120 void Sema::PopDeclContext() {
1121   assert(CurContext && "DeclContext imbalance!");
1122 
1123   CurContext = getContainingDC(CurContext);
1124   assert(CurContext && "Popped translation unit!");
1125 }
1126 
1127 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1128                                                                     Decl *D) {
1129   // Unlike PushDeclContext, the context to which we return is not necessarily
1130   // the containing DC of TD, because the new context will be some pre-existing
1131   // TagDecl definition instead of a fresh one.
1132   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1133   CurContext = cast<TagDecl>(D)->getDefinition();
1134   assert(CurContext && "skipping definition of undefined tag");
1135   // Start lookups from the parent of the current context; we don't want to look
1136   // into the pre-existing complete definition.
1137   S->setEntity(CurContext->getLookupParent());
1138   return Result;
1139 }
1140 
1141 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1142   CurContext = static_cast<decltype(CurContext)>(Context);
1143 }
1144 
1145 /// EnterDeclaratorContext - Used when we must lookup names in the context
1146 /// of a declarator's nested name specifier.
1147 ///
1148 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1149   // C++0x [basic.lookup.unqual]p13:
1150   //   A name used in the definition of a static data member of class
1151   //   X (after the qualified-id of the static member) is looked up as
1152   //   if the name was used in a member function of X.
1153   // C++0x [basic.lookup.unqual]p14:
1154   //   If a variable member of a namespace is defined outside of the
1155   //   scope of its namespace then any name used in the definition of
1156   //   the variable member (after the declarator-id) is looked up as
1157   //   if the definition of the variable member occurred in its
1158   //   namespace.
1159   // Both of these imply that we should push a scope whose context
1160   // is the semantic context of the declaration.  We can't use
1161   // PushDeclContext here because that context is not necessarily
1162   // lexically contained in the current context.  Fortunately,
1163   // the containing scope should have the appropriate information.
1164 
1165   assert(!S->getEntity() && "scope already has entity");
1166 
1167 #ifndef NDEBUG
1168   Scope *Ancestor = S->getParent();
1169   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1170   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1171 #endif
1172 
1173   CurContext = DC;
1174   S->setEntity(DC);
1175 }
1176 
1177 void Sema::ExitDeclaratorContext(Scope *S) {
1178   assert(S->getEntity() == CurContext && "Context imbalance!");
1179 
1180   // Switch back to the lexical context.  The safety of this is
1181   // enforced by an assert in EnterDeclaratorContext.
1182   Scope *Ancestor = S->getParent();
1183   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1184   CurContext = Ancestor->getEntity();
1185 
1186   // We don't need to do anything with the scope, which is going to
1187   // disappear.
1188 }
1189 
1190 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1191   // We assume that the caller has already called
1192   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1193   FunctionDecl *FD = D->getAsFunction();
1194   if (!FD)
1195     return;
1196 
1197   // Same implementation as PushDeclContext, but enters the context
1198   // from the lexical parent, rather than the top-level class.
1199   assert(CurContext == FD->getLexicalParent() &&
1200     "The next DeclContext should be lexically contained in the current one.");
1201   CurContext = FD;
1202   S->setEntity(CurContext);
1203 
1204   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1205     ParmVarDecl *Param = FD->getParamDecl(P);
1206     // If the parameter has an identifier, then add it to the scope
1207     if (Param->getIdentifier()) {
1208       S->AddDecl(Param);
1209       IdResolver.AddDecl(Param);
1210     }
1211   }
1212 }
1213 
1214 void Sema::ActOnExitFunctionContext() {
1215   // Same implementation as PopDeclContext, but returns to the lexical parent,
1216   // rather than the top-level class.
1217   assert(CurContext && "DeclContext imbalance!");
1218   CurContext = CurContext->getLexicalParent();
1219   assert(CurContext && "Popped translation unit!");
1220 }
1221 
1222 /// \brief Determine whether we allow overloading of the function
1223 /// PrevDecl with another declaration.
1224 ///
1225 /// This routine determines whether overloading is possible, not
1226 /// whether some new function is actually an overload. It will return
1227 /// true in C++ (where we can always provide overloads) or, as an
1228 /// extension, in C when the previous function is already an
1229 /// overloaded function declaration or has the "overloadable"
1230 /// attribute.
1231 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1232                                        ASTContext &Context) {
1233   if (Context.getLangOpts().CPlusPlus)
1234     return true;
1235 
1236   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1237     return true;
1238 
1239   return (Previous.getResultKind() == LookupResult::Found
1240           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1241 }
1242 
1243 /// Add this decl to the scope shadowed decl chains.
1244 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1245   // Move up the scope chain until we find the nearest enclosing
1246   // non-transparent context. The declaration will be introduced into this
1247   // scope.
1248   while (S->getEntity() && S->getEntity()->isTransparentContext())
1249     S = S->getParent();
1250 
1251   // Add scoped declarations into their context, so that they can be
1252   // found later. Declarations without a context won't be inserted
1253   // into any context.
1254   if (AddToContext)
1255     CurContext->addDecl(D);
1256 
1257   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1258   // are function-local declarations.
1259   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1260       !D->getDeclContext()->getRedeclContext()->Equals(
1261         D->getLexicalDeclContext()->getRedeclContext()) &&
1262       !D->getLexicalDeclContext()->isFunctionOrMethod())
1263     return;
1264 
1265   // Template instantiations should also not be pushed into scope.
1266   if (isa<FunctionDecl>(D) &&
1267       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1268     return;
1269 
1270   // If this replaces anything in the current scope,
1271   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1272                                IEnd = IdResolver.end();
1273   for (; I != IEnd; ++I) {
1274     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1275       S->RemoveDecl(*I);
1276       IdResolver.RemoveDecl(*I);
1277 
1278       // Should only need to replace one decl.
1279       break;
1280     }
1281   }
1282 
1283   S->AddDecl(D);
1284 
1285   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1286     // Implicitly-generated labels may end up getting generated in an order that
1287     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1288     // the label at the appropriate place in the identifier chain.
1289     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1290       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1291       if (IDC == CurContext) {
1292         if (!S->isDeclScope(*I))
1293           continue;
1294       } else if (IDC->Encloses(CurContext))
1295         break;
1296     }
1297 
1298     IdResolver.InsertDeclAfter(I, D);
1299   } else {
1300     IdResolver.AddDecl(D);
1301   }
1302 }
1303 
1304 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1305   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1306     TUScope->AddDecl(D);
1307 }
1308 
1309 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1310                          bool AllowInlineNamespace) {
1311   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1312 }
1313 
1314 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1315   DeclContext *TargetDC = DC->getPrimaryContext();
1316   do {
1317     if (DeclContext *ScopeDC = S->getEntity())
1318       if (ScopeDC->getPrimaryContext() == TargetDC)
1319         return S;
1320   } while ((S = S->getParent()));
1321 
1322   return nullptr;
1323 }
1324 
1325 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1326                                             DeclContext*,
1327                                             ASTContext&);
1328 
1329 /// Filters out lookup results that don't fall within the given scope
1330 /// as determined by isDeclInScope.
1331 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1332                                 bool ConsiderLinkage,
1333                                 bool AllowInlineNamespace) {
1334   LookupResult::Filter F = R.makeFilter();
1335   while (F.hasNext()) {
1336     NamedDecl *D = F.next();
1337 
1338     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1339       continue;
1340 
1341     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1342       continue;
1343 
1344     F.erase();
1345   }
1346 
1347   F.done();
1348 }
1349 
1350 static bool isUsingDecl(NamedDecl *D) {
1351   return isa<UsingShadowDecl>(D) ||
1352          isa<UnresolvedUsingTypenameDecl>(D) ||
1353          isa<UnresolvedUsingValueDecl>(D);
1354 }
1355 
1356 /// Removes using shadow declarations from the lookup results.
1357 static void RemoveUsingDecls(LookupResult &R) {
1358   LookupResult::Filter F = R.makeFilter();
1359   while (F.hasNext())
1360     if (isUsingDecl(F.next()))
1361       F.erase();
1362 
1363   F.done();
1364 }
1365 
1366 /// \brief Check for this common pattern:
1367 /// @code
1368 /// class S {
1369 ///   S(const S&); // DO NOT IMPLEMENT
1370 ///   void operator=(const S&); // DO NOT IMPLEMENT
1371 /// };
1372 /// @endcode
1373 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1374   // FIXME: Should check for private access too but access is set after we get
1375   // the decl here.
1376   if (D->doesThisDeclarationHaveABody())
1377     return false;
1378 
1379   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1380     return CD->isCopyConstructor();
1381   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1382     return Method->isCopyAssignmentOperator();
1383   return false;
1384 }
1385 
1386 // We need this to handle
1387 //
1388 // typedef struct {
1389 //   void *foo() { return 0; }
1390 // } A;
1391 //
1392 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1393 // for example. If 'A', foo will have external linkage. If we have '*A',
1394 // foo will have no linkage. Since we can't know until we get to the end
1395 // of the typedef, this function finds out if D might have non-external linkage.
1396 // Callers should verify at the end of the TU if it D has external linkage or
1397 // not.
1398 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1399   const DeclContext *DC = D->getDeclContext();
1400   while (!DC->isTranslationUnit()) {
1401     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1402       if (!RD->hasNameForLinkage())
1403         return true;
1404     }
1405     DC = DC->getParent();
1406   }
1407 
1408   return !D->isExternallyVisible();
1409 }
1410 
1411 // FIXME: This needs to be refactored; some other isInMainFile users want
1412 // these semantics.
1413 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1414   if (S.TUKind != TU_Complete)
1415     return false;
1416   return S.SourceMgr.isInMainFile(Loc);
1417 }
1418 
1419 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1420   assert(D);
1421 
1422   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1423     return false;
1424 
1425   // Ignore all entities declared within templates, and out-of-line definitions
1426   // of members of class templates.
1427   if (D->getDeclContext()->isDependentContext() ||
1428       D->getLexicalDeclContext()->isDependentContext())
1429     return false;
1430 
1431   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1432     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1433       return false;
1434 
1435     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1436       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1437         return false;
1438     } else {
1439       // 'static inline' functions are defined in headers; don't warn.
1440       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1441         return false;
1442     }
1443 
1444     if (FD->doesThisDeclarationHaveABody() &&
1445         Context.DeclMustBeEmitted(FD))
1446       return false;
1447   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1448     // Constants and utility variables are defined in headers with internal
1449     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1450     // like "inline".)
1451     if (!isMainFileLoc(*this, VD->getLocation()))
1452       return false;
1453 
1454     if (Context.DeclMustBeEmitted(VD))
1455       return false;
1456 
1457     if (VD->isStaticDataMember() &&
1458         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1459       return false;
1460 
1461     if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1462       return false;
1463   } else {
1464     return false;
1465   }
1466 
1467   // Only warn for unused decls internal to the translation unit.
1468   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1469   // for inline functions defined in the main source file, for instance.
1470   return mightHaveNonExternalLinkage(D);
1471 }
1472 
1473 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1474   if (!D)
1475     return;
1476 
1477   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1478     const FunctionDecl *First = FD->getFirstDecl();
1479     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1480       return; // First should already be in the vector.
1481   }
1482 
1483   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1484     const VarDecl *First = VD->getFirstDecl();
1485     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1486       return; // First should already be in the vector.
1487   }
1488 
1489   if (ShouldWarnIfUnusedFileScopedDecl(D))
1490     UnusedFileScopedDecls.push_back(D);
1491 }
1492 
1493 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1494   if (D->isInvalidDecl())
1495     return false;
1496 
1497   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1498       D->hasAttr<ObjCPreciseLifetimeAttr>())
1499     return false;
1500 
1501   if (isa<LabelDecl>(D))
1502     return true;
1503 
1504   // Except for labels, we only care about unused decls that are local to
1505   // functions.
1506   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1507   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1508     // For dependent types, the diagnostic is deferred.
1509     WithinFunction =
1510         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1511   if (!WithinFunction)
1512     return false;
1513 
1514   if (isa<TypedefNameDecl>(D))
1515     return true;
1516 
1517   // White-list anything that isn't a local variable.
1518   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1519     return false;
1520 
1521   // Types of valid local variables should be complete, so this should succeed.
1522   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1523 
1524     // White-list anything with an __attribute__((unused)) type.
1525     const auto *Ty = VD->getType().getTypePtr();
1526 
1527     // Only look at the outermost level of typedef.
1528     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1529       if (TT->getDecl()->hasAttr<UnusedAttr>())
1530         return false;
1531     }
1532 
1533     // If we failed to complete the type for some reason, or if the type is
1534     // dependent, don't diagnose the variable.
1535     if (Ty->isIncompleteType() || Ty->isDependentType())
1536       return false;
1537 
1538     // Look at the element type to ensure that the warning behaviour is
1539     // consistent for both scalars and arrays.
1540     Ty = Ty->getBaseElementTypeUnsafe();
1541 
1542     if (const TagType *TT = Ty->getAs<TagType>()) {
1543       const TagDecl *Tag = TT->getDecl();
1544       if (Tag->hasAttr<UnusedAttr>())
1545         return false;
1546 
1547       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1548         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1549           return false;
1550 
1551         if (const Expr *Init = VD->getInit()) {
1552           if (const ExprWithCleanups *Cleanups =
1553                   dyn_cast<ExprWithCleanups>(Init))
1554             Init = Cleanups->getSubExpr();
1555           const CXXConstructExpr *Construct =
1556             dyn_cast<CXXConstructExpr>(Init);
1557           if (Construct && !Construct->isElidable()) {
1558             CXXConstructorDecl *CD = Construct->getConstructor();
1559             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1560               return false;
1561           }
1562         }
1563       }
1564     }
1565 
1566     // TODO: __attribute__((unused)) templates?
1567   }
1568 
1569   return true;
1570 }
1571 
1572 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1573                                      FixItHint &Hint) {
1574   if (isa<LabelDecl>(D)) {
1575     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1576                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1577     if (AfterColon.isInvalid())
1578       return;
1579     Hint = FixItHint::CreateRemoval(CharSourceRange::
1580                                     getCharRange(D->getLocStart(), AfterColon));
1581   }
1582 }
1583 
1584 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1585   if (D->getTypeForDecl()->isDependentType())
1586     return;
1587 
1588   for (auto *TmpD : D->decls()) {
1589     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1590       DiagnoseUnusedDecl(T);
1591     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1592       DiagnoseUnusedNestedTypedefs(R);
1593   }
1594 }
1595 
1596 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1597 /// unless they are marked attr(unused).
1598 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1599   if (!ShouldDiagnoseUnusedDecl(D))
1600     return;
1601 
1602   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1603     // typedefs can be referenced later on, so the diagnostics are emitted
1604     // at end-of-translation-unit.
1605     UnusedLocalTypedefNameCandidates.insert(TD);
1606     return;
1607   }
1608 
1609   FixItHint Hint;
1610   GenerateFixForUnusedDecl(D, Context, Hint);
1611 
1612   unsigned DiagID;
1613   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1614     DiagID = diag::warn_unused_exception_param;
1615   else if (isa<LabelDecl>(D))
1616     DiagID = diag::warn_unused_label;
1617   else
1618     DiagID = diag::warn_unused_variable;
1619 
1620   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1621 }
1622 
1623 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1624   // Verify that we have no forward references left.  If so, there was a goto
1625   // or address of a label taken, but no definition of it.  Label fwd
1626   // definitions are indicated with a null substmt which is also not a resolved
1627   // MS inline assembly label name.
1628   bool Diagnose = false;
1629   if (L->isMSAsmLabel())
1630     Diagnose = !L->isResolvedMSAsmLabel();
1631   else
1632     Diagnose = L->getStmt() == nullptr;
1633   if (Diagnose)
1634     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1635 }
1636 
1637 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1638   S->mergeNRVOIntoParent();
1639 
1640   if (S->decl_empty()) return;
1641   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1642          "Scope shouldn't contain decls!");
1643 
1644   for (auto *TmpD : S->decls()) {
1645     assert(TmpD && "This decl didn't get pushed??");
1646 
1647     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1648     NamedDecl *D = cast<NamedDecl>(TmpD);
1649 
1650     if (!D->getDeclName()) continue;
1651 
1652     // Diagnose unused variables in this scope.
1653     if (!S->hasUnrecoverableErrorOccurred()) {
1654       DiagnoseUnusedDecl(D);
1655       if (const auto *RD = dyn_cast<RecordDecl>(D))
1656         DiagnoseUnusedNestedTypedefs(RD);
1657     }
1658 
1659     // If this was a forward reference to a label, verify it was defined.
1660     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1661       CheckPoppedLabel(LD, *this);
1662 
1663     // Remove this name from our lexical scope, and warn on it if we haven't
1664     // already.
1665     IdResolver.RemoveDecl(D);
1666     auto ShadowI = ShadowingDecls.find(D);
1667     if (ShadowI != ShadowingDecls.end()) {
1668       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1669         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1670             << D << FD << FD->getParent();
1671         Diag(FD->getLocation(), diag::note_previous_declaration);
1672       }
1673       ShadowingDecls.erase(ShadowI);
1674     }
1675   }
1676 }
1677 
1678 /// \brief Look for an Objective-C class in the translation unit.
1679 ///
1680 /// \param Id The name of the Objective-C class we're looking for. If
1681 /// typo-correction fixes this name, the Id will be updated
1682 /// to the fixed name.
1683 ///
1684 /// \param IdLoc The location of the name in the translation unit.
1685 ///
1686 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1687 /// if there is no class with the given name.
1688 ///
1689 /// \returns The declaration of the named Objective-C class, or NULL if the
1690 /// class could not be found.
1691 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1692                                               SourceLocation IdLoc,
1693                                               bool DoTypoCorrection) {
1694   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1695   // creation from this context.
1696   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1697 
1698   if (!IDecl && DoTypoCorrection) {
1699     // Perform typo correction at the given location, but only if we
1700     // find an Objective-C class name.
1701     if (TypoCorrection C = CorrectTypo(
1702             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1703             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1704             CTK_ErrorRecovery)) {
1705       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1706       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1707       Id = IDecl->getIdentifier();
1708     }
1709   }
1710   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1711   // This routine must always return a class definition, if any.
1712   if (Def && Def->getDefinition())
1713       Def = Def->getDefinition();
1714   return Def;
1715 }
1716 
1717 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1718 /// from S, where a non-field would be declared. This routine copes
1719 /// with the difference between C and C++ scoping rules in structs and
1720 /// unions. For example, the following code is well-formed in C but
1721 /// ill-formed in C++:
1722 /// @code
1723 /// struct S6 {
1724 ///   enum { BAR } e;
1725 /// };
1726 ///
1727 /// void test_S6() {
1728 ///   struct S6 a;
1729 ///   a.e = BAR;
1730 /// }
1731 /// @endcode
1732 /// For the declaration of BAR, this routine will return a different
1733 /// scope. The scope S will be the scope of the unnamed enumeration
1734 /// within S6. In C++, this routine will return the scope associated
1735 /// with S6, because the enumeration's scope is a transparent
1736 /// context but structures can contain non-field names. In C, this
1737 /// routine will return the translation unit scope, since the
1738 /// enumeration's scope is a transparent context and structures cannot
1739 /// contain non-field names.
1740 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1741   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1742          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1743          (S->isClassScope() && !getLangOpts().CPlusPlus))
1744     S = S->getParent();
1745   return S;
1746 }
1747 
1748 /// \brief Looks up the declaration of "struct objc_super" and
1749 /// saves it for later use in building builtin declaration of
1750 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1751 /// pre-existing declaration exists no action takes place.
1752 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1753                                         IdentifierInfo *II) {
1754   if (!II->isStr("objc_msgSendSuper"))
1755     return;
1756   ASTContext &Context = ThisSema.Context;
1757 
1758   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1759                       SourceLocation(), Sema::LookupTagName);
1760   ThisSema.LookupName(Result, S);
1761   if (Result.getResultKind() == LookupResult::Found)
1762     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1763       Context.setObjCSuperType(Context.getTagDeclType(TD));
1764 }
1765 
1766 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1767   switch (Error) {
1768   case ASTContext::GE_None:
1769     return "";
1770   case ASTContext::GE_Missing_stdio:
1771     return "stdio.h";
1772   case ASTContext::GE_Missing_setjmp:
1773     return "setjmp.h";
1774   case ASTContext::GE_Missing_ucontext:
1775     return "ucontext.h";
1776   }
1777   llvm_unreachable("unhandled error kind");
1778 }
1779 
1780 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1781 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1782 /// if we're creating this built-in in anticipation of redeclaring the
1783 /// built-in.
1784 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1785                                      Scope *S, bool ForRedeclaration,
1786                                      SourceLocation Loc) {
1787   LookupPredefedObjCSuperType(*this, S, II);
1788 
1789   ASTContext::GetBuiltinTypeError Error;
1790   QualType R = Context.GetBuiltinType(ID, Error);
1791   if (Error) {
1792     if (ForRedeclaration)
1793       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1794           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1795     return nullptr;
1796   }
1797 
1798   if (!ForRedeclaration &&
1799       (Context.BuiltinInfo.isPredefinedLibFunction(ID) ||
1800        Context.BuiltinInfo.isHeaderDependentFunction(ID))) {
1801     Diag(Loc, diag::ext_implicit_lib_function_decl)
1802         << Context.BuiltinInfo.getName(ID) << R;
1803     if (Context.BuiltinInfo.getHeaderName(ID) &&
1804         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1805       Diag(Loc, diag::note_include_header_or_declare)
1806           << Context.BuiltinInfo.getHeaderName(ID)
1807           << Context.BuiltinInfo.getName(ID);
1808   }
1809 
1810   if (R.isNull())
1811     return nullptr;
1812 
1813   DeclContext *Parent = Context.getTranslationUnitDecl();
1814   if (getLangOpts().CPlusPlus) {
1815     LinkageSpecDecl *CLinkageDecl =
1816         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1817                                 LinkageSpecDecl::lang_c, false);
1818     CLinkageDecl->setImplicit();
1819     Parent->addDecl(CLinkageDecl);
1820     Parent = CLinkageDecl;
1821   }
1822 
1823   FunctionDecl *New = FunctionDecl::Create(Context,
1824                                            Parent,
1825                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1826                                            SC_Extern,
1827                                            false,
1828                                            R->isFunctionProtoType());
1829   New->setImplicit();
1830 
1831   // Create Decl objects for each parameter, adding them to the
1832   // FunctionDecl.
1833   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1834     SmallVector<ParmVarDecl*, 16> Params;
1835     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1836       ParmVarDecl *parm =
1837           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1838                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1839                               SC_None, nullptr);
1840       parm->setScopeInfo(0, i);
1841       Params.push_back(parm);
1842     }
1843     New->setParams(Params);
1844   }
1845 
1846   AddKnownFunctionAttributes(New);
1847   RegisterLocallyScopedExternCDecl(New, S);
1848 
1849   // TUScope is the translation-unit scope to insert this function into.
1850   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1851   // relate Scopes to DeclContexts, and probably eliminate CurContext
1852   // entirely, but we're not there yet.
1853   DeclContext *SavedContext = CurContext;
1854   CurContext = Parent;
1855   PushOnScopeChains(New, TUScope);
1856   CurContext = SavedContext;
1857   return New;
1858 }
1859 
1860 /// Typedef declarations don't have linkage, but they still denote the same
1861 /// entity if their types are the same.
1862 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1863 /// isSameEntity.
1864 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1865                                                      TypedefNameDecl *Decl,
1866                                                      LookupResult &Previous) {
1867   // This is only interesting when modules are enabled.
1868   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1869     return;
1870 
1871   // Empty sets are uninteresting.
1872   if (Previous.empty())
1873     return;
1874 
1875   LookupResult::Filter Filter = Previous.makeFilter();
1876   while (Filter.hasNext()) {
1877     NamedDecl *Old = Filter.next();
1878 
1879     // Non-hidden declarations are never ignored.
1880     if (S.isVisible(Old))
1881       continue;
1882 
1883     // Declarations of the same entity are not ignored, even if they have
1884     // different linkages.
1885     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1886       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1887                                 Decl->getUnderlyingType()))
1888         continue;
1889 
1890       // If both declarations give a tag declaration a typedef name for linkage
1891       // purposes, then they declare the same entity.
1892       if (S.getLangOpts().CPlusPlus &&
1893           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1894           Decl->getAnonDeclWithTypedefName())
1895         continue;
1896     }
1897 
1898     Filter.erase();
1899   }
1900 
1901   Filter.done();
1902 }
1903 
1904 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1905   QualType OldType;
1906   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1907     OldType = OldTypedef->getUnderlyingType();
1908   else
1909     OldType = Context.getTypeDeclType(Old);
1910   QualType NewType = New->getUnderlyingType();
1911 
1912   if (NewType->isVariablyModifiedType()) {
1913     // Must not redefine a typedef with a variably-modified type.
1914     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1915     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1916       << Kind << NewType;
1917     if (Old->getLocation().isValid())
1918       Diag(Old->getLocation(), diag::note_previous_definition);
1919     New->setInvalidDecl();
1920     return true;
1921   }
1922 
1923   if (OldType != NewType &&
1924       !OldType->isDependentType() &&
1925       !NewType->isDependentType() &&
1926       !Context.hasSameType(OldType, NewType)) {
1927     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1928     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1929       << Kind << NewType << OldType;
1930     if (Old->getLocation().isValid())
1931       Diag(Old->getLocation(), diag::note_previous_definition);
1932     New->setInvalidDecl();
1933     return true;
1934   }
1935   return false;
1936 }
1937 
1938 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1939 /// same name and scope as a previous declaration 'Old'.  Figure out
1940 /// how to resolve this situation, merging decls or emitting
1941 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1942 ///
1943 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
1944                                 LookupResult &OldDecls) {
1945   // If the new decl is known invalid already, don't bother doing any
1946   // merging checks.
1947   if (New->isInvalidDecl()) return;
1948 
1949   // Allow multiple definitions for ObjC built-in typedefs.
1950   // FIXME: Verify the underlying types are equivalent!
1951   if (getLangOpts().ObjC1) {
1952     const IdentifierInfo *TypeID = New->getIdentifier();
1953     switch (TypeID->getLength()) {
1954     default: break;
1955     case 2:
1956       {
1957         if (!TypeID->isStr("id"))
1958           break;
1959         QualType T = New->getUnderlyingType();
1960         if (!T->isPointerType())
1961           break;
1962         if (!T->isVoidPointerType()) {
1963           QualType PT = T->getAs<PointerType>()->getPointeeType();
1964           if (!PT->isStructureType())
1965             break;
1966         }
1967         Context.setObjCIdRedefinitionType(T);
1968         // Install the built-in type for 'id', ignoring the current definition.
1969         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1970         return;
1971       }
1972     case 5:
1973       if (!TypeID->isStr("Class"))
1974         break;
1975       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1976       // Install the built-in type for 'Class', ignoring the current definition.
1977       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1978       return;
1979     case 3:
1980       if (!TypeID->isStr("SEL"))
1981         break;
1982       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1983       // Install the built-in type for 'SEL', ignoring the current definition.
1984       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1985       return;
1986     }
1987     // Fall through - the typedef name was not a builtin type.
1988   }
1989 
1990   // Verify the old decl was also a type.
1991   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1992   if (!Old) {
1993     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1994       << New->getDeclName();
1995 
1996     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1997     if (OldD->getLocation().isValid())
1998       Diag(OldD->getLocation(), diag::note_previous_definition);
1999 
2000     return New->setInvalidDecl();
2001   }
2002 
2003   // If the old declaration is invalid, just give up here.
2004   if (Old->isInvalidDecl())
2005     return New->setInvalidDecl();
2006 
2007   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2008     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2009     auto *NewTag = New->getAnonDeclWithTypedefName();
2010     NamedDecl *Hidden = nullptr;
2011     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
2012         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2013         !hasVisibleDefinition(OldTag, &Hidden)) {
2014       // There is a definition of this tag, but it is not visible. Use it
2015       // instead of our tag.
2016       New->setTypeForDecl(OldTD->getTypeForDecl());
2017       if (OldTD->isModed())
2018         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2019                                     OldTD->getUnderlyingType());
2020       else
2021         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2022 
2023       // Make the old tag definition visible.
2024       makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
2025 
2026       // If this was an unscoped enumeration, yank all of its enumerators
2027       // out of the scope.
2028       if (isa<EnumDecl>(NewTag)) {
2029         Scope *EnumScope = getNonFieldDeclScope(S);
2030         for (auto *D : NewTag->decls()) {
2031           auto *ED = cast<EnumConstantDecl>(D);
2032           assert(EnumScope->isDeclScope(ED));
2033           EnumScope->RemoveDecl(ED);
2034           IdResolver.RemoveDecl(ED);
2035           ED->getLexicalDeclContext()->removeDecl(ED);
2036         }
2037       }
2038     }
2039   }
2040 
2041   // If the typedef types are not identical, reject them in all languages and
2042   // with any extensions enabled.
2043   if (isIncompatibleTypedef(Old, New))
2044     return;
2045 
2046   // The types match.  Link up the redeclaration chain and merge attributes if
2047   // the old declaration was a typedef.
2048   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2049     New->setPreviousDecl(Typedef);
2050     mergeDeclAttributes(New, Old);
2051   }
2052 
2053   if (getLangOpts().MicrosoftExt)
2054     return;
2055 
2056   if (getLangOpts().CPlusPlus) {
2057     // C++ [dcl.typedef]p2:
2058     //   In a given non-class scope, a typedef specifier can be used to
2059     //   redefine the name of any type declared in that scope to refer
2060     //   to the type to which it already refers.
2061     if (!isa<CXXRecordDecl>(CurContext))
2062       return;
2063 
2064     // C++0x [dcl.typedef]p4:
2065     //   In a given class scope, a typedef specifier can be used to redefine
2066     //   any class-name declared in that scope that is not also a typedef-name
2067     //   to refer to the type to which it already refers.
2068     //
2069     // This wording came in via DR424, which was a correction to the
2070     // wording in DR56, which accidentally banned code like:
2071     //
2072     //   struct S {
2073     //     typedef struct A { } A;
2074     //   };
2075     //
2076     // in the C++03 standard. We implement the C++0x semantics, which
2077     // allow the above but disallow
2078     //
2079     //   struct S {
2080     //     typedef int I;
2081     //     typedef int I;
2082     //   };
2083     //
2084     // since that was the intent of DR56.
2085     if (!isa<TypedefNameDecl>(Old))
2086       return;
2087 
2088     Diag(New->getLocation(), diag::err_redefinition)
2089       << New->getDeclName();
2090     Diag(Old->getLocation(), diag::note_previous_definition);
2091     return New->setInvalidDecl();
2092   }
2093 
2094   // Modules always permit redefinition of typedefs, as does C11.
2095   if (getLangOpts().Modules || getLangOpts().C11)
2096     return;
2097 
2098   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2099   // is normally mapped to an error, but can be controlled with
2100   // -Wtypedef-redefinition.  If either the original or the redefinition is
2101   // in a system header, don't emit this for compatibility with GCC.
2102   if (getDiagnostics().getSuppressSystemWarnings() &&
2103       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2104        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2105     return;
2106 
2107   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2108     << New->getDeclName();
2109   Diag(Old->getLocation(), diag::note_previous_definition);
2110 }
2111 
2112 /// DeclhasAttr - returns true if decl Declaration already has the target
2113 /// attribute.
2114 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2115   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2116   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2117   for (const auto *i : D->attrs())
2118     if (i->getKind() == A->getKind()) {
2119       if (Ann) {
2120         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2121           return true;
2122         continue;
2123       }
2124       // FIXME: Don't hardcode this check
2125       if (OA && isa<OwnershipAttr>(i))
2126         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2127       return true;
2128     }
2129 
2130   return false;
2131 }
2132 
2133 static bool isAttributeTargetADefinition(Decl *D) {
2134   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2135     return VD->isThisDeclarationADefinition();
2136   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2137     return TD->isCompleteDefinition() || TD->isBeingDefined();
2138   return true;
2139 }
2140 
2141 /// Merge alignment attributes from \p Old to \p New, taking into account the
2142 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2143 ///
2144 /// \return \c true if any attributes were added to \p New.
2145 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2146   // Look for alignas attributes on Old, and pick out whichever attribute
2147   // specifies the strictest alignment requirement.
2148   AlignedAttr *OldAlignasAttr = nullptr;
2149   AlignedAttr *OldStrictestAlignAttr = nullptr;
2150   unsigned OldAlign = 0;
2151   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2152     // FIXME: We have no way of representing inherited dependent alignments
2153     // in a case like:
2154     //   template<int A, int B> struct alignas(A) X;
2155     //   template<int A, int B> struct alignas(B) X {};
2156     // For now, we just ignore any alignas attributes which are not on the
2157     // definition in such a case.
2158     if (I->isAlignmentDependent())
2159       return false;
2160 
2161     if (I->isAlignas())
2162       OldAlignasAttr = I;
2163 
2164     unsigned Align = I->getAlignment(S.Context);
2165     if (Align > OldAlign) {
2166       OldAlign = Align;
2167       OldStrictestAlignAttr = I;
2168     }
2169   }
2170 
2171   // Look for alignas attributes on New.
2172   AlignedAttr *NewAlignasAttr = nullptr;
2173   unsigned NewAlign = 0;
2174   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2175     if (I->isAlignmentDependent())
2176       return false;
2177 
2178     if (I->isAlignas())
2179       NewAlignasAttr = I;
2180 
2181     unsigned Align = I->getAlignment(S.Context);
2182     if (Align > NewAlign)
2183       NewAlign = Align;
2184   }
2185 
2186   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2187     // Both declarations have 'alignas' attributes. We require them to match.
2188     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2189     // fall short. (If two declarations both have alignas, they must both match
2190     // every definition, and so must match each other if there is a definition.)
2191 
2192     // If either declaration only contains 'alignas(0)' specifiers, then it
2193     // specifies the natural alignment for the type.
2194     if (OldAlign == 0 || NewAlign == 0) {
2195       QualType Ty;
2196       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2197         Ty = VD->getType();
2198       else
2199         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2200 
2201       if (OldAlign == 0)
2202         OldAlign = S.Context.getTypeAlign(Ty);
2203       if (NewAlign == 0)
2204         NewAlign = S.Context.getTypeAlign(Ty);
2205     }
2206 
2207     if (OldAlign != NewAlign) {
2208       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2209         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2210         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2211       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2212     }
2213   }
2214 
2215   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2216     // C++11 [dcl.align]p6:
2217     //   if any declaration of an entity has an alignment-specifier,
2218     //   every defining declaration of that entity shall specify an
2219     //   equivalent alignment.
2220     // C11 6.7.5/7:
2221     //   If the definition of an object does not have an alignment
2222     //   specifier, any other declaration of that object shall also
2223     //   have no alignment specifier.
2224     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2225       << OldAlignasAttr;
2226     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2227       << OldAlignasAttr;
2228   }
2229 
2230   bool AnyAdded = false;
2231 
2232   // Ensure we have an attribute representing the strictest alignment.
2233   if (OldAlign > NewAlign) {
2234     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2235     Clone->setInherited(true);
2236     New->addAttr(Clone);
2237     AnyAdded = true;
2238   }
2239 
2240   // Ensure we have an alignas attribute if the old declaration had one.
2241   if (OldAlignasAttr && !NewAlignasAttr &&
2242       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2243     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2244     Clone->setInherited(true);
2245     New->addAttr(Clone);
2246     AnyAdded = true;
2247   }
2248 
2249   return AnyAdded;
2250 }
2251 
2252 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2253                                const InheritableAttr *Attr,
2254                                Sema::AvailabilityMergeKind AMK) {
2255   // This function copies an attribute Attr from a previous declaration to the
2256   // new declaration D if the new declaration doesn't itself have that attribute
2257   // yet or if that attribute allows duplicates.
2258   // If you're adding a new attribute that requires logic different from
2259   // "use explicit attribute on decl if present, else use attribute from
2260   // previous decl", for example if the attribute needs to be consistent
2261   // between redeclarations, you need to call a custom merge function here.
2262   InheritableAttr *NewAttr = nullptr;
2263   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2264   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2265     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2266                                       AA->isImplicit(), AA->getIntroduced(),
2267                                       AA->getDeprecated(),
2268                                       AA->getObsoleted(), AA->getUnavailable(),
2269                                       AA->getMessage(), AA->getStrict(),
2270                                       AA->getReplacement(), AMK,
2271                                       AttrSpellingListIndex);
2272   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2273     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2274                                     AttrSpellingListIndex);
2275   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2276     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2277                                         AttrSpellingListIndex);
2278   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2279     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2280                                    AttrSpellingListIndex);
2281   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2282     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2283                                    AttrSpellingListIndex);
2284   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2285     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2286                                 FA->getFormatIdx(), FA->getFirstArg(),
2287                                 AttrSpellingListIndex);
2288   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2289     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2290                                  AttrSpellingListIndex);
2291   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2292     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2293                                        AttrSpellingListIndex,
2294                                        IA->getSemanticSpelling());
2295   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2296     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2297                                       &S.Context.Idents.get(AA->getSpelling()),
2298                                       AttrSpellingListIndex);
2299   else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2300            (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2301             isa<CUDAGlobalAttr>(Attr))) {
2302     // CUDA target attributes are part of function signature for
2303     // overloading purposes and must not be merged.
2304     return false;
2305   } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2306     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2307   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2308     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2309   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2310     NewAttr = S.mergeInternalLinkageAttr(
2311         D, InternalLinkageA->getRange(),
2312         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2313         AttrSpellingListIndex);
2314   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2315     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2316                                 &S.Context.Idents.get(CommonA->getSpelling()),
2317                                 AttrSpellingListIndex);
2318   else if (isa<AlignedAttr>(Attr))
2319     // AlignedAttrs are handled separately, because we need to handle all
2320     // such attributes on a declaration at the same time.
2321     NewAttr = nullptr;
2322   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2323            (AMK == Sema::AMK_Override ||
2324             AMK == Sema::AMK_ProtocolImplementation))
2325     NewAttr = nullptr;
2326   else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2327     NewAttr = S.mergeUuidAttr(D, UA->getRange(), AttrSpellingListIndex,
2328                               UA->getGuid());
2329   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2330     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2331 
2332   if (NewAttr) {
2333     NewAttr->setInherited(true);
2334     D->addAttr(NewAttr);
2335     if (isa<MSInheritanceAttr>(NewAttr))
2336       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2337     return true;
2338   }
2339 
2340   return false;
2341 }
2342 
2343 static const Decl *getDefinition(const Decl *D) {
2344   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2345     return TD->getDefinition();
2346   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2347     const VarDecl *Def = VD->getDefinition();
2348     if (Def)
2349       return Def;
2350     return VD->getActingDefinition();
2351   }
2352   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2353     return FD->getDefinition();
2354   return nullptr;
2355 }
2356 
2357 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2358   for (const auto *Attribute : D->attrs())
2359     if (Attribute->getKind() == Kind)
2360       return true;
2361   return false;
2362 }
2363 
2364 /// checkNewAttributesAfterDef - If we already have a definition, check that
2365 /// there are no new attributes in this declaration.
2366 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2367   if (!New->hasAttrs())
2368     return;
2369 
2370   const Decl *Def = getDefinition(Old);
2371   if (!Def || Def == New)
2372     return;
2373 
2374   AttrVec &NewAttributes = New->getAttrs();
2375   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2376     const Attr *NewAttribute = NewAttributes[I];
2377 
2378     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2379       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2380         Sema::SkipBodyInfo SkipBody;
2381         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2382 
2383         // If we're skipping this definition, drop the "alias" attribute.
2384         if (SkipBody.ShouldSkip) {
2385           NewAttributes.erase(NewAttributes.begin() + I);
2386           --E;
2387           continue;
2388         }
2389       } else {
2390         VarDecl *VD = cast<VarDecl>(New);
2391         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2392                                 VarDecl::TentativeDefinition
2393                             ? diag::err_alias_after_tentative
2394                             : diag::err_redefinition;
2395         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2396         S.Diag(Def->getLocation(), diag::note_previous_definition);
2397         VD->setInvalidDecl();
2398       }
2399       ++I;
2400       continue;
2401     }
2402 
2403     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2404       // Tentative definitions are only interesting for the alias check above.
2405       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2406         ++I;
2407         continue;
2408       }
2409     }
2410 
2411     if (hasAttribute(Def, NewAttribute->getKind())) {
2412       ++I;
2413       continue; // regular attr merging will take care of validating this.
2414     }
2415 
2416     if (isa<C11NoReturnAttr>(NewAttribute)) {
2417       // C's _Noreturn is allowed to be added to a function after it is defined.
2418       ++I;
2419       continue;
2420     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2421       if (AA->isAlignas()) {
2422         // C++11 [dcl.align]p6:
2423         //   if any declaration of an entity has an alignment-specifier,
2424         //   every defining declaration of that entity shall specify an
2425         //   equivalent alignment.
2426         // C11 6.7.5/7:
2427         //   If the definition of an object does not have an alignment
2428         //   specifier, any other declaration of that object shall also
2429         //   have no alignment specifier.
2430         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2431           << AA;
2432         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2433           << AA;
2434         NewAttributes.erase(NewAttributes.begin() + I);
2435         --E;
2436         continue;
2437       }
2438     }
2439 
2440     S.Diag(NewAttribute->getLocation(),
2441            diag::warn_attribute_precede_definition);
2442     S.Diag(Def->getLocation(), diag::note_previous_definition);
2443     NewAttributes.erase(NewAttributes.begin() + I);
2444     --E;
2445   }
2446 }
2447 
2448 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2449 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2450                                AvailabilityMergeKind AMK) {
2451   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2452     UsedAttr *NewAttr = OldAttr->clone(Context);
2453     NewAttr->setInherited(true);
2454     New->addAttr(NewAttr);
2455   }
2456 
2457   if (!Old->hasAttrs() && !New->hasAttrs())
2458     return;
2459 
2460   // Attributes declared post-definition are currently ignored.
2461   checkNewAttributesAfterDef(*this, New, Old);
2462 
2463   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2464     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2465       if (OldA->getLabel() != NewA->getLabel()) {
2466         // This redeclaration changes __asm__ label.
2467         Diag(New->getLocation(), diag::err_different_asm_label);
2468         Diag(OldA->getLocation(), diag::note_previous_declaration);
2469       }
2470     } else if (Old->isUsed()) {
2471       // This redeclaration adds an __asm__ label to a declaration that has
2472       // already been ODR-used.
2473       Diag(New->getLocation(), diag::err_late_asm_label_name)
2474         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2475     }
2476   }
2477 
2478   // Re-declaration cannot add abi_tag's.
2479   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2480     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2481       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2482         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2483                       NewTag) == OldAbiTagAttr->tags_end()) {
2484           Diag(NewAbiTagAttr->getLocation(),
2485                diag::err_new_abi_tag_on_redeclaration)
2486               << NewTag;
2487           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2488         }
2489       }
2490     } else {
2491       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2492       Diag(Old->getLocation(), diag::note_previous_declaration);
2493     }
2494   }
2495 
2496   if (!Old->hasAttrs())
2497     return;
2498 
2499   bool foundAny = New->hasAttrs();
2500 
2501   // Ensure that any moving of objects within the allocated map is done before
2502   // we process them.
2503   if (!foundAny) New->setAttrs(AttrVec());
2504 
2505   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2506     // Ignore deprecated/unavailable/availability attributes if requested.
2507     AvailabilityMergeKind LocalAMK = AMK_None;
2508     if (isa<DeprecatedAttr>(I) ||
2509         isa<UnavailableAttr>(I) ||
2510         isa<AvailabilityAttr>(I)) {
2511       switch (AMK) {
2512       case AMK_None:
2513         continue;
2514 
2515       case AMK_Redeclaration:
2516       case AMK_Override:
2517       case AMK_ProtocolImplementation:
2518         LocalAMK = AMK;
2519         break;
2520       }
2521     }
2522 
2523     // Already handled.
2524     if (isa<UsedAttr>(I))
2525       continue;
2526 
2527     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2528       foundAny = true;
2529   }
2530 
2531   if (mergeAlignedAttrs(*this, New, Old))
2532     foundAny = true;
2533 
2534   if (!foundAny) New->dropAttrs();
2535 }
2536 
2537 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2538 /// to the new one.
2539 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2540                                      const ParmVarDecl *oldDecl,
2541                                      Sema &S) {
2542   // C++11 [dcl.attr.depend]p2:
2543   //   The first declaration of a function shall specify the
2544   //   carries_dependency attribute for its declarator-id if any declaration
2545   //   of the function specifies the carries_dependency attribute.
2546   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2547   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2548     S.Diag(CDA->getLocation(),
2549            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2550     // Find the first declaration of the parameter.
2551     // FIXME: Should we build redeclaration chains for function parameters?
2552     const FunctionDecl *FirstFD =
2553       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2554     const ParmVarDecl *FirstVD =
2555       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2556     S.Diag(FirstVD->getLocation(),
2557            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2558   }
2559 
2560   if (!oldDecl->hasAttrs())
2561     return;
2562 
2563   bool foundAny = newDecl->hasAttrs();
2564 
2565   // Ensure that any moving of objects within the allocated map is
2566   // done before we process them.
2567   if (!foundAny) newDecl->setAttrs(AttrVec());
2568 
2569   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2570     if (!DeclHasAttr(newDecl, I)) {
2571       InheritableAttr *newAttr =
2572         cast<InheritableParamAttr>(I->clone(S.Context));
2573       newAttr->setInherited(true);
2574       newDecl->addAttr(newAttr);
2575       foundAny = true;
2576     }
2577   }
2578 
2579   if (!foundAny) newDecl->dropAttrs();
2580 }
2581 
2582 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2583                                 const ParmVarDecl *OldParam,
2584                                 Sema &S) {
2585   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2586     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2587       if (*Oldnullability != *Newnullability) {
2588         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2589           << DiagNullabilityKind(
2590                *Newnullability,
2591                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2592                 != 0))
2593           << DiagNullabilityKind(
2594                *Oldnullability,
2595                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2596                 != 0));
2597         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2598       }
2599     } else {
2600       QualType NewT = NewParam->getType();
2601       NewT = S.Context.getAttributedType(
2602                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2603                          NewT, NewT);
2604       NewParam->setType(NewT);
2605     }
2606   }
2607 }
2608 
2609 namespace {
2610 
2611 /// Used in MergeFunctionDecl to keep track of function parameters in
2612 /// C.
2613 struct GNUCompatibleParamWarning {
2614   ParmVarDecl *OldParm;
2615   ParmVarDecl *NewParm;
2616   QualType PromotedType;
2617 };
2618 
2619 } // end anonymous namespace
2620 
2621 /// getSpecialMember - get the special member enum for a method.
2622 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2623   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2624     if (Ctor->isDefaultConstructor())
2625       return Sema::CXXDefaultConstructor;
2626 
2627     if (Ctor->isCopyConstructor())
2628       return Sema::CXXCopyConstructor;
2629 
2630     if (Ctor->isMoveConstructor())
2631       return Sema::CXXMoveConstructor;
2632   } else if (isa<CXXDestructorDecl>(MD)) {
2633     return Sema::CXXDestructor;
2634   } else if (MD->isCopyAssignmentOperator()) {
2635     return Sema::CXXCopyAssignment;
2636   } else if (MD->isMoveAssignmentOperator()) {
2637     return Sema::CXXMoveAssignment;
2638   }
2639 
2640   return Sema::CXXInvalid;
2641 }
2642 
2643 // Determine whether the previous declaration was a definition, implicit
2644 // declaration, or a declaration.
2645 template <typename T>
2646 static std::pair<diag::kind, SourceLocation>
2647 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2648   diag::kind PrevDiag;
2649   SourceLocation OldLocation = Old->getLocation();
2650   if (Old->isThisDeclarationADefinition())
2651     PrevDiag = diag::note_previous_definition;
2652   else if (Old->isImplicit()) {
2653     PrevDiag = diag::note_previous_implicit_declaration;
2654     if (OldLocation.isInvalid())
2655       OldLocation = New->getLocation();
2656   } else
2657     PrevDiag = diag::note_previous_declaration;
2658   return std::make_pair(PrevDiag, OldLocation);
2659 }
2660 
2661 /// canRedefineFunction - checks if a function can be redefined. Currently,
2662 /// only extern inline functions can be redefined, and even then only in
2663 /// GNU89 mode.
2664 static bool canRedefineFunction(const FunctionDecl *FD,
2665                                 const LangOptions& LangOpts) {
2666   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2667           !LangOpts.CPlusPlus &&
2668           FD->isInlineSpecified() &&
2669           FD->getStorageClass() == SC_Extern);
2670 }
2671 
2672 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2673   const AttributedType *AT = T->getAs<AttributedType>();
2674   while (AT && !AT->isCallingConv())
2675     AT = AT->getModifiedType()->getAs<AttributedType>();
2676   return AT;
2677 }
2678 
2679 template <typename T>
2680 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2681   const DeclContext *DC = Old->getDeclContext();
2682   if (DC->isRecord())
2683     return false;
2684 
2685   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2686   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2687     return true;
2688   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2689     return true;
2690   return false;
2691 }
2692 
2693 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2694 static bool isExternC(VarTemplateDecl *) { return false; }
2695 
2696 /// \brief Check whether a redeclaration of an entity introduced by a
2697 /// using-declaration is valid, given that we know it's not an overload
2698 /// (nor a hidden tag declaration).
2699 template<typename ExpectedDecl>
2700 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2701                                    ExpectedDecl *New) {
2702   // C++11 [basic.scope.declarative]p4:
2703   //   Given a set of declarations in a single declarative region, each of
2704   //   which specifies the same unqualified name,
2705   //   -- they shall all refer to the same entity, or all refer to functions
2706   //      and function templates; or
2707   //   -- exactly one declaration shall declare a class name or enumeration
2708   //      name that is not a typedef name and the other declarations shall all
2709   //      refer to the same variable or enumerator, or all refer to functions
2710   //      and function templates; in this case the class name or enumeration
2711   //      name is hidden (3.3.10).
2712 
2713   // C++11 [namespace.udecl]p14:
2714   //   If a function declaration in namespace scope or block scope has the
2715   //   same name and the same parameter-type-list as a function introduced
2716   //   by a using-declaration, and the declarations do not declare the same
2717   //   function, the program is ill-formed.
2718 
2719   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2720   if (Old &&
2721       !Old->getDeclContext()->getRedeclContext()->Equals(
2722           New->getDeclContext()->getRedeclContext()) &&
2723       !(isExternC(Old) && isExternC(New)))
2724     Old = nullptr;
2725 
2726   if (!Old) {
2727     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2728     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2729     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2730     return true;
2731   }
2732   return false;
2733 }
2734 
2735 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2736                                             const FunctionDecl *B) {
2737   assert(A->getNumParams() == B->getNumParams());
2738 
2739   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2740     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2741     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2742     if (AttrA == AttrB)
2743       return true;
2744     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2745   };
2746 
2747   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2748 }
2749 
2750 /// MergeFunctionDecl - We just parsed a function 'New' from
2751 /// declarator D which has the same name and scope as a previous
2752 /// declaration 'Old'.  Figure out how to resolve this situation,
2753 /// merging decls or emitting diagnostics as appropriate.
2754 ///
2755 /// In C++, New and Old must be declarations that are not
2756 /// overloaded. Use IsOverload to determine whether New and Old are
2757 /// overloaded, and to select the Old declaration that New should be
2758 /// merged with.
2759 ///
2760 /// Returns true if there was an error, false otherwise.
2761 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2762                              Scope *S, bool MergeTypeWithOld) {
2763   // Verify the old decl was also a function.
2764   FunctionDecl *Old = OldD->getAsFunction();
2765   if (!Old) {
2766     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2767       if (New->getFriendObjectKind()) {
2768         Diag(New->getLocation(), diag::err_using_decl_friend);
2769         Diag(Shadow->getTargetDecl()->getLocation(),
2770              diag::note_using_decl_target);
2771         Diag(Shadow->getUsingDecl()->getLocation(),
2772              diag::note_using_decl) << 0;
2773         return true;
2774       }
2775 
2776       // Check whether the two declarations might declare the same function.
2777       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2778         return true;
2779       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2780     } else {
2781       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2782         << New->getDeclName();
2783       Diag(OldD->getLocation(), diag::note_previous_definition);
2784       return true;
2785     }
2786   }
2787 
2788   // If the old declaration is invalid, just give up here.
2789   if (Old->isInvalidDecl())
2790     return true;
2791 
2792   diag::kind PrevDiag;
2793   SourceLocation OldLocation;
2794   std::tie(PrevDiag, OldLocation) =
2795       getNoteDiagForInvalidRedeclaration(Old, New);
2796 
2797   // Don't complain about this if we're in GNU89 mode and the old function
2798   // is an extern inline function.
2799   // Don't complain about specializations. They are not supposed to have
2800   // storage classes.
2801   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2802       New->getStorageClass() == SC_Static &&
2803       Old->hasExternalFormalLinkage() &&
2804       !New->getTemplateSpecializationInfo() &&
2805       !canRedefineFunction(Old, getLangOpts())) {
2806     if (getLangOpts().MicrosoftExt) {
2807       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2808       Diag(OldLocation, PrevDiag);
2809     } else {
2810       Diag(New->getLocation(), diag::err_static_non_static) << New;
2811       Diag(OldLocation, PrevDiag);
2812       return true;
2813     }
2814   }
2815 
2816   if (New->hasAttr<InternalLinkageAttr>() &&
2817       !Old->hasAttr<InternalLinkageAttr>()) {
2818     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2819         << New->getDeclName();
2820     Diag(Old->getLocation(), diag::note_previous_definition);
2821     New->dropAttr<InternalLinkageAttr>();
2822   }
2823 
2824   // If a function is first declared with a calling convention, but is later
2825   // declared or defined without one, all following decls assume the calling
2826   // convention of the first.
2827   //
2828   // It's OK if a function is first declared without a calling convention,
2829   // but is later declared or defined with the default calling convention.
2830   //
2831   // To test if either decl has an explicit calling convention, we look for
2832   // AttributedType sugar nodes on the type as written.  If they are missing or
2833   // were canonicalized away, we assume the calling convention was implicit.
2834   //
2835   // Note also that we DO NOT return at this point, because we still have
2836   // other tests to run.
2837   QualType OldQType = Context.getCanonicalType(Old->getType());
2838   QualType NewQType = Context.getCanonicalType(New->getType());
2839   const FunctionType *OldType = cast<FunctionType>(OldQType);
2840   const FunctionType *NewType = cast<FunctionType>(NewQType);
2841   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2842   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2843   bool RequiresAdjustment = false;
2844 
2845   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2846     FunctionDecl *First = Old->getFirstDecl();
2847     const FunctionType *FT =
2848         First->getType().getCanonicalType()->castAs<FunctionType>();
2849     FunctionType::ExtInfo FI = FT->getExtInfo();
2850     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2851     if (!NewCCExplicit) {
2852       // Inherit the CC from the previous declaration if it was specified
2853       // there but not here.
2854       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2855       RequiresAdjustment = true;
2856     } else {
2857       // Calling conventions aren't compatible, so complain.
2858       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2859       Diag(New->getLocation(), diag::err_cconv_change)
2860         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2861         << !FirstCCExplicit
2862         << (!FirstCCExplicit ? "" :
2863             FunctionType::getNameForCallConv(FI.getCC()));
2864 
2865       // Put the note on the first decl, since it is the one that matters.
2866       Diag(First->getLocation(), diag::note_previous_declaration);
2867       return true;
2868     }
2869   }
2870 
2871   // FIXME: diagnose the other way around?
2872   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2873     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2874     RequiresAdjustment = true;
2875   }
2876 
2877   // Merge regparm attribute.
2878   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2879       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2880     if (NewTypeInfo.getHasRegParm()) {
2881       Diag(New->getLocation(), diag::err_regparm_mismatch)
2882         << NewType->getRegParmType()
2883         << OldType->getRegParmType();
2884       Diag(OldLocation, diag::note_previous_declaration);
2885       return true;
2886     }
2887 
2888     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2889     RequiresAdjustment = true;
2890   }
2891 
2892   // Merge ns_returns_retained attribute.
2893   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2894     if (NewTypeInfo.getProducesResult()) {
2895       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2896       Diag(OldLocation, diag::note_previous_declaration);
2897       return true;
2898     }
2899 
2900     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2901     RequiresAdjustment = true;
2902   }
2903 
2904   if (RequiresAdjustment) {
2905     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2906     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2907     New->setType(QualType(AdjustedType, 0));
2908     NewQType = Context.getCanonicalType(New->getType());
2909     NewType = cast<FunctionType>(NewQType);
2910   }
2911 
2912   // If this redeclaration makes the function inline, we may need to add it to
2913   // UndefinedButUsed.
2914   if (!Old->isInlined() && New->isInlined() &&
2915       !New->hasAttr<GNUInlineAttr>() &&
2916       !getLangOpts().GNUInline &&
2917       Old->isUsed(false) &&
2918       !Old->isDefined() && !New->isThisDeclarationADefinition())
2919     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2920                                            SourceLocation()));
2921 
2922   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2923   // about it.
2924   if (New->hasAttr<GNUInlineAttr>() &&
2925       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2926     UndefinedButUsed.erase(Old->getCanonicalDecl());
2927   }
2928 
2929   // If pass_object_size params don't match up perfectly, this isn't a valid
2930   // redeclaration.
2931   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
2932       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
2933     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
2934         << New->getDeclName();
2935     Diag(OldLocation, PrevDiag) << Old << Old->getType();
2936     return true;
2937   }
2938 
2939   if (getLangOpts().CPlusPlus) {
2940     // C++1z [over.load]p2
2941     //   Certain function declarations cannot be overloaded:
2942     //     -- Function declarations that differ only in the return type,
2943     //        the exception specification, or both cannot be overloaded.
2944 
2945     // Check the exception specifications match. This may recompute the type of
2946     // both Old and New if it resolved exception specifications, so grab the
2947     // types again after this. Because this updates the type, we do this before
2948     // any of the other checks below, which may update the "de facto" NewQType
2949     // but do not necessarily update the type of New.
2950     if (CheckEquivalentExceptionSpec(Old, New))
2951       return true;
2952     OldQType = Context.getCanonicalType(Old->getType());
2953     NewQType = Context.getCanonicalType(New->getType());
2954 
2955     // Go back to the type source info to compare the declared return types,
2956     // per C++1y [dcl.type.auto]p13:
2957     //   Redeclarations or specializations of a function or function template
2958     //   with a declared return type that uses a placeholder type shall also
2959     //   use that placeholder, not a deduced type.
2960     QualType OldDeclaredReturnType =
2961         (Old->getTypeSourceInfo()
2962              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2963              : OldType)->getReturnType();
2964     QualType NewDeclaredReturnType =
2965         (New->getTypeSourceInfo()
2966              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2967              : NewType)->getReturnType();
2968     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2969         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2970           New->isLocalExternDecl())) {
2971       QualType ResQT;
2972       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2973           OldDeclaredReturnType->isObjCObjectPointerType())
2974         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2975       if (ResQT.isNull()) {
2976         if (New->isCXXClassMember() && New->isOutOfLine())
2977           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2978               << New << New->getReturnTypeSourceRange();
2979         else
2980           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2981               << New->getReturnTypeSourceRange();
2982         Diag(OldLocation, PrevDiag) << Old << Old->getType()
2983                                     << Old->getReturnTypeSourceRange();
2984         return true;
2985       }
2986       else
2987         NewQType = ResQT;
2988     }
2989 
2990     QualType OldReturnType = OldType->getReturnType();
2991     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2992     if (OldReturnType != NewReturnType) {
2993       // If this function has a deduced return type and has already been
2994       // defined, copy the deduced value from the old declaration.
2995       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2996       if (OldAT && OldAT->isDeduced()) {
2997         New->setType(
2998             SubstAutoType(New->getType(),
2999                           OldAT->isDependentType() ? Context.DependentTy
3000                                                    : OldAT->getDeducedType()));
3001         NewQType = Context.getCanonicalType(
3002             SubstAutoType(NewQType,
3003                           OldAT->isDependentType() ? Context.DependentTy
3004                                                    : OldAT->getDeducedType()));
3005       }
3006     }
3007 
3008     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3009     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3010     if (OldMethod && NewMethod) {
3011       // Preserve triviality.
3012       NewMethod->setTrivial(OldMethod->isTrivial());
3013 
3014       // MSVC allows explicit template specialization at class scope:
3015       // 2 CXXMethodDecls referring to the same function will be injected.
3016       // We don't want a redeclaration error.
3017       bool IsClassScopeExplicitSpecialization =
3018                               OldMethod->isFunctionTemplateSpecialization() &&
3019                               NewMethod->isFunctionTemplateSpecialization();
3020       bool isFriend = NewMethod->getFriendObjectKind();
3021 
3022       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3023           !IsClassScopeExplicitSpecialization) {
3024         //    -- Member function declarations with the same name and the
3025         //       same parameter types cannot be overloaded if any of them
3026         //       is a static member function declaration.
3027         if (OldMethod->isStatic() != NewMethod->isStatic()) {
3028           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3029           Diag(OldLocation, PrevDiag) << Old << Old->getType();
3030           return true;
3031         }
3032 
3033         // C++ [class.mem]p1:
3034         //   [...] A member shall not be declared twice in the
3035         //   member-specification, except that a nested class or member
3036         //   class template can be declared and then later defined.
3037         if (ActiveTemplateInstantiations.empty()) {
3038           unsigned NewDiag;
3039           if (isa<CXXConstructorDecl>(OldMethod))
3040             NewDiag = diag::err_constructor_redeclared;
3041           else if (isa<CXXDestructorDecl>(NewMethod))
3042             NewDiag = diag::err_destructor_redeclared;
3043           else if (isa<CXXConversionDecl>(NewMethod))
3044             NewDiag = diag::err_conv_function_redeclared;
3045           else
3046             NewDiag = diag::err_member_redeclared;
3047 
3048           Diag(New->getLocation(), NewDiag);
3049         } else {
3050           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3051             << New << New->getType();
3052         }
3053         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3054         return true;
3055 
3056       // Complain if this is an explicit declaration of a special
3057       // member that was initially declared implicitly.
3058       //
3059       // As an exception, it's okay to befriend such methods in order
3060       // to permit the implicit constructor/destructor/operator calls.
3061       } else if (OldMethod->isImplicit()) {
3062         if (isFriend) {
3063           NewMethod->setImplicit();
3064         } else {
3065           Diag(NewMethod->getLocation(),
3066                diag::err_definition_of_implicitly_declared_member)
3067             << New << getSpecialMember(OldMethod);
3068           return true;
3069         }
3070       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3071         Diag(NewMethod->getLocation(),
3072              diag::err_definition_of_explicitly_defaulted_member)
3073           << getSpecialMember(OldMethod);
3074         return true;
3075       }
3076     }
3077 
3078     // C++11 [dcl.attr.noreturn]p1:
3079     //   The first declaration of a function shall specify the noreturn
3080     //   attribute if any declaration of that function specifies the noreturn
3081     //   attribute.
3082     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3083     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3084       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3085       Diag(Old->getFirstDecl()->getLocation(),
3086            diag::note_noreturn_missing_first_decl);
3087     }
3088 
3089     // C++11 [dcl.attr.depend]p2:
3090     //   The first declaration of a function shall specify the
3091     //   carries_dependency attribute for its declarator-id if any declaration
3092     //   of the function specifies the carries_dependency attribute.
3093     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3094     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3095       Diag(CDA->getLocation(),
3096            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3097       Diag(Old->getFirstDecl()->getLocation(),
3098            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3099     }
3100 
3101     // (C++98 8.3.5p3):
3102     //   All declarations for a function shall agree exactly in both the
3103     //   return type and the parameter-type-list.
3104     // We also want to respect all the extended bits except noreturn.
3105 
3106     // noreturn should now match unless the old type info didn't have it.
3107     QualType OldQTypeForComparison = OldQType;
3108     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3109       auto *OldType = OldQType->castAs<FunctionProtoType>();
3110       const FunctionType *OldTypeForComparison
3111         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3112       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3113       assert(OldQTypeForComparison.isCanonical());
3114     }
3115 
3116     if (haveIncompatibleLanguageLinkages(Old, New)) {
3117       // As a special case, retain the language linkage from previous
3118       // declarations of a friend function as an extension.
3119       //
3120       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3121       // and is useful because there's otherwise no way to specify language
3122       // linkage within class scope.
3123       //
3124       // Check cautiously as the friend object kind isn't yet complete.
3125       if (New->getFriendObjectKind() != Decl::FOK_None) {
3126         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3127         Diag(OldLocation, PrevDiag);
3128       } else {
3129         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3130         Diag(OldLocation, PrevDiag);
3131         return true;
3132       }
3133     }
3134 
3135     if (OldQTypeForComparison == NewQType)
3136       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3137 
3138     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3139         New->isLocalExternDecl()) {
3140       // It's OK if we couldn't merge types for a local function declaraton
3141       // if either the old or new type is dependent. We'll merge the types
3142       // when we instantiate the function.
3143       return false;
3144     }
3145 
3146     // Fall through for conflicting redeclarations and redefinitions.
3147   }
3148 
3149   // C: Function types need to be compatible, not identical. This handles
3150   // duplicate function decls like "void f(int); void f(enum X);" properly.
3151   if (!getLangOpts().CPlusPlus &&
3152       Context.typesAreCompatible(OldQType, NewQType)) {
3153     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3154     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3155     const FunctionProtoType *OldProto = nullptr;
3156     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3157         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3158       // The old declaration provided a function prototype, but the
3159       // new declaration does not. Merge in the prototype.
3160       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3161       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3162       NewQType =
3163           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3164                                   OldProto->getExtProtoInfo());
3165       New->setType(NewQType);
3166       New->setHasInheritedPrototype();
3167 
3168       // Synthesize parameters with the same types.
3169       SmallVector<ParmVarDecl*, 16> Params;
3170       for (const auto &ParamType : OldProto->param_types()) {
3171         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3172                                                  SourceLocation(), nullptr,
3173                                                  ParamType, /*TInfo=*/nullptr,
3174                                                  SC_None, nullptr);
3175         Param->setScopeInfo(0, Params.size());
3176         Param->setImplicit();
3177         Params.push_back(Param);
3178       }
3179 
3180       New->setParams(Params);
3181     }
3182 
3183     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3184   }
3185 
3186   // GNU C permits a K&R definition to follow a prototype declaration
3187   // if the declared types of the parameters in the K&R definition
3188   // match the types in the prototype declaration, even when the
3189   // promoted types of the parameters from the K&R definition differ
3190   // from the types in the prototype. GCC then keeps the types from
3191   // the prototype.
3192   //
3193   // If a variadic prototype is followed by a non-variadic K&R definition,
3194   // the K&R definition becomes variadic.  This is sort of an edge case, but
3195   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3196   // C99 6.9.1p8.
3197   if (!getLangOpts().CPlusPlus &&
3198       Old->hasPrototype() && !New->hasPrototype() &&
3199       New->getType()->getAs<FunctionProtoType>() &&
3200       Old->getNumParams() == New->getNumParams()) {
3201     SmallVector<QualType, 16> ArgTypes;
3202     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3203     const FunctionProtoType *OldProto
3204       = Old->getType()->getAs<FunctionProtoType>();
3205     const FunctionProtoType *NewProto
3206       = New->getType()->getAs<FunctionProtoType>();
3207 
3208     // Determine whether this is the GNU C extension.
3209     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3210                                                NewProto->getReturnType());
3211     bool LooseCompatible = !MergedReturn.isNull();
3212     for (unsigned Idx = 0, End = Old->getNumParams();
3213          LooseCompatible && Idx != End; ++Idx) {
3214       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3215       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3216       if (Context.typesAreCompatible(OldParm->getType(),
3217                                      NewProto->getParamType(Idx))) {
3218         ArgTypes.push_back(NewParm->getType());
3219       } else if (Context.typesAreCompatible(OldParm->getType(),
3220                                             NewParm->getType(),
3221                                             /*CompareUnqualified=*/true)) {
3222         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3223                                            NewProto->getParamType(Idx) };
3224         Warnings.push_back(Warn);
3225         ArgTypes.push_back(NewParm->getType());
3226       } else
3227         LooseCompatible = false;
3228     }
3229 
3230     if (LooseCompatible) {
3231       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3232         Diag(Warnings[Warn].NewParm->getLocation(),
3233              diag::ext_param_promoted_not_compatible_with_prototype)
3234           << Warnings[Warn].PromotedType
3235           << Warnings[Warn].OldParm->getType();
3236         if (Warnings[Warn].OldParm->getLocation().isValid())
3237           Diag(Warnings[Warn].OldParm->getLocation(),
3238                diag::note_previous_declaration);
3239       }
3240 
3241       if (MergeTypeWithOld)
3242         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3243                                              OldProto->getExtProtoInfo()));
3244       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3245     }
3246 
3247     // Fall through to diagnose conflicting types.
3248   }
3249 
3250   // A function that has already been declared has been redeclared or
3251   // defined with a different type; show an appropriate diagnostic.
3252 
3253   // If the previous declaration was an implicitly-generated builtin
3254   // declaration, then at the very least we should use a specialized note.
3255   unsigned BuiltinID;
3256   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3257     // If it's actually a library-defined builtin function like 'malloc'
3258     // or 'printf', just warn about the incompatible redeclaration.
3259     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3260       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3261       Diag(OldLocation, diag::note_previous_builtin_declaration)
3262         << Old << Old->getType();
3263 
3264       // If this is a global redeclaration, just forget hereafter
3265       // about the "builtin-ness" of the function.
3266       //
3267       // Doing this for local extern declarations is problematic.  If
3268       // the builtin declaration remains visible, a second invalid
3269       // local declaration will produce a hard error; if it doesn't
3270       // remain visible, a single bogus local redeclaration (which is
3271       // actually only a warning) could break all the downstream code.
3272       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3273         New->getIdentifier()->revertBuiltin();
3274 
3275       return false;
3276     }
3277 
3278     PrevDiag = diag::note_previous_builtin_declaration;
3279   }
3280 
3281   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3282   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3283   return true;
3284 }
3285 
3286 /// \brief Completes the merge of two function declarations that are
3287 /// known to be compatible.
3288 ///
3289 /// This routine handles the merging of attributes and other
3290 /// properties of function declarations from the old declaration to
3291 /// the new declaration, once we know that New is in fact a
3292 /// redeclaration of Old.
3293 ///
3294 /// \returns false
3295 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3296                                         Scope *S, bool MergeTypeWithOld) {
3297   // Merge the attributes
3298   mergeDeclAttributes(New, Old);
3299 
3300   // Merge "pure" flag.
3301   if (Old->isPure())
3302     New->setPure();
3303 
3304   // Merge "used" flag.
3305   if (Old->getMostRecentDecl()->isUsed(false))
3306     New->setIsUsed();
3307 
3308   // Merge attributes from the parameters.  These can mismatch with K&R
3309   // declarations.
3310   if (New->getNumParams() == Old->getNumParams())
3311       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3312         ParmVarDecl *NewParam = New->getParamDecl(i);
3313         ParmVarDecl *OldParam = Old->getParamDecl(i);
3314         mergeParamDeclAttributes(NewParam, OldParam, *this);
3315         mergeParamDeclTypes(NewParam, OldParam, *this);
3316       }
3317 
3318   if (getLangOpts().CPlusPlus)
3319     return MergeCXXFunctionDecl(New, Old, S);
3320 
3321   // Merge the function types so the we get the composite types for the return
3322   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3323   // was visible.
3324   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3325   if (!Merged.isNull() && MergeTypeWithOld)
3326     New->setType(Merged);
3327 
3328   return false;
3329 }
3330 
3331 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3332                                 ObjCMethodDecl *oldMethod) {
3333   // Merge the attributes, including deprecated/unavailable
3334   AvailabilityMergeKind MergeKind =
3335     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3336       ? AMK_ProtocolImplementation
3337       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3338                                                        : AMK_Override;
3339 
3340   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3341 
3342   // Merge attributes from the parameters.
3343   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3344                                        oe = oldMethod->param_end();
3345   for (ObjCMethodDecl::param_iterator
3346          ni = newMethod->param_begin(), ne = newMethod->param_end();
3347        ni != ne && oi != oe; ++ni, ++oi)
3348     mergeParamDeclAttributes(*ni, *oi, *this);
3349 
3350   CheckObjCMethodOverride(newMethod, oldMethod);
3351 }
3352 
3353 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3354   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3355 
3356   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3357          ? diag::err_redefinition_different_type
3358          : diag::err_redeclaration_different_type)
3359     << New->getDeclName() << New->getType() << Old->getType();
3360 
3361   diag::kind PrevDiag;
3362   SourceLocation OldLocation;
3363   std::tie(PrevDiag, OldLocation)
3364     = getNoteDiagForInvalidRedeclaration(Old, New);
3365   S.Diag(OldLocation, PrevDiag);
3366   New->setInvalidDecl();
3367 }
3368 
3369 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3370 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3371 /// emitting diagnostics as appropriate.
3372 ///
3373 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3374 /// to here in AddInitializerToDecl. We can't check them before the initializer
3375 /// is attached.
3376 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3377                              bool MergeTypeWithOld) {
3378   if (New->isInvalidDecl() || Old->isInvalidDecl())
3379     return;
3380 
3381   QualType MergedT;
3382   if (getLangOpts().CPlusPlus) {
3383     if (New->getType()->isUndeducedType()) {
3384       // We don't know what the new type is until the initializer is attached.
3385       return;
3386     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3387       // These could still be something that needs exception specs checked.
3388       return MergeVarDeclExceptionSpecs(New, Old);
3389     }
3390     // C++ [basic.link]p10:
3391     //   [...] the types specified by all declarations referring to a given
3392     //   object or function shall be identical, except that declarations for an
3393     //   array object can specify array types that differ by the presence or
3394     //   absence of a major array bound (8.3.4).
3395     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3396       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3397       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3398 
3399       // We are merging a variable declaration New into Old. If it has an array
3400       // bound, and that bound differs from Old's bound, we should diagnose the
3401       // mismatch.
3402       if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
3403         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3404              PrevVD = PrevVD->getPreviousDecl()) {
3405           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3406           if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
3407             continue;
3408 
3409           if (!Context.hasSameType(NewArray, PrevVDTy))
3410             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3411         }
3412       }
3413 
3414       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3415         if (Context.hasSameType(OldArray->getElementType(),
3416                                 NewArray->getElementType()))
3417           MergedT = New->getType();
3418       }
3419       // FIXME: Check visibility. New is hidden but has a complete type. If New
3420       // has no array bound, it should not inherit one from Old, if Old is not
3421       // visible.
3422       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3423         if (Context.hasSameType(OldArray->getElementType(),
3424                                 NewArray->getElementType()))
3425           MergedT = Old->getType();
3426       }
3427     }
3428     else if (New->getType()->isObjCObjectPointerType() &&
3429                Old->getType()->isObjCObjectPointerType()) {
3430       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3431                                               Old->getType());
3432     }
3433   } else {
3434     // C 6.2.7p2:
3435     //   All declarations that refer to the same object or function shall have
3436     //   compatible type.
3437     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3438   }
3439   if (MergedT.isNull()) {
3440     // It's OK if we couldn't merge types if either type is dependent, for a
3441     // block-scope variable. In other cases (static data members of class
3442     // templates, variable templates, ...), we require the types to be
3443     // equivalent.
3444     // FIXME: The C++ standard doesn't say anything about this.
3445     if ((New->getType()->isDependentType() ||
3446          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3447       // If the old type was dependent, we can't merge with it, so the new type
3448       // becomes dependent for now. We'll reproduce the original type when we
3449       // instantiate the TypeSourceInfo for the variable.
3450       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3451         New->setType(Context.DependentTy);
3452       return;
3453     }
3454     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3455   }
3456 
3457   // Don't actually update the type on the new declaration if the old
3458   // declaration was an extern declaration in a different scope.
3459   if (MergeTypeWithOld)
3460     New->setType(MergedT);
3461 }
3462 
3463 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3464                                   LookupResult &Previous) {
3465   // C11 6.2.7p4:
3466   //   For an identifier with internal or external linkage declared
3467   //   in a scope in which a prior declaration of that identifier is
3468   //   visible, if the prior declaration specifies internal or
3469   //   external linkage, the type of the identifier at the later
3470   //   declaration becomes the composite type.
3471   //
3472   // If the variable isn't visible, we do not merge with its type.
3473   if (Previous.isShadowed())
3474     return false;
3475 
3476   if (S.getLangOpts().CPlusPlus) {
3477     // C++11 [dcl.array]p3:
3478     //   If there is a preceding declaration of the entity in the same
3479     //   scope in which the bound was specified, an omitted array bound
3480     //   is taken to be the same as in that earlier declaration.
3481     return NewVD->isPreviousDeclInSameBlockScope() ||
3482            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3483             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3484   } else {
3485     // If the old declaration was function-local, don't merge with its
3486     // type unless we're in the same function.
3487     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3488            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3489   }
3490 }
3491 
3492 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3493 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3494 /// situation, merging decls or emitting diagnostics as appropriate.
3495 ///
3496 /// Tentative definition rules (C99 6.9.2p2) are checked by
3497 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3498 /// definitions here, since the initializer hasn't been attached.
3499 ///
3500 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3501   // If the new decl is already invalid, don't do any other checking.
3502   if (New->isInvalidDecl())
3503     return;
3504 
3505   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3506     return;
3507 
3508   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3509 
3510   // Verify the old decl was also a variable or variable template.
3511   VarDecl *Old = nullptr;
3512   VarTemplateDecl *OldTemplate = nullptr;
3513   if (Previous.isSingleResult()) {
3514     if (NewTemplate) {
3515       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3516       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3517 
3518       if (auto *Shadow =
3519               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3520         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3521           return New->setInvalidDecl();
3522     } else {
3523       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3524 
3525       if (auto *Shadow =
3526               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3527         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3528           return New->setInvalidDecl();
3529     }
3530   }
3531   if (!Old) {
3532     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3533       << New->getDeclName();
3534     Diag(Previous.getRepresentativeDecl()->getLocation(),
3535          diag::note_previous_definition);
3536     return New->setInvalidDecl();
3537   }
3538 
3539   // Ensure the template parameters are compatible.
3540   if (NewTemplate &&
3541       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3542                                       OldTemplate->getTemplateParameters(),
3543                                       /*Complain=*/true, TPL_TemplateMatch))
3544     return New->setInvalidDecl();
3545 
3546   // C++ [class.mem]p1:
3547   //   A member shall not be declared twice in the member-specification [...]
3548   //
3549   // Here, we need only consider static data members.
3550   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3551     Diag(New->getLocation(), diag::err_duplicate_member)
3552       << New->getIdentifier();
3553     Diag(Old->getLocation(), diag::note_previous_declaration);
3554     New->setInvalidDecl();
3555   }
3556 
3557   mergeDeclAttributes(New, Old);
3558   // Warn if an already-declared variable is made a weak_import in a subsequent
3559   // declaration
3560   if (New->hasAttr<WeakImportAttr>() &&
3561       Old->getStorageClass() == SC_None &&
3562       !Old->hasAttr<WeakImportAttr>()) {
3563     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3564     Diag(Old->getLocation(), diag::note_previous_definition);
3565     // Remove weak_import attribute on new declaration.
3566     New->dropAttr<WeakImportAttr>();
3567   }
3568 
3569   if (New->hasAttr<InternalLinkageAttr>() &&
3570       !Old->hasAttr<InternalLinkageAttr>()) {
3571     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3572         << New->getDeclName();
3573     Diag(Old->getLocation(), diag::note_previous_definition);
3574     New->dropAttr<InternalLinkageAttr>();
3575   }
3576 
3577   // Merge the types.
3578   VarDecl *MostRecent = Old->getMostRecentDecl();
3579   if (MostRecent != Old) {
3580     MergeVarDeclTypes(New, MostRecent,
3581                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3582     if (New->isInvalidDecl())
3583       return;
3584   }
3585 
3586   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3587   if (New->isInvalidDecl())
3588     return;
3589 
3590   diag::kind PrevDiag;
3591   SourceLocation OldLocation;
3592   std::tie(PrevDiag, OldLocation) =
3593       getNoteDiagForInvalidRedeclaration(Old, New);
3594 
3595   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3596   if (New->getStorageClass() == SC_Static &&
3597       !New->isStaticDataMember() &&
3598       Old->hasExternalFormalLinkage()) {
3599     if (getLangOpts().MicrosoftExt) {
3600       Diag(New->getLocation(), diag::ext_static_non_static)
3601           << New->getDeclName();
3602       Diag(OldLocation, PrevDiag);
3603     } else {
3604       Diag(New->getLocation(), diag::err_static_non_static)
3605           << New->getDeclName();
3606       Diag(OldLocation, PrevDiag);
3607       return New->setInvalidDecl();
3608     }
3609   }
3610   // C99 6.2.2p4:
3611   //   For an identifier declared with the storage-class specifier
3612   //   extern in a scope in which a prior declaration of that
3613   //   identifier is visible,23) if the prior declaration specifies
3614   //   internal or external linkage, the linkage of the identifier at
3615   //   the later declaration is the same as the linkage specified at
3616   //   the prior declaration. If no prior declaration is visible, or
3617   //   if the prior declaration specifies no linkage, then the
3618   //   identifier has external linkage.
3619   if (New->hasExternalStorage() && Old->hasLinkage())
3620     /* Okay */;
3621   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3622            !New->isStaticDataMember() &&
3623            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3624     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3625     Diag(OldLocation, PrevDiag);
3626     return New->setInvalidDecl();
3627   }
3628 
3629   // Check if extern is followed by non-extern and vice-versa.
3630   if (New->hasExternalStorage() &&
3631       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3632     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3633     Diag(OldLocation, PrevDiag);
3634     return New->setInvalidDecl();
3635   }
3636   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3637       !New->hasExternalStorage()) {
3638     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3639     Diag(OldLocation, PrevDiag);
3640     return New->setInvalidDecl();
3641   }
3642 
3643   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3644 
3645   // FIXME: The test for external storage here seems wrong? We still
3646   // need to check for mismatches.
3647   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3648       // Don't complain about out-of-line definitions of static members.
3649       !(Old->getLexicalDeclContext()->isRecord() &&
3650         !New->getLexicalDeclContext()->isRecord())) {
3651     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3652     Diag(OldLocation, PrevDiag);
3653     return New->setInvalidDecl();
3654   }
3655 
3656   if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
3657     if (VarDecl *Def = Old->getDefinition()) {
3658       // C++1z [dcl.fcn.spec]p4:
3659       //   If the definition of a variable appears in a translation unit before
3660       //   its first declaration as inline, the program is ill-formed.
3661       Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
3662       Diag(Def->getLocation(), diag::note_previous_definition);
3663     }
3664   }
3665 
3666   // If this redeclaration makes the function inline, we may need to add it to
3667   // UndefinedButUsed.
3668   if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
3669       !Old->getDefinition() && !New->isThisDeclarationADefinition())
3670     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3671                                            SourceLocation()));
3672 
3673   if (New->getTLSKind() != Old->getTLSKind()) {
3674     if (!Old->getTLSKind()) {
3675       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3676       Diag(OldLocation, PrevDiag);
3677     } else if (!New->getTLSKind()) {
3678       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3679       Diag(OldLocation, PrevDiag);
3680     } else {
3681       // Do not allow redeclaration to change the variable between requiring
3682       // static and dynamic initialization.
3683       // FIXME: GCC allows this, but uses the TLS keyword on the first
3684       // declaration to determine the kind. Do we need to be compatible here?
3685       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3686         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3687       Diag(OldLocation, PrevDiag);
3688     }
3689   }
3690 
3691   // C++ doesn't have tentative definitions, so go right ahead and check here.
3692   if (getLangOpts().CPlusPlus &&
3693       New->isThisDeclarationADefinition() == VarDecl::Definition) {
3694     if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
3695         Old->getCanonicalDecl()->isConstexpr()) {
3696       // This definition won't be a definition any more once it's been merged.
3697       Diag(New->getLocation(),
3698            diag::warn_deprecated_redundant_constexpr_static_def);
3699     } else if (VarDecl *Def = Old->getDefinition()) {
3700       if (checkVarDeclRedefinition(Def, New))
3701         return;
3702     }
3703   }
3704 
3705   if (haveIncompatibleLanguageLinkages(Old, New)) {
3706     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3707     Diag(OldLocation, PrevDiag);
3708     New->setInvalidDecl();
3709     return;
3710   }
3711 
3712   // Merge "used" flag.
3713   if (Old->getMostRecentDecl()->isUsed(false))
3714     New->setIsUsed();
3715 
3716   // Keep a chain of previous declarations.
3717   New->setPreviousDecl(Old);
3718   if (NewTemplate)
3719     NewTemplate->setPreviousDecl(OldTemplate);
3720 
3721   // Inherit access appropriately.
3722   New->setAccess(Old->getAccess());
3723   if (NewTemplate)
3724     NewTemplate->setAccess(New->getAccess());
3725 
3726   if (Old->isInline())
3727     New->setImplicitlyInline();
3728 }
3729 
3730 /// We've just determined that \p Old and \p New both appear to be definitions
3731 /// of the same variable. Either diagnose or fix the problem.
3732 bool Sema::checkVarDeclRedefinition(VarDecl *Old, VarDecl *New) {
3733   if (!hasVisibleDefinition(Old) &&
3734       (New->getFormalLinkage() == InternalLinkage ||
3735        New->isInline() ||
3736        New->getDescribedVarTemplate() ||
3737        New->getNumTemplateParameterLists() ||
3738        New->getDeclContext()->isDependentContext())) {
3739     // The previous definition is hidden, and multiple definitions are
3740     // permitted (in separate TUs). Demote this to a declaration.
3741     New->demoteThisDefinitionToDeclaration();
3742 
3743     // Make the canonical definition visible.
3744     if (auto *OldTD = Old->getDescribedVarTemplate())
3745       makeMergedDefinitionVisible(OldTD, New->getLocation());
3746     makeMergedDefinitionVisible(Old, New->getLocation());
3747     return false;
3748   } else {
3749     Diag(New->getLocation(), diag::err_redefinition) << New;
3750     Diag(Old->getLocation(), diag::note_previous_definition);
3751     New->setInvalidDecl();
3752     return true;
3753   }
3754 }
3755 
3756 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3757 /// no declarator (e.g. "struct foo;") is parsed.
3758 Decl *
3759 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3760                                  RecordDecl *&AnonRecord) {
3761   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3762                                     AnonRecord);
3763 }
3764 
3765 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3766 // disambiguate entities defined in different scopes.
3767 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3768 // compatibility.
3769 // We will pick our mangling number depending on which version of MSVC is being
3770 // targeted.
3771 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3772   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3773              ? S->getMSCurManglingNumber()
3774              : S->getMSLastManglingNumber();
3775 }
3776 
3777 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3778   if (!Context.getLangOpts().CPlusPlus)
3779     return;
3780 
3781   if (isa<CXXRecordDecl>(Tag->getParent())) {
3782     // If this tag is the direct child of a class, number it if
3783     // it is anonymous.
3784     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3785       return;
3786     MangleNumberingContext &MCtx =
3787         Context.getManglingNumberContext(Tag->getParent());
3788     Context.setManglingNumber(
3789         Tag, MCtx.getManglingNumber(
3790                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3791     return;
3792   }
3793 
3794   // If this tag isn't a direct child of a class, number it if it is local.
3795   Decl *ManglingContextDecl;
3796   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3797           Tag->getDeclContext(), ManglingContextDecl)) {
3798     Context.setManglingNumber(
3799         Tag, MCtx->getManglingNumber(
3800                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3801   }
3802 }
3803 
3804 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3805                                         TypedefNameDecl *NewTD) {
3806   if (TagFromDeclSpec->isInvalidDecl())
3807     return;
3808 
3809   // Do nothing if the tag already has a name for linkage purposes.
3810   if (TagFromDeclSpec->hasNameForLinkage())
3811     return;
3812 
3813   // A well-formed anonymous tag must always be a TUK_Definition.
3814   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3815 
3816   // The type must match the tag exactly;  no qualifiers allowed.
3817   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3818                            Context.getTagDeclType(TagFromDeclSpec))) {
3819     if (getLangOpts().CPlusPlus)
3820       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3821     return;
3822   }
3823 
3824   // If we've already computed linkage for the anonymous tag, then
3825   // adding a typedef name for the anonymous decl can change that
3826   // linkage, which might be a serious problem.  Diagnose this as
3827   // unsupported and ignore the typedef name.  TODO: we should
3828   // pursue this as a language defect and establish a formal rule
3829   // for how to handle it.
3830   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3831     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3832 
3833     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3834     tagLoc = getLocForEndOfToken(tagLoc);
3835 
3836     llvm::SmallString<40> textToInsert;
3837     textToInsert += ' ';
3838     textToInsert += NewTD->getIdentifier()->getName();
3839     Diag(tagLoc, diag::note_typedef_changes_linkage)
3840         << FixItHint::CreateInsertion(tagLoc, textToInsert);
3841     return;
3842   }
3843 
3844   // Otherwise, set this is the anon-decl typedef for the tag.
3845   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3846 }
3847 
3848 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3849   switch (T) {
3850   case DeclSpec::TST_class:
3851     return 0;
3852   case DeclSpec::TST_struct:
3853     return 1;
3854   case DeclSpec::TST_interface:
3855     return 2;
3856   case DeclSpec::TST_union:
3857     return 3;
3858   case DeclSpec::TST_enum:
3859     return 4;
3860   default:
3861     llvm_unreachable("unexpected type specifier");
3862   }
3863 }
3864 
3865 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3866 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3867 /// parameters to cope with template friend declarations.
3868 Decl *
3869 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3870                                  MultiTemplateParamsArg TemplateParams,
3871                                  bool IsExplicitInstantiation,
3872                                  RecordDecl *&AnonRecord) {
3873   Decl *TagD = nullptr;
3874   TagDecl *Tag = nullptr;
3875   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3876       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3877       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3878       DS.getTypeSpecType() == DeclSpec::TST_union ||
3879       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3880     TagD = DS.getRepAsDecl();
3881 
3882     if (!TagD) // We probably had an error
3883       return nullptr;
3884 
3885     // Note that the above type specs guarantee that the
3886     // type rep is a Decl, whereas in many of the others
3887     // it's a Type.
3888     if (isa<TagDecl>(TagD))
3889       Tag = cast<TagDecl>(TagD);
3890     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3891       Tag = CTD->getTemplatedDecl();
3892   }
3893 
3894   if (Tag) {
3895     handleTagNumbering(Tag, S);
3896     Tag->setFreeStanding();
3897     if (Tag->isInvalidDecl())
3898       return Tag;
3899   }
3900 
3901   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3902     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3903     // or incomplete types shall not be restrict-qualified."
3904     if (TypeQuals & DeclSpec::TQ_restrict)
3905       Diag(DS.getRestrictSpecLoc(),
3906            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3907            << DS.getSourceRange();
3908   }
3909 
3910   if (DS.isInlineSpecified())
3911     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
3912         << getLangOpts().CPlusPlus1z;
3913 
3914   if (DS.isConstexprSpecified()) {
3915     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3916     // and definitions of functions and variables.
3917     if (Tag)
3918       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3919           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3920     else
3921       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3922     // Don't emit warnings after this error.
3923     return TagD;
3924   }
3925 
3926   if (DS.isConceptSpecified()) {
3927     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3928     // either a function concept and its definition or a variable concept and
3929     // its initializer.
3930     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3931     return TagD;
3932   }
3933 
3934   DiagnoseFunctionSpecifiers(DS);
3935 
3936   if (DS.isFriendSpecified()) {
3937     // If we're dealing with a decl but not a TagDecl, assume that
3938     // whatever routines created it handled the friendship aspect.
3939     if (TagD && !Tag)
3940       return nullptr;
3941     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3942   }
3943 
3944   const CXXScopeSpec &SS = DS.getTypeSpecScope();
3945   bool IsExplicitSpecialization =
3946     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3947   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3948       !IsExplicitInstantiation && !IsExplicitSpecialization &&
3949       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
3950     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3951     // nested-name-specifier unless it is an explicit instantiation
3952     // or an explicit specialization.
3953     //
3954     // FIXME: We allow class template partial specializations here too, per the
3955     // obvious intent of DR1819.
3956     //
3957     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3958     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3959         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
3960     return nullptr;
3961   }
3962 
3963   // Track whether this decl-specifier declares anything.
3964   bool DeclaresAnything = true;
3965 
3966   // Handle anonymous struct definitions.
3967   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3968     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3969         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3970       if (getLangOpts().CPlusPlus ||
3971           Record->getDeclContext()->isRecord()) {
3972         // If CurContext is a DeclContext that can contain statements,
3973         // RecursiveASTVisitor won't visit the decls that
3974         // BuildAnonymousStructOrUnion() will put into CurContext.
3975         // Also store them here so that they can be part of the
3976         // DeclStmt that gets created in this case.
3977         // FIXME: Also return the IndirectFieldDecls created by
3978         // BuildAnonymousStructOr union, for the same reason?
3979         if (CurContext->isFunctionOrMethod())
3980           AnonRecord = Record;
3981         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3982                                            Context.getPrintingPolicy());
3983       }
3984 
3985       DeclaresAnything = false;
3986     }
3987   }
3988 
3989   // C11 6.7.2.1p2:
3990   //   A struct-declaration that does not declare an anonymous structure or
3991   //   anonymous union shall contain a struct-declarator-list.
3992   //
3993   // This rule also existed in C89 and C99; the grammar for struct-declaration
3994   // did not permit a struct-declaration without a struct-declarator-list.
3995   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3996       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3997     // Check for Microsoft C extension: anonymous struct/union member.
3998     // Handle 2 kinds of anonymous struct/union:
3999     //   struct STRUCT;
4000     //   union UNION;
4001     // and
4002     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
4003     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
4004     if ((Tag && Tag->getDeclName()) ||
4005         DS.getTypeSpecType() == DeclSpec::TST_typename) {
4006       RecordDecl *Record = nullptr;
4007       if (Tag)
4008         Record = dyn_cast<RecordDecl>(Tag);
4009       else if (const RecordType *RT =
4010                    DS.getRepAsType().get()->getAsStructureType())
4011         Record = RT->getDecl();
4012       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4013         Record = UT->getDecl();
4014 
4015       if (Record && getLangOpts().MicrosoftExt) {
4016         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
4017           << Record->isUnion() << DS.getSourceRange();
4018         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4019       }
4020 
4021       DeclaresAnything = false;
4022     }
4023   }
4024 
4025   // Skip all the checks below if we have a type error.
4026   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4027       (TagD && TagD->isInvalidDecl()))
4028     return TagD;
4029 
4030   if (getLangOpts().CPlusPlus &&
4031       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
4032     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4033       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4034           !Enum->getIdentifier() && !Enum->isInvalidDecl())
4035         DeclaresAnything = false;
4036 
4037   if (!DS.isMissingDeclaratorOk()) {
4038     // Customize diagnostic for a typedef missing a name.
4039     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
4040       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
4041         << DS.getSourceRange();
4042     else
4043       DeclaresAnything = false;
4044   }
4045 
4046   if (DS.isModulePrivateSpecified() &&
4047       Tag && Tag->getDeclContext()->isFunctionOrMethod())
4048     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4049       << Tag->getTagKind()
4050       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
4051 
4052   ActOnDocumentableDecl(TagD);
4053 
4054   // C 6.7/2:
4055   //   A declaration [...] shall declare at least a declarator [...], a tag,
4056   //   or the members of an enumeration.
4057   // C++ [dcl.dcl]p3:
4058   //   [If there are no declarators], and except for the declaration of an
4059   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
4060   //   names into the program, or shall redeclare a name introduced by a
4061   //   previous declaration.
4062   if (!DeclaresAnything) {
4063     // In C, we allow this as a (popular) extension / bug. Don't bother
4064     // producing further diagnostics for redundant qualifiers after this.
4065     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
4066     return TagD;
4067   }
4068 
4069   // C++ [dcl.stc]p1:
4070   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4071   //   init-declarator-list of the declaration shall not be empty.
4072   // C++ [dcl.fct.spec]p1:
4073   //   If a cv-qualifier appears in a decl-specifier-seq, the
4074   //   init-declarator-list of the declaration shall not be empty.
4075   //
4076   // Spurious qualifiers here appear to be valid in C.
4077   unsigned DiagID = diag::warn_standalone_specifier;
4078   if (getLangOpts().CPlusPlus)
4079     DiagID = diag::ext_standalone_specifier;
4080 
4081   // Note that a linkage-specification sets a storage class, but
4082   // 'extern "C" struct foo;' is actually valid and not theoretically
4083   // useless.
4084   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4085     if (SCS == DeclSpec::SCS_mutable)
4086       // Since mutable is not a viable storage class specifier in C, there is
4087       // no reason to treat it as an extension. Instead, diagnose as an error.
4088       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4089     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4090       Diag(DS.getStorageClassSpecLoc(), DiagID)
4091         << DeclSpec::getSpecifierName(SCS);
4092   }
4093 
4094   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4095     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4096       << DeclSpec::getSpecifierName(TSCS);
4097   if (DS.getTypeQualifiers()) {
4098     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4099       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4100     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4101       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4102     // Restrict is covered above.
4103     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4104       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4105     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4106       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4107   }
4108 
4109   // Warn about ignored type attributes, for example:
4110   // __attribute__((aligned)) struct A;
4111   // Attributes should be placed after tag to apply to type declaration.
4112   if (!DS.getAttributes().empty()) {
4113     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4114     if (TypeSpecType == DeclSpec::TST_class ||
4115         TypeSpecType == DeclSpec::TST_struct ||
4116         TypeSpecType == DeclSpec::TST_interface ||
4117         TypeSpecType == DeclSpec::TST_union ||
4118         TypeSpecType == DeclSpec::TST_enum) {
4119       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4120            attrs = attrs->getNext())
4121         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4122             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4123     }
4124   }
4125 
4126   return TagD;
4127 }
4128 
4129 /// We are trying to inject an anonymous member into the given scope;
4130 /// check if there's an existing declaration that can't be overloaded.
4131 ///
4132 /// \return true if this is a forbidden redeclaration
4133 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4134                                          Scope *S,
4135                                          DeclContext *Owner,
4136                                          DeclarationName Name,
4137                                          SourceLocation NameLoc,
4138                                          bool IsUnion) {
4139   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4140                  Sema::ForRedeclaration);
4141   if (!SemaRef.LookupName(R, S)) return false;
4142 
4143   // Pick a representative declaration.
4144   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4145   assert(PrevDecl && "Expected a non-null Decl");
4146 
4147   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4148     return false;
4149 
4150   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4151     << IsUnion << Name;
4152   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4153 
4154   return true;
4155 }
4156 
4157 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4158 /// anonymous struct or union AnonRecord into the owning context Owner
4159 /// and scope S. This routine will be invoked just after we realize
4160 /// that an unnamed union or struct is actually an anonymous union or
4161 /// struct, e.g.,
4162 ///
4163 /// @code
4164 /// union {
4165 ///   int i;
4166 ///   float f;
4167 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4168 ///    // f into the surrounding scope.x
4169 /// @endcode
4170 ///
4171 /// This routine is recursive, injecting the names of nested anonymous
4172 /// structs/unions into the owning context and scope as well.
4173 static bool
4174 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4175                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4176                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4177   bool Invalid = false;
4178 
4179   // Look every FieldDecl and IndirectFieldDecl with a name.
4180   for (auto *D : AnonRecord->decls()) {
4181     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4182         cast<NamedDecl>(D)->getDeclName()) {
4183       ValueDecl *VD = cast<ValueDecl>(D);
4184       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4185                                        VD->getLocation(),
4186                                        AnonRecord->isUnion())) {
4187         // C++ [class.union]p2:
4188         //   The names of the members of an anonymous union shall be
4189         //   distinct from the names of any other entity in the
4190         //   scope in which the anonymous union is declared.
4191         Invalid = true;
4192       } else {
4193         // C++ [class.union]p2:
4194         //   For the purpose of name lookup, after the anonymous union
4195         //   definition, the members of the anonymous union are
4196         //   considered to have been defined in the scope in which the
4197         //   anonymous union is declared.
4198         unsigned OldChainingSize = Chaining.size();
4199         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4200           Chaining.append(IF->chain_begin(), IF->chain_end());
4201         else
4202           Chaining.push_back(VD);
4203 
4204         assert(Chaining.size() >= 2);
4205         NamedDecl **NamedChain =
4206           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4207         for (unsigned i = 0; i < Chaining.size(); i++)
4208           NamedChain[i] = Chaining[i];
4209 
4210         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4211             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4212             VD->getType(), {NamedChain, Chaining.size()});
4213 
4214         for (const auto *Attr : VD->attrs())
4215           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4216 
4217         IndirectField->setAccess(AS);
4218         IndirectField->setImplicit();
4219         SemaRef.PushOnScopeChains(IndirectField, S);
4220 
4221         // That includes picking up the appropriate access specifier.
4222         if (AS != AS_none) IndirectField->setAccess(AS);
4223 
4224         Chaining.resize(OldChainingSize);
4225       }
4226     }
4227   }
4228 
4229   return Invalid;
4230 }
4231 
4232 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4233 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4234 /// illegal input values are mapped to SC_None.
4235 static StorageClass
4236 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4237   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4238   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4239          "Parser allowed 'typedef' as storage class VarDecl.");
4240   switch (StorageClassSpec) {
4241   case DeclSpec::SCS_unspecified:    return SC_None;
4242   case DeclSpec::SCS_extern:
4243     if (DS.isExternInLinkageSpec())
4244       return SC_None;
4245     return SC_Extern;
4246   case DeclSpec::SCS_static:         return SC_Static;
4247   case DeclSpec::SCS_auto:           return SC_Auto;
4248   case DeclSpec::SCS_register:       return SC_Register;
4249   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4250     // Illegal SCSs map to None: error reporting is up to the caller.
4251   case DeclSpec::SCS_mutable:        // Fall through.
4252   case DeclSpec::SCS_typedef:        return SC_None;
4253   }
4254   llvm_unreachable("unknown storage class specifier");
4255 }
4256 
4257 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4258   assert(Record->hasInClassInitializer());
4259 
4260   for (const auto *I : Record->decls()) {
4261     const auto *FD = dyn_cast<FieldDecl>(I);
4262     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4263       FD = IFD->getAnonField();
4264     if (FD && FD->hasInClassInitializer())
4265       return FD->getLocation();
4266   }
4267 
4268   llvm_unreachable("couldn't find in-class initializer");
4269 }
4270 
4271 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4272                                       SourceLocation DefaultInitLoc) {
4273   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4274     return;
4275 
4276   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4277   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4278 }
4279 
4280 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4281                                       CXXRecordDecl *AnonUnion) {
4282   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4283     return;
4284 
4285   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4286 }
4287 
4288 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4289 /// anonymous structure or union. Anonymous unions are a C++ feature
4290 /// (C++ [class.union]) and a C11 feature; anonymous structures
4291 /// are a C11 feature and GNU C++ extension.
4292 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4293                                         AccessSpecifier AS,
4294                                         RecordDecl *Record,
4295                                         const PrintingPolicy &Policy) {
4296   DeclContext *Owner = Record->getDeclContext();
4297 
4298   // Diagnose whether this anonymous struct/union is an extension.
4299   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4300     Diag(Record->getLocation(), diag::ext_anonymous_union);
4301   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4302     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4303   else if (!Record->isUnion() && !getLangOpts().C11)
4304     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4305 
4306   // C and C++ require different kinds of checks for anonymous
4307   // structs/unions.
4308   bool Invalid = false;
4309   if (getLangOpts().CPlusPlus) {
4310     const char *PrevSpec = nullptr;
4311     unsigned DiagID;
4312     if (Record->isUnion()) {
4313       // C++ [class.union]p6:
4314       //   Anonymous unions declared in a named namespace or in the
4315       //   global namespace shall be declared static.
4316       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4317           (isa<TranslationUnitDecl>(Owner) ||
4318            (isa<NamespaceDecl>(Owner) &&
4319             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4320         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4321           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4322 
4323         // Recover by adding 'static'.
4324         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4325                                PrevSpec, DiagID, Policy);
4326       }
4327       // C++ [class.union]p6:
4328       //   A storage class is not allowed in a declaration of an
4329       //   anonymous union in a class scope.
4330       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4331                isa<RecordDecl>(Owner)) {
4332         Diag(DS.getStorageClassSpecLoc(),
4333              diag::err_anonymous_union_with_storage_spec)
4334           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4335 
4336         // Recover by removing the storage specifier.
4337         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4338                                SourceLocation(),
4339                                PrevSpec, DiagID, Context.getPrintingPolicy());
4340       }
4341     }
4342 
4343     // Ignore const/volatile/restrict qualifiers.
4344     if (DS.getTypeQualifiers()) {
4345       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4346         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4347           << Record->isUnion() << "const"
4348           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4349       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4350         Diag(DS.getVolatileSpecLoc(),
4351              diag::ext_anonymous_struct_union_qualified)
4352           << Record->isUnion() << "volatile"
4353           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4354       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4355         Diag(DS.getRestrictSpecLoc(),
4356              diag::ext_anonymous_struct_union_qualified)
4357           << Record->isUnion() << "restrict"
4358           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4359       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4360         Diag(DS.getAtomicSpecLoc(),
4361              diag::ext_anonymous_struct_union_qualified)
4362           << Record->isUnion() << "_Atomic"
4363           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4364       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4365         Diag(DS.getUnalignedSpecLoc(),
4366              diag::ext_anonymous_struct_union_qualified)
4367           << Record->isUnion() << "__unaligned"
4368           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4369 
4370       DS.ClearTypeQualifiers();
4371     }
4372 
4373     // C++ [class.union]p2:
4374     //   The member-specification of an anonymous union shall only
4375     //   define non-static data members. [Note: nested types and
4376     //   functions cannot be declared within an anonymous union. ]
4377     for (auto *Mem : Record->decls()) {
4378       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4379         // C++ [class.union]p3:
4380         //   An anonymous union shall not have private or protected
4381         //   members (clause 11).
4382         assert(FD->getAccess() != AS_none);
4383         if (FD->getAccess() != AS_public) {
4384           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4385             << Record->isUnion() << (FD->getAccess() == AS_protected);
4386           Invalid = true;
4387         }
4388 
4389         // C++ [class.union]p1
4390         //   An object of a class with a non-trivial constructor, a non-trivial
4391         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4392         //   assignment operator cannot be a member of a union, nor can an
4393         //   array of such objects.
4394         if (CheckNontrivialField(FD))
4395           Invalid = true;
4396       } else if (Mem->isImplicit()) {
4397         // Any implicit members are fine.
4398       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4399         // This is a type that showed up in an
4400         // elaborated-type-specifier inside the anonymous struct or
4401         // union, but which actually declares a type outside of the
4402         // anonymous struct or union. It's okay.
4403       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4404         if (!MemRecord->isAnonymousStructOrUnion() &&
4405             MemRecord->getDeclName()) {
4406           // Visual C++ allows type definition in anonymous struct or union.
4407           if (getLangOpts().MicrosoftExt)
4408             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4409               << Record->isUnion();
4410           else {
4411             // This is a nested type declaration.
4412             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4413               << Record->isUnion();
4414             Invalid = true;
4415           }
4416         } else {
4417           // This is an anonymous type definition within another anonymous type.
4418           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4419           // not part of standard C++.
4420           Diag(MemRecord->getLocation(),
4421                diag::ext_anonymous_record_with_anonymous_type)
4422             << Record->isUnion();
4423         }
4424       } else if (isa<AccessSpecDecl>(Mem)) {
4425         // Any access specifier is fine.
4426       } else if (isa<StaticAssertDecl>(Mem)) {
4427         // In C++1z, static_assert declarations are also fine.
4428       } else {
4429         // We have something that isn't a non-static data
4430         // member. Complain about it.
4431         unsigned DK = diag::err_anonymous_record_bad_member;
4432         if (isa<TypeDecl>(Mem))
4433           DK = diag::err_anonymous_record_with_type;
4434         else if (isa<FunctionDecl>(Mem))
4435           DK = diag::err_anonymous_record_with_function;
4436         else if (isa<VarDecl>(Mem))
4437           DK = diag::err_anonymous_record_with_static;
4438 
4439         // Visual C++ allows type definition in anonymous struct or union.
4440         if (getLangOpts().MicrosoftExt &&
4441             DK == diag::err_anonymous_record_with_type)
4442           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4443             << Record->isUnion();
4444         else {
4445           Diag(Mem->getLocation(), DK) << Record->isUnion();
4446           Invalid = true;
4447         }
4448       }
4449     }
4450 
4451     // C++11 [class.union]p8 (DR1460):
4452     //   At most one variant member of a union may have a
4453     //   brace-or-equal-initializer.
4454     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4455         Owner->isRecord())
4456       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4457                                 cast<CXXRecordDecl>(Record));
4458   }
4459 
4460   if (!Record->isUnion() && !Owner->isRecord()) {
4461     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4462       << getLangOpts().CPlusPlus;
4463     Invalid = true;
4464   }
4465 
4466   // Mock up a declarator.
4467   Declarator Dc(DS, Declarator::MemberContext);
4468   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4469   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4470 
4471   // Create a declaration for this anonymous struct/union.
4472   NamedDecl *Anon = nullptr;
4473   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4474     Anon = FieldDecl::Create(Context, OwningClass,
4475                              DS.getLocStart(),
4476                              Record->getLocation(),
4477                              /*IdentifierInfo=*/nullptr,
4478                              Context.getTypeDeclType(Record),
4479                              TInfo,
4480                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4481                              /*InitStyle=*/ICIS_NoInit);
4482     Anon->setAccess(AS);
4483     if (getLangOpts().CPlusPlus)
4484       FieldCollector->Add(cast<FieldDecl>(Anon));
4485   } else {
4486     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4487     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4488     if (SCSpec == DeclSpec::SCS_mutable) {
4489       // mutable can only appear on non-static class members, so it's always
4490       // an error here
4491       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4492       Invalid = true;
4493       SC = SC_None;
4494     }
4495 
4496     Anon = VarDecl::Create(Context, Owner,
4497                            DS.getLocStart(),
4498                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4499                            Context.getTypeDeclType(Record),
4500                            TInfo, SC);
4501 
4502     // Default-initialize the implicit variable. This initialization will be
4503     // trivial in almost all cases, except if a union member has an in-class
4504     // initializer:
4505     //   union { int n = 0; };
4506     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4507   }
4508   Anon->setImplicit();
4509 
4510   // Mark this as an anonymous struct/union type.
4511   Record->setAnonymousStructOrUnion(true);
4512 
4513   // Add the anonymous struct/union object to the current
4514   // context. We'll be referencing this object when we refer to one of
4515   // its members.
4516   Owner->addDecl(Anon);
4517 
4518   // Inject the members of the anonymous struct/union into the owning
4519   // context and into the identifier resolver chain for name lookup
4520   // purposes.
4521   SmallVector<NamedDecl*, 2> Chain;
4522   Chain.push_back(Anon);
4523 
4524   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4525     Invalid = true;
4526 
4527   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4528     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4529       Decl *ManglingContextDecl;
4530       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4531               NewVD->getDeclContext(), ManglingContextDecl)) {
4532         Context.setManglingNumber(
4533             NewVD, MCtx->getManglingNumber(
4534                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4535         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4536       }
4537     }
4538   }
4539 
4540   if (Invalid)
4541     Anon->setInvalidDecl();
4542 
4543   return Anon;
4544 }
4545 
4546 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4547 /// Microsoft C anonymous structure.
4548 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4549 /// Example:
4550 ///
4551 /// struct A { int a; };
4552 /// struct B { struct A; int b; };
4553 ///
4554 /// void foo() {
4555 ///   B var;
4556 ///   var.a = 3;
4557 /// }
4558 ///
4559 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4560                                            RecordDecl *Record) {
4561   assert(Record && "expected a record!");
4562 
4563   // Mock up a declarator.
4564   Declarator Dc(DS, Declarator::TypeNameContext);
4565   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4566   assert(TInfo && "couldn't build declarator info for anonymous struct");
4567 
4568   auto *ParentDecl = cast<RecordDecl>(CurContext);
4569   QualType RecTy = Context.getTypeDeclType(Record);
4570 
4571   // Create a declaration for this anonymous struct.
4572   NamedDecl *Anon = FieldDecl::Create(Context,
4573                              ParentDecl,
4574                              DS.getLocStart(),
4575                              DS.getLocStart(),
4576                              /*IdentifierInfo=*/nullptr,
4577                              RecTy,
4578                              TInfo,
4579                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4580                              /*InitStyle=*/ICIS_NoInit);
4581   Anon->setImplicit();
4582 
4583   // Add the anonymous struct object to the current context.
4584   CurContext->addDecl(Anon);
4585 
4586   // Inject the members of the anonymous struct into the current
4587   // context and into the identifier resolver chain for name lookup
4588   // purposes.
4589   SmallVector<NamedDecl*, 2> Chain;
4590   Chain.push_back(Anon);
4591 
4592   RecordDecl *RecordDef = Record->getDefinition();
4593   if (RequireCompleteType(Anon->getLocation(), RecTy,
4594                           diag::err_field_incomplete) ||
4595       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4596                                           AS_none, Chain)) {
4597     Anon->setInvalidDecl();
4598     ParentDecl->setInvalidDecl();
4599   }
4600 
4601   return Anon;
4602 }
4603 
4604 /// GetNameForDeclarator - Determine the full declaration name for the
4605 /// given Declarator.
4606 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4607   return GetNameFromUnqualifiedId(D.getName());
4608 }
4609 
4610 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4611 DeclarationNameInfo
4612 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4613   DeclarationNameInfo NameInfo;
4614   NameInfo.setLoc(Name.StartLocation);
4615 
4616   switch (Name.getKind()) {
4617 
4618   case UnqualifiedId::IK_ImplicitSelfParam:
4619   case UnqualifiedId::IK_Identifier:
4620     NameInfo.setName(Name.Identifier);
4621     NameInfo.setLoc(Name.StartLocation);
4622     return NameInfo;
4623 
4624   case UnqualifiedId::IK_OperatorFunctionId:
4625     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4626                                            Name.OperatorFunctionId.Operator));
4627     NameInfo.setLoc(Name.StartLocation);
4628     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4629       = Name.OperatorFunctionId.SymbolLocations[0];
4630     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4631       = Name.EndLocation.getRawEncoding();
4632     return NameInfo;
4633 
4634   case UnqualifiedId::IK_LiteralOperatorId:
4635     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4636                                                            Name.Identifier));
4637     NameInfo.setLoc(Name.StartLocation);
4638     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4639     return NameInfo;
4640 
4641   case UnqualifiedId::IK_ConversionFunctionId: {
4642     TypeSourceInfo *TInfo;
4643     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4644     if (Ty.isNull())
4645       return DeclarationNameInfo();
4646     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4647                                                Context.getCanonicalType(Ty)));
4648     NameInfo.setLoc(Name.StartLocation);
4649     NameInfo.setNamedTypeInfo(TInfo);
4650     return NameInfo;
4651   }
4652 
4653   case UnqualifiedId::IK_ConstructorName: {
4654     TypeSourceInfo *TInfo;
4655     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4656     if (Ty.isNull())
4657       return DeclarationNameInfo();
4658     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4659                                               Context.getCanonicalType(Ty)));
4660     NameInfo.setLoc(Name.StartLocation);
4661     NameInfo.setNamedTypeInfo(TInfo);
4662     return NameInfo;
4663   }
4664 
4665   case UnqualifiedId::IK_ConstructorTemplateId: {
4666     // In well-formed code, we can only have a constructor
4667     // template-id that refers to the current context, so go there
4668     // to find the actual type being constructed.
4669     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4670     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4671       return DeclarationNameInfo();
4672 
4673     // Determine the type of the class being constructed.
4674     QualType CurClassType = Context.getTypeDeclType(CurClass);
4675 
4676     // FIXME: Check two things: that the template-id names the same type as
4677     // CurClassType, and that the template-id does not occur when the name
4678     // was qualified.
4679 
4680     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4681                                     Context.getCanonicalType(CurClassType)));
4682     NameInfo.setLoc(Name.StartLocation);
4683     // FIXME: should we retrieve TypeSourceInfo?
4684     NameInfo.setNamedTypeInfo(nullptr);
4685     return NameInfo;
4686   }
4687 
4688   case UnqualifiedId::IK_DestructorName: {
4689     TypeSourceInfo *TInfo;
4690     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4691     if (Ty.isNull())
4692       return DeclarationNameInfo();
4693     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4694                                               Context.getCanonicalType(Ty)));
4695     NameInfo.setLoc(Name.StartLocation);
4696     NameInfo.setNamedTypeInfo(TInfo);
4697     return NameInfo;
4698   }
4699 
4700   case UnqualifiedId::IK_TemplateId: {
4701     TemplateName TName = Name.TemplateId->Template.get();
4702     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4703     return Context.getNameForTemplate(TName, TNameLoc);
4704   }
4705 
4706   } // switch (Name.getKind())
4707 
4708   llvm_unreachable("Unknown name kind");
4709 }
4710 
4711 static QualType getCoreType(QualType Ty) {
4712   do {
4713     if (Ty->isPointerType() || Ty->isReferenceType())
4714       Ty = Ty->getPointeeType();
4715     else if (Ty->isArrayType())
4716       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4717     else
4718       return Ty.withoutLocalFastQualifiers();
4719   } while (true);
4720 }
4721 
4722 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4723 /// and Definition have "nearly" matching parameters. This heuristic is
4724 /// used to improve diagnostics in the case where an out-of-line function
4725 /// definition doesn't match any declaration within the class or namespace.
4726 /// Also sets Params to the list of indices to the parameters that differ
4727 /// between the declaration and the definition. If hasSimilarParameters
4728 /// returns true and Params is empty, then all of the parameters match.
4729 static bool hasSimilarParameters(ASTContext &Context,
4730                                      FunctionDecl *Declaration,
4731                                      FunctionDecl *Definition,
4732                                      SmallVectorImpl<unsigned> &Params) {
4733   Params.clear();
4734   if (Declaration->param_size() != Definition->param_size())
4735     return false;
4736   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4737     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4738     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4739 
4740     // The parameter types are identical
4741     if (Context.hasSameType(DefParamTy, DeclParamTy))
4742       continue;
4743 
4744     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4745     QualType DefParamBaseTy = getCoreType(DefParamTy);
4746     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4747     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4748 
4749     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4750         (DeclTyName && DeclTyName == DefTyName))
4751       Params.push_back(Idx);
4752     else  // The two parameters aren't even close
4753       return false;
4754   }
4755 
4756   return true;
4757 }
4758 
4759 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4760 /// declarator needs to be rebuilt in the current instantiation.
4761 /// Any bits of declarator which appear before the name are valid for
4762 /// consideration here.  That's specifically the type in the decl spec
4763 /// and the base type in any member-pointer chunks.
4764 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4765                                                     DeclarationName Name) {
4766   // The types we specifically need to rebuild are:
4767   //   - typenames, typeofs, and decltypes
4768   //   - types which will become injected class names
4769   // Of course, we also need to rebuild any type referencing such a
4770   // type.  It's safest to just say "dependent", but we call out a
4771   // few cases here.
4772 
4773   DeclSpec &DS = D.getMutableDeclSpec();
4774   switch (DS.getTypeSpecType()) {
4775   case DeclSpec::TST_typename:
4776   case DeclSpec::TST_typeofType:
4777   case DeclSpec::TST_underlyingType:
4778   case DeclSpec::TST_atomic: {
4779     // Grab the type from the parser.
4780     TypeSourceInfo *TSI = nullptr;
4781     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4782     if (T.isNull() || !T->isDependentType()) break;
4783 
4784     // Make sure there's a type source info.  This isn't really much
4785     // of a waste; most dependent types should have type source info
4786     // attached already.
4787     if (!TSI)
4788       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4789 
4790     // Rebuild the type in the current instantiation.
4791     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4792     if (!TSI) return true;
4793 
4794     // Store the new type back in the decl spec.
4795     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4796     DS.UpdateTypeRep(LocType);
4797     break;
4798   }
4799 
4800   case DeclSpec::TST_decltype:
4801   case DeclSpec::TST_typeofExpr: {
4802     Expr *E = DS.getRepAsExpr();
4803     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4804     if (Result.isInvalid()) return true;
4805     DS.UpdateExprRep(Result.get());
4806     break;
4807   }
4808 
4809   default:
4810     // Nothing to do for these decl specs.
4811     break;
4812   }
4813 
4814   // It doesn't matter what order we do this in.
4815   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4816     DeclaratorChunk &Chunk = D.getTypeObject(I);
4817 
4818     // The only type information in the declarator which can come
4819     // before the declaration name is the base type of a member
4820     // pointer.
4821     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4822       continue;
4823 
4824     // Rebuild the scope specifier in-place.
4825     CXXScopeSpec &SS = Chunk.Mem.Scope();
4826     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4827       return true;
4828   }
4829 
4830   return false;
4831 }
4832 
4833 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4834   D.setFunctionDefinitionKind(FDK_Declaration);
4835   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4836 
4837   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4838       Dcl && Dcl->getDeclContext()->isFileContext())
4839     Dcl->setTopLevelDeclInObjCContainer();
4840 
4841   return Dcl;
4842 }
4843 
4844 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4845 ///   If T is the name of a class, then each of the following shall have a
4846 ///   name different from T:
4847 ///     - every static data member of class T;
4848 ///     - every member function of class T
4849 ///     - every member of class T that is itself a type;
4850 /// \returns true if the declaration name violates these rules.
4851 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4852                                    DeclarationNameInfo NameInfo) {
4853   DeclarationName Name = NameInfo.getName();
4854 
4855   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
4856   while (Record && Record->isAnonymousStructOrUnion())
4857     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
4858   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
4859     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4860     return true;
4861   }
4862 
4863   return false;
4864 }
4865 
4866 /// \brief Diagnose a declaration whose declarator-id has the given
4867 /// nested-name-specifier.
4868 ///
4869 /// \param SS The nested-name-specifier of the declarator-id.
4870 ///
4871 /// \param DC The declaration context to which the nested-name-specifier
4872 /// resolves.
4873 ///
4874 /// \param Name The name of the entity being declared.
4875 ///
4876 /// \param Loc The location of the name of the entity being declared.
4877 ///
4878 /// \returns true if we cannot safely recover from this error, false otherwise.
4879 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4880                                         DeclarationName Name,
4881                                         SourceLocation Loc) {
4882   DeclContext *Cur = CurContext;
4883   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4884     Cur = Cur->getParent();
4885 
4886   // If the user provided a superfluous scope specifier that refers back to the
4887   // class in which the entity is already declared, diagnose and ignore it.
4888   //
4889   // class X {
4890   //   void X::f();
4891   // };
4892   //
4893   // Note, it was once ill-formed to give redundant qualification in all
4894   // contexts, but that rule was removed by DR482.
4895   if (Cur->Equals(DC)) {
4896     if (Cur->isRecord()) {
4897       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4898                                       : diag::err_member_extra_qualification)
4899         << Name << FixItHint::CreateRemoval(SS.getRange());
4900       SS.clear();
4901     } else {
4902       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4903     }
4904     return false;
4905   }
4906 
4907   // Check whether the qualifying scope encloses the scope of the original
4908   // declaration.
4909   if (!Cur->Encloses(DC)) {
4910     if (Cur->isRecord())
4911       Diag(Loc, diag::err_member_qualification)
4912         << Name << SS.getRange();
4913     else if (isa<TranslationUnitDecl>(DC))
4914       Diag(Loc, diag::err_invalid_declarator_global_scope)
4915         << Name << SS.getRange();
4916     else if (isa<FunctionDecl>(Cur))
4917       Diag(Loc, diag::err_invalid_declarator_in_function)
4918         << Name << SS.getRange();
4919     else if (isa<BlockDecl>(Cur))
4920       Diag(Loc, diag::err_invalid_declarator_in_block)
4921         << Name << SS.getRange();
4922     else
4923       Diag(Loc, diag::err_invalid_declarator_scope)
4924       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4925 
4926     return true;
4927   }
4928 
4929   if (Cur->isRecord()) {
4930     // Cannot qualify members within a class.
4931     Diag(Loc, diag::err_member_qualification)
4932       << Name << SS.getRange();
4933     SS.clear();
4934 
4935     // C++ constructors and destructors with incorrect scopes can break
4936     // our AST invariants by having the wrong underlying types. If
4937     // that's the case, then drop this declaration entirely.
4938     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4939          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4940         !Context.hasSameType(Name.getCXXNameType(),
4941                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4942       return true;
4943 
4944     return false;
4945   }
4946 
4947   // C++11 [dcl.meaning]p1:
4948   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4949   //   not begin with a decltype-specifer"
4950   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4951   while (SpecLoc.getPrefix())
4952     SpecLoc = SpecLoc.getPrefix();
4953   if (dyn_cast_or_null<DecltypeType>(
4954         SpecLoc.getNestedNameSpecifier()->getAsType()))
4955     Diag(Loc, diag::err_decltype_in_declarator)
4956       << SpecLoc.getTypeLoc().getSourceRange();
4957 
4958   return false;
4959 }
4960 
4961 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4962                                   MultiTemplateParamsArg TemplateParamLists) {
4963   // TODO: consider using NameInfo for diagnostic.
4964   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4965   DeclarationName Name = NameInfo.getName();
4966 
4967   // All of these full declarators require an identifier.  If it doesn't have
4968   // one, the ParsedFreeStandingDeclSpec action should be used.
4969   if (D.isDecompositionDeclarator()) {
4970     return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
4971   } else if (!Name) {
4972     if (!D.isInvalidType())  // Reject this if we think it is valid.
4973       Diag(D.getDeclSpec().getLocStart(),
4974            diag::err_declarator_need_ident)
4975         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4976     return nullptr;
4977   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4978     return nullptr;
4979 
4980   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4981   // we find one that is.
4982   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4983          (S->getFlags() & Scope::TemplateParamScope) != 0)
4984     S = S->getParent();
4985 
4986   DeclContext *DC = CurContext;
4987   if (D.getCXXScopeSpec().isInvalid())
4988     D.setInvalidType();
4989   else if (D.getCXXScopeSpec().isSet()) {
4990     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4991                                         UPPC_DeclarationQualifier))
4992       return nullptr;
4993 
4994     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4995     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4996     if (!DC || isa<EnumDecl>(DC)) {
4997       // If we could not compute the declaration context, it's because the
4998       // declaration context is dependent but does not refer to a class,
4999       // class template, or class template partial specialization. Complain
5000       // and return early, to avoid the coming semantic disaster.
5001       Diag(D.getIdentifierLoc(),
5002            diag::err_template_qualified_declarator_no_match)
5003         << D.getCXXScopeSpec().getScopeRep()
5004         << D.getCXXScopeSpec().getRange();
5005       return nullptr;
5006     }
5007     bool IsDependentContext = DC->isDependentContext();
5008 
5009     if (!IsDependentContext &&
5010         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5011       return nullptr;
5012 
5013     // If a class is incomplete, do not parse entities inside it.
5014     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5015       Diag(D.getIdentifierLoc(),
5016            diag::err_member_def_undefined_record)
5017         << Name << DC << D.getCXXScopeSpec().getRange();
5018       return nullptr;
5019     }
5020     if (!D.getDeclSpec().isFriendSpecified()) {
5021       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
5022                                       Name, D.getIdentifierLoc())) {
5023         if (DC->isRecord())
5024           return nullptr;
5025 
5026         D.setInvalidType();
5027       }
5028     }
5029 
5030     // Check whether we need to rebuild the type of the given
5031     // declaration in the current instantiation.
5032     if (EnteringContext && IsDependentContext &&
5033         TemplateParamLists.size() != 0) {
5034       ContextRAII SavedContext(*this, DC);
5035       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
5036         D.setInvalidType();
5037     }
5038   }
5039 
5040   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5041   QualType R = TInfo->getType();
5042 
5043   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
5044     // If this is a typedef, we'll end up spewing multiple diagnostics.
5045     // Just return early; it's safer. If this is a function, let the
5046     // "constructor cannot have a return type" diagnostic handle it.
5047     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5048       return nullptr;
5049 
5050   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
5051                                       UPPC_DeclarationType))
5052     D.setInvalidType();
5053 
5054   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
5055                         ForRedeclaration);
5056 
5057   // See if this is a redefinition of a variable in the same scope.
5058   if (!D.getCXXScopeSpec().isSet()) {
5059     bool IsLinkageLookup = false;
5060     bool CreateBuiltins = false;
5061 
5062     // If the declaration we're planning to build will be a function
5063     // or object with linkage, then look for another declaration with
5064     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
5065     //
5066     // If the declaration we're planning to build will be declared with
5067     // external linkage in the translation unit, create any builtin with
5068     // the same name.
5069     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
5070       /* Do nothing*/;
5071     else if (CurContext->isFunctionOrMethod() &&
5072              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
5073               R->isFunctionType())) {
5074       IsLinkageLookup = true;
5075       CreateBuiltins =
5076           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
5077     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
5078                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
5079       CreateBuiltins = true;
5080 
5081     if (IsLinkageLookup)
5082       Previous.clear(LookupRedeclarationWithLinkage);
5083 
5084     LookupName(Previous, S, CreateBuiltins);
5085   } else { // Something like "int foo::x;"
5086     LookupQualifiedName(Previous, DC);
5087 
5088     // C++ [dcl.meaning]p1:
5089     //   When the declarator-id is qualified, the declaration shall refer to a
5090     //  previously declared member of the class or namespace to which the
5091     //  qualifier refers (or, in the case of a namespace, of an element of the
5092     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5093     //  thereof; [...]
5094     //
5095     // Note that we already checked the context above, and that we do not have
5096     // enough information to make sure that Previous contains the declaration
5097     // we want to match. For example, given:
5098     //
5099     //   class X {
5100     //     void f();
5101     //     void f(float);
5102     //   };
5103     //
5104     //   void X::f(int) { } // ill-formed
5105     //
5106     // In this case, Previous will point to the overload set
5107     // containing the two f's declared in X, but neither of them
5108     // matches.
5109 
5110     // C++ [dcl.meaning]p1:
5111     //   [...] the member shall not merely have been introduced by a
5112     //   using-declaration in the scope of the class or namespace nominated by
5113     //   the nested-name-specifier of the declarator-id.
5114     RemoveUsingDecls(Previous);
5115   }
5116 
5117   if (Previous.isSingleResult() &&
5118       Previous.getFoundDecl()->isTemplateParameter()) {
5119     // Maybe we will complain about the shadowed template parameter.
5120     if (!D.isInvalidType())
5121       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5122                                       Previous.getFoundDecl());
5123 
5124     // Just pretend that we didn't see the previous declaration.
5125     Previous.clear();
5126   }
5127 
5128   // In C++, the previous declaration we find might be a tag type
5129   // (class or enum). In this case, the new declaration will hide the
5130   // tag type. Note that this does does not apply if we're declaring a
5131   // typedef (C++ [dcl.typedef]p4).
5132   if (Previous.isSingleTagDecl() &&
5133       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5134     Previous.clear();
5135 
5136   // Check that there are no default arguments other than in the parameters
5137   // of a function declaration (C++ only).
5138   if (getLangOpts().CPlusPlus)
5139     CheckExtraCXXDefaultArguments(D);
5140 
5141   if (D.getDeclSpec().isConceptSpecified()) {
5142     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5143     // applied only to the definition of a function template or variable
5144     // template, declared in namespace scope
5145     if (!TemplateParamLists.size()) {
5146       Diag(D.getDeclSpec().getConceptSpecLoc(),
5147            diag:: err_concept_wrong_decl_kind);
5148       return nullptr;
5149     }
5150 
5151     if (!DC->getRedeclContext()->isFileContext()) {
5152       Diag(D.getIdentifierLoc(),
5153            diag::err_concept_decls_may_only_appear_in_namespace_scope);
5154       return nullptr;
5155     }
5156   }
5157 
5158   NamedDecl *New;
5159 
5160   bool AddToScope = true;
5161   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5162     if (TemplateParamLists.size()) {
5163       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5164       return nullptr;
5165     }
5166 
5167     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5168   } else if (R->isFunctionType()) {
5169     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5170                                   TemplateParamLists,
5171                                   AddToScope);
5172   } else {
5173     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5174                                   AddToScope);
5175   }
5176 
5177   if (!New)
5178     return nullptr;
5179 
5180   // If this has an identifier and is not a function template specialization,
5181   // add it to the scope stack.
5182   if (New->getDeclName() && AddToScope) {
5183     // Only make a locally-scoped extern declaration visible if it is the first
5184     // declaration of this entity. Qualified lookup for such an entity should
5185     // only find this declaration if there is no visible declaration of it.
5186     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5187     PushOnScopeChains(New, S, AddToContext);
5188     if (!AddToContext)
5189       CurContext->addHiddenDecl(New);
5190   }
5191 
5192   if (isInOpenMPDeclareTargetContext())
5193     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5194 
5195   return New;
5196 }
5197 
5198 /// Helper method to turn variable array types into constant array
5199 /// types in certain situations which would otherwise be errors (for
5200 /// GCC compatibility).
5201 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5202                                                     ASTContext &Context,
5203                                                     bool &SizeIsNegative,
5204                                                     llvm::APSInt &Oversized) {
5205   // This method tries to turn a variable array into a constant
5206   // array even when the size isn't an ICE.  This is necessary
5207   // for compatibility with code that depends on gcc's buggy
5208   // constant expression folding, like struct {char x[(int)(char*)2];}
5209   SizeIsNegative = false;
5210   Oversized = 0;
5211 
5212   if (T->isDependentType())
5213     return QualType();
5214 
5215   QualifierCollector Qs;
5216   const Type *Ty = Qs.strip(T);
5217 
5218   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5219     QualType Pointee = PTy->getPointeeType();
5220     QualType FixedType =
5221         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5222                                             Oversized);
5223     if (FixedType.isNull()) return FixedType;
5224     FixedType = Context.getPointerType(FixedType);
5225     return Qs.apply(Context, FixedType);
5226   }
5227   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5228     QualType Inner = PTy->getInnerType();
5229     QualType FixedType =
5230         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5231                                             Oversized);
5232     if (FixedType.isNull()) return FixedType;
5233     FixedType = Context.getParenType(FixedType);
5234     return Qs.apply(Context, FixedType);
5235   }
5236 
5237   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5238   if (!VLATy)
5239     return QualType();
5240   // FIXME: We should probably handle this case
5241   if (VLATy->getElementType()->isVariablyModifiedType())
5242     return QualType();
5243 
5244   llvm::APSInt Res;
5245   if (!VLATy->getSizeExpr() ||
5246       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5247     return QualType();
5248 
5249   // Check whether the array size is negative.
5250   if (Res.isSigned() && Res.isNegative()) {
5251     SizeIsNegative = true;
5252     return QualType();
5253   }
5254 
5255   // Check whether the array is too large to be addressed.
5256   unsigned ActiveSizeBits
5257     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5258                                               Res);
5259   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5260     Oversized = Res;
5261     return QualType();
5262   }
5263 
5264   return Context.getConstantArrayType(VLATy->getElementType(),
5265                                       Res, ArrayType::Normal, 0);
5266 }
5267 
5268 static void
5269 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5270   SrcTL = SrcTL.getUnqualifiedLoc();
5271   DstTL = DstTL.getUnqualifiedLoc();
5272   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5273     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5274     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5275                                       DstPTL.getPointeeLoc());
5276     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5277     return;
5278   }
5279   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5280     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5281     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5282                                       DstPTL.getInnerLoc());
5283     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5284     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5285     return;
5286   }
5287   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5288   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5289   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5290   TypeLoc DstElemTL = DstATL.getElementLoc();
5291   DstElemTL.initializeFullCopy(SrcElemTL);
5292   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5293   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5294   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5295 }
5296 
5297 /// Helper method to turn variable array types into constant array
5298 /// types in certain situations which would otherwise be errors (for
5299 /// GCC compatibility).
5300 static TypeSourceInfo*
5301 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5302                                               ASTContext &Context,
5303                                               bool &SizeIsNegative,
5304                                               llvm::APSInt &Oversized) {
5305   QualType FixedTy
5306     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5307                                           SizeIsNegative, Oversized);
5308   if (FixedTy.isNull())
5309     return nullptr;
5310   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5311   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5312                                     FixedTInfo->getTypeLoc());
5313   return FixedTInfo;
5314 }
5315 
5316 /// \brief Register the given locally-scoped extern "C" declaration so
5317 /// that it can be found later for redeclarations. We include any extern "C"
5318 /// declaration that is not visible in the translation unit here, not just
5319 /// function-scope declarations.
5320 void
5321 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5322   if (!getLangOpts().CPlusPlus &&
5323       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5324     // Don't need to track declarations in the TU in C.
5325     return;
5326 
5327   // Note that we have a locally-scoped external with this name.
5328   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5329 }
5330 
5331 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5332   // FIXME: We can have multiple results via __attribute__((overloadable)).
5333   auto Result = Context.getExternCContextDecl()->lookup(Name);
5334   return Result.empty() ? nullptr : *Result.begin();
5335 }
5336 
5337 /// \brief Diagnose function specifiers on a declaration of an identifier that
5338 /// does not identify a function.
5339 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5340   // FIXME: We should probably indicate the identifier in question to avoid
5341   // confusion for constructs like "virtual int a(), b;"
5342   if (DS.isVirtualSpecified())
5343     Diag(DS.getVirtualSpecLoc(),
5344          diag::err_virtual_non_function);
5345 
5346   if (DS.isExplicitSpecified())
5347     Diag(DS.getExplicitSpecLoc(),
5348          diag::err_explicit_non_function);
5349 
5350   if (DS.isNoreturnSpecified())
5351     Diag(DS.getNoreturnSpecLoc(),
5352          diag::err_noreturn_non_function);
5353 }
5354 
5355 NamedDecl*
5356 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5357                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5358   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5359   if (D.getCXXScopeSpec().isSet()) {
5360     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5361       << D.getCXXScopeSpec().getRange();
5362     D.setInvalidType();
5363     // Pretend we didn't see the scope specifier.
5364     DC = CurContext;
5365     Previous.clear();
5366   }
5367 
5368   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5369 
5370   if (D.getDeclSpec().isInlineSpecified())
5371     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
5372         << getLangOpts().CPlusPlus1z;
5373   if (D.getDeclSpec().isConstexprSpecified())
5374     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5375       << 1;
5376   if (D.getDeclSpec().isConceptSpecified())
5377     Diag(D.getDeclSpec().getConceptSpecLoc(),
5378          diag::err_concept_wrong_decl_kind);
5379 
5380   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5381     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5382       << D.getName().getSourceRange();
5383     return nullptr;
5384   }
5385 
5386   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5387   if (!NewTD) return nullptr;
5388 
5389   // Handle attributes prior to checking for duplicates in MergeVarDecl
5390   ProcessDeclAttributes(S, NewTD, D);
5391 
5392   CheckTypedefForVariablyModifiedType(S, NewTD);
5393 
5394   bool Redeclaration = D.isRedeclaration();
5395   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5396   D.setRedeclaration(Redeclaration);
5397   return ND;
5398 }
5399 
5400 void
5401 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5402   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5403   // then it shall have block scope.
5404   // Note that variably modified types must be fixed before merging the decl so
5405   // that redeclarations will match.
5406   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5407   QualType T = TInfo->getType();
5408   if (T->isVariablyModifiedType()) {
5409     getCurFunction()->setHasBranchProtectedScope();
5410 
5411     if (S->getFnParent() == nullptr) {
5412       bool SizeIsNegative;
5413       llvm::APSInt Oversized;
5414       TypeSourceInfo *FixedTInfo =
5415         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5416                                                       SizeIsNegative,
5417                                                       Oversized);
5418       if (FixedTInfo) {
5419         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5420         NewTD->setTypeSourceInfo(FixedTInfo);
5421       } else {
5422         if (SizeIsNegative)
5423           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5424         else if (T->isVariableArrayType())
5425           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5426         else if (Oversized.getBoolValue())
5427           Diag(NewTD->getLocation(), diag::err_array_too_large)
5428             << Oversized.toString(10);
5429         else
5430           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5431         NewTD->setInvalidDecl();
5432       }
5433     }
5434   }
5435 }
5436 
5437 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5438 /// declares a typedef-name, either using the 'typedef' type specifier or via
5439 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5440 NamedDecl*
5441 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5442                            LookupResult &Previous, bool &Redeclaration) {
5443   // Merge the decl with the existing one if appropriate. If the decl is
5444   // in an outer scope, it isn't the same thing.
5445   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5446                        /*AllowInlineNamespace*/false);
5447   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5448   if (!Previous.empty()) {
5449     Redeclaration = true;
5450     MergeTypedefNameDecl(S, NewTD, Previous);
5451   }
5452 
5453   // If this is the C FILE type, notify the AST context.
5454   if (IdentifierInfo *II = NewTD->getIdentifier())
5455     if (!NewTD->isInvalidDecl() &&
5456         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5457       if (II->isStr("FILE"))
5458         Context.setFILEDecl(NewTD);
5459       else if (II->isStr("jmp_buf"))
5460         Context.setjmp_bufDecl(NewTD);
5461       else if (II->isStr("sigjmp_buf"))
5462         Context.setsigjmp_bufDecl(NewTD);
5463       else if (II->isStr("ucontext_t"))
5464         Context.setucontext_tDecl(NewTD);
5465     }
5466 
5467   return NewTD;
5468 }
5469 
5470 /// \brief Determines whether the given declaration is an out-of-scope
5471 /// previous declaration.
5472 ///
5473 /// This routine should be invoked when name lookup has found a
5474 /// previous declaration (PrevDecl) that is not in the scope where a
5475 /// new declaration by the same name is being introduced. If the new
5476 /// declaration occurs in a local scope, previous declarations with
5477 /// linkage may still be considered previous declarations (C99
5478 /// 6.2.2p4-5, C++ [basic.link]p6).
5479 ///
5480 /// \param PrevDecl the previous declaration found by name
5481 /// lookup
5482 ///
5483 /// \param DC the context in which the new declaration is being
5484 /// declared.
5485 ///
5486 /// \returns true if PrevDecl is an out-of-scope previous declaration
5487 /// for a new delcaration with the same name.
5488 static bool
5489 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5490                                 ASTContext &Context) {
5491   if (!PrevDecl)
5492     return false;
5493 
5494   if (!PrevDecl->hasLinkage())
5495     return false;
5496 
5497   if (Context.getLangOpts().CPlusPlus) {
5498     // C++ [basic.link]p6:
5499     //   If there is a visible declaration of an entity with linkage
5500     //   having the same name and type, ignoring entities declared
5501     //   outside the innermost enclosing namespace scope, the block
5502     //   scope declaration declares that same entity and receives the
5503     //   linkage of the previous declaration.
5504     DeclContext *OuterContext = DC->getRedeclContext();
5505     if (!OuterContext->isFunctionOrMethod())
5506       // This rule only applies to block-scope declarations.
5507       return false;
5508 
5509     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5510     if (PrevOuterContext->isRecord())
5511       // We found a member function: ignore it.
5512       return false;
5513 
5514     // Find the innermost enclosing namespace for the new and
5515     // previous declarations.
5516     OuterContext = OuterContext->getEnclosingNamespaceContext();
5517     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5518 
5519     // The previous declaration is in a different namespace, so it
5520     // isn't the same function.
5521     if (!OuterContext->Equals(PrevOuterContext))
5522       return false;
5523   }
5524 
5525   return true;
5526 }
5527 
5528 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5529   CXXScopeSpec &SS = D.getCXXScopeSpec();
5530   if (!SS.isSet()) return;
5531   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5532 }
5533 
5534 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5535   QualType type = decl->getType();
5536   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5537   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5538     // Various kinds of declaration aren't allowed to be __autoreleasing.
5539     unsigned kind = -1U;
5540     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5541       if (var->hasAttr<BlocksAttr>())
5542         kind = 0; // __block
5543       else if (!var->hasLocalStorage())
5544         kind = 1; // global
5545     } else if (isa<ObjCIvarDecl>(decl)) {
5546       kind = 3; // ivar
5547     } else if (isa<FieldDecl>(decl)) {
5548       kind = 2; // field
5549     }
5550 
5551     if (kind != -1U) {
5552       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5553         << kind;
5554     }
5555   } else if (lifetime == Qualifiers::OCL_None) {
5556     // Try to infer lifetime.
5557     if (!type->isObjCLifetimeType())
5558       return false;
5559 
5560     lifetime = type->getObjCARCImplicitLifetime();
5561     type = Context.getLifetimeQualifiedType(type, lifetime);
5562     decl->setType(type);
5563   }
5564 
5565   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5566     // Thread-local variables cannot have lifetime.
5567     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5568         var->getTLSKind()) {
5569       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5570         << var->getType();
5571       return true;
5572     }
5573   }
5574 
5575   return false;
5576 }
5577 
5578 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5579   // Ensure that an auto decl is deduced otherwise the checks below might cache
5580   // the wrong linkage.
5581   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5582 
5583   // 'weak' only applies to declarations with external linkage.
5584   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5585     if (!ND.isExternallyVisible()) {
5586       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5587       ND.dropAttr<WeakAttr>();
5588     }
5589   }
5590   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5591     if (ND.isExternallyVisible()) {
5592       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5593       ND.dropAttr<WeakRefAttr>();
5594       ND.dropAttr<AliasAttr>();
5595     }
5596   }
5597 
5598   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5599     if (VD->hasInit()) {
5600       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5601         assert(VD->isThisDeclarationADefinition() &&
5602                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5603         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5604         VD->dropAttr<AliasAttr>();
5605       }
5606     }
5607   }
5608 
5609   // 'selectany' only applies to externally visible variable declarations.
5610   // It does not apply to functions.
5611   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5612     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5613       S.Diag(Attr->getLocation(),
5614              diag::err_attribute_selectany_non_extern_data);
5615       ND.dropAttr<SelectAnyAttr>();
5616     }
5617   }
5618 
5619   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5620     // dll attributes require external linkage. Static locals may have external
5621     // linkage but still cannot be explicitly imported or exported.
5622     auto *VD = dyn_cast<VarDecl>(&ND);
5623     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5624       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5625         << &ND << Attr;
5626       ND.setInvalidDecl();
5627     }
5628   }
5629 
5630   // Virtual functions cannot be marked as 'notail'.
5631   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5632     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5633       if (MD->isVirtual()) {
5634         S.Diag(ND.getLocation(),
5635                diag::err_invalid_attribute_on_virtual_function)
5636             << Attr;
5637         ND.dropAttr<NotTailCalledAttr>();
5638       }
5639 }
5640 
5641 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5642                                            NamedDecl *NewDecl,
5643                                            bool IsSpecialization,
5644                                            bool IsDefinition) {
5645   if (OldDecl->isInvalidDecl())
5646     return;
5647 
5648   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5649     OldDecl = OldTD->getTemplatedDecl();
5650     if (!IsSpecialization)
5651       IsDefinition = false;
5652   }
5653   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5654     NewDecl = NewTD->getTemplatedDecl();
5655 
5656   if (!OldDecl || !NewDecl)
5657     return;
5658 
5659   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5660   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5661   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5662   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5663 
5664   // dllimport and dllexport are inheritable attributes so we have to exclude
5665   // inherited attribute instances.
5666   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5667                     (NewExportAttr && !NewExportAttr->isInherited());
5668 
5669   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5670   // the only exception being explicit specializations.
5671   // Implicitly generated declarations are also excluded for now because there
5672   // is no other way to switch these to use dllimport or dllexport.
5673   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5674 
5675   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5676     // Allow with a warning for free functions and global variables.
5677     bool JustWarn = false;
5678     if (!OldDecl->isCXXClassMember()) {
5679       auto *VD = dyn_cast<VarDecl>(OldDecl);
5680       if (VD && !VD->getDescribedVarTemplate())
5681         JustWarn = true;
5682       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5683       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5684         JustWarn = true;
5685     }
5686 
5687     // We cannot change a declaration that's been used because IR has already
5688     // been emitted. Dllimported functions will still work though (modulo
5689     // address equality) as they can use the thunk.
5690     if (OldDecl->isUsed())
5691       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5692         JustWarn = false;
5693 
5694     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5695                                : diag::err_attribute_dll_redeclaration;
5696     S.Diag(NewDecl->getLocation(), DiagID)
5697         << NewDecl
5698         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5699     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5700     if (!JustWarn) {
5701       NewDecl->setInvalidDecl();
5702       return;
5703     }
5704   }
5705 
5706   // A redeclaration is not allowed to drop a dllimport attribute, the only
5707   // exceptions being inline function definitions, local extern declarations,
5708   // qualified friend declarations or special MSVC extension: in the last case,
5709   // the declaration is treated as if it were marked dllexport.
5710   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5711   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5712   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5713     // Ignore static data because out-of-line definitions are diagnosed
5714     // separately.
5715     IsStaticDataMember = VD->isStaticDataMember();
5716     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5717                    VarDecl::DeclarationOnly;
5718   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5719     IsInline = FD->isInlined();
5720     IsQualifiedFriend = FD->getQualifier() &&
5721                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5722   }
5723 
5724   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5725       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5726     if (IsMicrosoft && IsDefinition) {
5727       S.Diag(NewDecl->getLocation(),
5728              diag::warn_redeclaration_without_import_attribute)
5729           << NewDecl;
5730       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5731       NewDecl->dropAttr<DLLImportAttr>();
5732       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
5733           NewImportAttr->getRange(), S.Context,
5734           NewImportAttr->getSpellingListIndex()));
5735     } else {
5736       S.Diag(NewDecl->getLocation(),
5737              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5738           << NewDecl << OldImportAttr;
5739       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5740       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5741       OldDecl->dropAttr<DLLImportAttr>();
5742       NewDecl->dropAttr<DLLImportAttr>();
5743     }
5744   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
5745     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5746     OldDecl->dropAttr<DLLImportAttr>();
5747     NewDecl->dropAttr<DLLImportAttr>();
5748     S.Diag(NewDecl->getLocation(),
5749            diag::warn_dllimport_dropped_from_inline_function)
5750         << NewDecl << OldImportAttr;
5751   }
5752 }
5753 
5754 /// Given that we are within the definition of the given function,
5755 /// will that definition behave like C99's 'inline', where the
5756 /// definition is discarded except for optimization purposes?
5757 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5758   // Try to avoid calling GetGVALinkageForFunction.
5759 
5760   // All cases of this require the 'inline' keyword.
5761   if (!FD->isInlined()) return false;
5762 
5763   // This is only possible in C++ with the gnu_inline attribute.
5764   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5765     return false;
5766 
5767   // Okay, go ahead and call the relatively-more-expensive function.
5768   return S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5769 }
5770 
5771 /// Determine whether a variable is extern "C" prior to attaching
5772 /// an initializer. We can't just call isExternC() here, because that
5773 /// will also compute and cache whether the declaration is externally
5774 /// visible, which might change when we attach the initializer.
5775 ///
5776 /// This can only be used if the declaration is known to not be a
5777 /// redeclaration of an internal linkage declaration.
5778 ///
5779 /// For instance:
5780 ///
5781 ///   auto x = []{};
5782 ///
5783 /// Attaching the initializer here makes this declaration not externally
5784 /// visible, because its type has internal linkage.
5785 ///
5786 /// FIXME: This is a hack.
5787 template<typename T>
5788 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5789   if (S.getLangOpts().CPlusPlus) {
5790     // In C++, the overloadable attribute negates the effects of extern "C".
5791     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5792       return false;
5793 
5794     // So do CUDA's host/device attributes.
5795     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
5796                                  D->template hasAttr<CUDAHostAttr>()))
5797       return false;
5798   }
5799   return D->isExternC();
5800 }
5801 
5802 static bool shouldConsiderLinkage(const VarDecl *VD) {
5803   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5804   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
5805     return VD->hasExternalStorage();
5806   if (DC->isFileContext())
5807     return true;
5808   if (DC->isRecord())
5809     return false;
5810   llvm_unreachable("Unexpected context");
5811 }
5812 
5813 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5814   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5815   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
5816       isa<OMPDeclareReductionDecl>(DC))
5817     return true;
5818   if (DC->isRecord())
5819     return false;
5820   llvm_unreachable("Unexpected context");
5821 }
5822 
5823 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5824                           AttributeList::Kind Kind) {
5825   for (const AttributeList *L = AttrList; L; L = L->getNext())
5826     if (L->getKind() == Kind)
5827       return true;
5828   return false;
5829 }
5830 
5831 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5832                           AttributeList::Kind Kind) {
5833   // Check decl attributes on the DeclSpec.
5834   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5835     return true;
5836 
5837   // Walk the declarator structure, checking decl attributes that were in a type
5838   // position to the decl itself.
5839   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5840     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5841       return true;
5842   }
5843 
5844   // Finally, check attributes on the decl itself.
5845   return hasParsedAttr(S, PD.getAttributes(), Kind);
5846 }
5847 
5848 /// Adjust the \c DeclContext for a function or variable that might be a
5849 /// function-local external declaration.
5850 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5851   if (!DC->isFunctionOrMethod())
5852     return false;
5853 
5854   // If this is a local extern function or variable declared within a function
5855   // template, don't add it into the enclosing namespace scope until it is
5856   // instantiated; it might have a dependent type right now.
5857   if (DC->isDependentContext())
5858     return true;
5859 
5860   // C++11 [basic.link]p7:
5861   //   When a block scope declaration of an entity with linkage is not found to
5862   //   refer to some other declaration, then that entity is a member of the
5863   //   innermost enclosing namespace.
5864   //
5865   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5866   // semantically-enclosing namespace, not a lexically-enclosing one.
5867   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5868     DC = DC->getParent();
5869   return true;
5870 }
5871 
5872 /// \brief Returns true if given declaration has external C language linkage.
5873 static bool isDeclExternC(const Decl *D) {
5874   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5875     return FD->isExternC();
5876   if (const auto *VD = dyn_cast<VarDecl>(D))
5877     return VD->isExternC();
5878 
5879   llvm_unreachable("Unknown type of decl!");
5880 }
5881 
5882 NamedDecl *Sema::ActOnVariableDeclarator(
5883     Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
5884     LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
5885     bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
5886   QualType R = TInfo->getType();
5887   DeclarationName Name = GetNameForDeclarator(D).getName();
5888 
5889   IdentifierInfo *II = Name.getAsIdentifierInfo();
5890 
5891   if (D.isDecompositionDeclarator()) {
5892     AddToScope = false;
5893     // Take the name of the first declarator as our name for diagnostic
5894     // purposes.
5895     auto &Decomp = D.getDecompositionDeclarator();
5896     if (!Decomp.bindings().empty()) {
5897       II = Decomp.bindings()[0].Name;
5898       Name = II;
5899     }
5900   } else if (!II) {
5901     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5902       << Name;
5903     return nullptr;
5904   }
5905 
5906   if (getLangOpts().OpenCL) {
5907     // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
5908     // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
5909     // argument.
5910     if (R->isImageType() || R->isPipeType()) {
5911       Diag(D.getIdentifierLoc(),
5912            diag::err_opencl_type_can_only_be_used_as_function_parameter)
5913           << R;
5914       D.setInvalidType();
5915       return nullptr;
5916     }
5917 
5918     // OpenCL v1.2 s6.9.r:
5919     // The event type cannot be used to declare a program scope variable.
5920     // OpenCL v2.0 s6.9.q:
5921     // The clk_event_t and reserve_id_t types cannot be declared in program scope.
5922     if (NULL == S->getParent()) {
5923       if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
5924         Diag(D.getIdentifierLoc(),
5925              diag::err_invalid_type_for_program_scope_var) << R;
5926         D.setInvalidType();
5927         return nullptr;
5928       }
5929     }
5930 
5931     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5932     QualType NR = R;
5933     while (NR->isPointerType()) {
5934       if (NR->isFunctionPointerType()) {
5935         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5936         D.setInvalidType();
5937         break;
5938       }
5939       NR = NR->getPointeeType();
5940     }
5941 
5942     if (!getOpenCLOptions().cl_khr_fp16) {
5943       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5944       // half array type (unless the cl_khr_fp16 extension is enabled).
5945       if (Context.getBaseElementType(R)->isHalfType()) {
5946         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5947         D.setInvalidType();
5948       }
5949     }
5950 
5951     // OpenCL v1.2 s6.9.b p4:
5952     // The sampler type cannot be used with the __local and __global address
5953     // space qualifiers.
5954     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5955       R.getAddressSpace() == LangAS::opencl_global)) {
5956       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5957     }
5958 
5959     // OpenCL v1.2 s6.9.r:
5960     // The event type cannot be used with the __local, __constant and __global
5961     // address space qualifiers.
5962     if (R->isEventT()) {
5963       if (R.getAddressSpace()) {
5964         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5965         D.setInvalidType();
5966       }
5967     }
5968   }
5969 
5970   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5971   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5972 
5973   // dllimport globals without explicit storage class are treated as extern. We
5974   // have to change the storage class this early to get the right DeclContext.
5975   if (SC == SC_None && !DC->isRecord() &&
5976       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5977       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5978     SC = SC_Extern;
5979 
5980   DeclContext *OriginalDC = DC;
5981   bool IsLocalExternDecl = SC == SC_Extern &&
5982                            adjustContextForLocalExternDecl(DC);
5983 
5984   if (SCSpec == DeclSpec::SCS_mutable) {
5985     // mutable can only appear on non-static class members, so it's always
5986     // an error here
5987     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5988     D.setInvalidType();
5989     SC = SC_None;
5990   }
5991 
5992   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5993       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5994                               D.getDeclSpec().getStorageClassSpecLoc())) {
5995     // In C++11, the 'register' storage class specifier is deprecated.
5996     // Suppress the warning in system macros, it's used in macros in some
5997     // popular C system headers, such as in glibc's htonl() macro.
5998     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5999          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
6000                                    : diag::warn_deprecated_register)
6001       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6002   }
6003 
6004   DiagnoseFunctionSpecifiers(D.getDeclSpec());
6005 
6006   if (!DC->isRecord() && S->getFnParent() == nullptr) {
6007     // C99 6.9p2: The storage-class specifiers auto and register shall not
6008     // appear in the declaration specifiers in an external declaration.
6009     // Global Register+Asm is a GNU extension we support.
6010     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
6011       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
6012       D.setInvalidType();
6013     }
6014   }
6015 
6016   bool IsExplicitSpecialization = false;
6017   bool IsVariableTemplateSpecialization = false;
6018   bool IsPartialSpecialization = false;
6019   bool IsVariableTemplate = false;
6020   VarDecl *NewVD = nullptr;
6021   VarTemplateDecl *NewTemplate = nullptr;
6022   TemplateParameterList *TemplateParams = nullptr;
6023   if (!getLangOpts().CPlusPlus) {
6024     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6025                             D.getIdentifierLoc(), II,
6026                             R, TInfo, SC);
6027 
6028     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
6029       ParsingInitForAutoVars.insert(NewVD);
6030 
6031     if (D.isInvalidType())
6032       NewVD->setInvalidDecl();
6033   } else {
6034     bool Invalid = false;
6035 
6036     if (DC->isRecord() && !CurContext->isRecord()) {
6037       // This is an out-of-line definition of a static data member.
6038       switch (SC) {
6039       case SC_None:
6040         break;
6041       case SC_Static:
6042         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6043              diag::err_static_out_of_line)
6044           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6045         break;
6046       case SC_Auto:
6047       case SC_Register:
6048       case SC_Extern:
6049         // [dcl.stc] p2: The auto or register specifiers shall be applied only
6050         // to names of variables declared in a block or to function parameters.
6051         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
6052         // of class members
6053 
6054         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6055              diag::err_storage_class_for_static_member)
6056           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
6057         break;
6058       case SC_PrivateExtern:
6059         llvm_unreachable("C storage class in c++!");
6060       }
6061     }
6062 
6063     if (SC == SC_Static && CurContext->isRecord()) {
6064       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
6065         if (RD->isLocalClass())
6066           Diag(D.getIdentifierLoc(),
6067                diag::err_static_data_member_not_allowed_in_local_class)
6068             << Name << RD->getDeclName();
6069 
6070         // C++98 [class.union]p1: If a union contains a static data member,
6071         // the program is ill-formed. C++11 drops this restriction.
6072         if (RD->isUnion())
6073           Diag(D.getIdentifierLoc(),
6074                getLangOpts().CPlusPlus11
6075                  ? diag::warn_cxx98_compat_static_data_member_in_union
6076                  : diag::ext_static_data_member_in_union) << Name;
6077         // We conservatively disallow static data members in anonymous structs.
6078         else if (!RD->getDeclName())
6079           Diag(D.getIdentifierLoc(),
6080                diag::err_static_data_member_not_allowed_in_anon_struct)
6081             << Name << RD->isUnion();
6082       }
6083     }
6084 
6085     // Match up the template parameter lists with the scope specifier, then
6086     // determine whether we have a template or a template specialization.
6087     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6088         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6089         D.getCXXScopeSpec(),
6090         D.getName().getKind() == UnqualifiedId::IK_TemplateId
6091             ? D.getName().TemplateId
6092             : nullptr,
6093         TemplateParamLists,
6094         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
6095 
6096     if (TemplateParams) {
6097       if (!TemplateParams->size() &&
6098           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6099         // There is an extraneous 'template<>' for this variable. Complain
6100         // about it, but allow the declaration of the variable.
6101         Diag(TemplateParams->getTemplateLoc(),
6102              diag::err_template_variable_noparams)
6103           << II
6104           << SourceRange(TemplateParams->getTemplateLoc(),
6105                          TemplateParams->getRAngleLoc());
6106         TemplateParams = nullptr;
6107       } else {
6108         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6109           // This is an explicit specialization or a partial specialization.
6110           // FIXME: Check that we can declare a specialization here.
6111           IsVariableTemplateSpecialization = true;
6112           IsPartialSpecialization = TemplateParams->size() > 0;
6113         } else { // if (TemplateParams->size() > 0)
6114           // This is a template declaration.
6115           IsVariableTemplate = true;
6116 
6117           // Check that we can declare a template here.
6118           if (CheckTemplateDeclScope(S, TemplateParams))
6119             return nullptr;
6120 
6121           // Only C++1y supports variable templates (N3651).
6122           Diag(D.getIdentifierLoc(),
6123                getLangOpts().CPlusPlus14
6124                    ? diag::warn_cxx11_compat_variable_template
6125                    : diag::ext_variable_template);
6126         }
6127       }
6128     } else {
6129       assert(
6130           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6131           "should have a 'template<>' for this decl");
6132     }
6133 
6134     if (IsVariableTemplateSpecialization) {
6135       SourceLocation TemplateKWLoc =
6136           TemplateParamLists.size() > 0
6137               ? TemplateParamLists[0]->getTemplateLoc()
6138               : SourceLocation();
6139       DeclResult Res = ActOnVarTemplateSpecialization(
6140           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6141           IsPartialSpecialization);
6142       if (Res.isInvalid())
6143         return nullptr;
6144       NewVD = cast<VarDecl>(Res.get());
6145       AddToScope = false;
6146     } else if (D.isDecompositionDeclarator()) {
6147       NewVD = DecompositionDecl::Create(Context, DC, D.getLocStart(),
6148                                         D.getIdentifierLoc(), R, TInfo, SC,
6149                                         Bindings);
6150     } else
6151       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6152                               D.getIdentifierLoc(), II, R, TInfo, SC);
6153 
6154     // If this is supposed to be a variable template, create it as such.
6155     if (IsVariableTemplate) {
6156       NewTemplate =
6157           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6158                                   TemplateParams, NewVD);
6159       NewVD->setDescribedVarTemplate(NewTemplate);
6160     }
6161 
6162     // If this decl has an auto type in need of deduction, make a note of the
6163     // Decl so we can diagnose uses of it in its own initializer.
6164     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
6165       ParsingInitForAutoVars.insert(NewVD);
6166 
6167     if (D.isInvalidType() || Invalid) {
6168       NewVD->setInvalidDecl();
6169       if (NewTemplate)
6170         NewTemplate->setInvalidDecl();
6171     }
6172 
6173     SetNestedNameSpecifier(NewVD, D);
6174 
6175     // If we have any template parameter lists that don't directly belong to
6176     // the variable (matching the scope specifier), store them.
6177     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6178     if (TemplateParamLists.size() > VDTemplateParamLists)
6179       NewVD->setTemplateParameterListsInfo(
6180           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6181 
6182     if (D.getDeclSpec().isConstexprSpecified()) {
6183       NewVD->setConstexpr(true);
6184       // C++1z [dcl.spec.constexpr]p1:
6185       //   A static data member declared with the constexpr specifier is
6186       //   implicitly an inline variable.
6187       if (NewVD->isStaticDataMember() && getLangOpts().CPlusPlus1z)
6188         NewVD->setImplicitlyInline();
6189     }
6190 
6191     if (D.getDeclSpec().isConceptSpecified()) {
6192       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6193         VTD->setConcept();
6194 
6195       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6196       // be declared with the thread_local, inline, friend, or constexpr
6197       // specifiers, [...]
6198       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6199         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6200              diag::err_concept_decl_invalid_specifiers)
6201             << 0 << 0;
6202         NewVD->setInvalidDecl(true);
6203       }
6204 
6205       if (D.getDeclSpec().isConstexprSpecified()) {
6206         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6207              diag::err_concept_decl_invalid_specifiers)
6208             << 0 << 3;
6209         NewVD->setInvalidDecl(true);
6210       }
6211 
6212       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6213       // applied only to the definition of a function template or variable
6214       // template, declared in namespace scope.
6215       if (IsVariableTemplateSpecialization) {
6216         Diag(D.getDeclSpec().getConceptSpecLoc(),
6217              diag::err_concept_specified_specialization)
6218             << (IsPartialSpecialization ? 2 : 1);
6219       }
6220 
6221       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6222       // following restrictions:
6223       // - The declared type shall have the type bool.
6224       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6225           !NewVD->isInvalidDecl()) {
6226         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6227         NewVD->setInvalidDecl(true);
6228       }
6229     }
6230   }
6231 
6232   if (D.getDeclSpec().isInlineSpecified()) {
6233     if (!getLangOpts().CPlusPlus) {
6234       Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6235           << 0;
6236     } else if (CurContext->isFunctionOrMethod()) {
6237       // 'inline' is not allowed on block scope variable declaration.
6238       Diag(D.getDeclSpec().getInlineSpecLoc(),
6239            diag::err_inline_declaration_block_scope) << Name
6240         << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
6241     } else {
6242       Diag(D.getDeclSpec().getInlineSpecLoc(),
6243            getLangOpts().CPlusPlus1z ? diag::warn_cxx14_compat_inline_variable
6244                                      : diag::ext_inline_variable);
6245       NewVD->setInlineSpecified();
6246     }
6247   }
6248 
6249   // Set the lexical context. If the declarator has a C++ scope specifier, the
6250   // lexical context will be different from the semantic context.
6251   NewVD->setLexicalDeclContext(CurContext);
6252   if (NewTemplate)
6253     NewTemplate->setLexicalDeclContext(CurContext);
6254 
6255   if (IsLocalExternDecl) {
6256     if (D.isDecompositionDeclarator())
6257       for (auto *B : Bindings)
6258         B->setLocalExternDecl();
6259     else
6260       NewVD->setLocalExternDecl();
6261   }
6262 
6263   bool EmitTLSUnsupportedError = false;
6264   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6265     // C++11 [dcl.stc]p4:
6266     //   When thread_local is applied to a variable of block scope the
6267     //   storage-class-specifier static is implied if it does not appear
6268     //   explicitly.
6269     // Core issue: 'static' is not implied if the variable is declared
6270     //   'extern'.
6271     if (NewVD->hasLocalStorage() &&
6272         (SCSpec != DeclSpec::SCS_unspecified ||
6273          TSCS != DeclSpec::TSCS_thread_local ||
6274          !DC->isFunctionOrMethod()))
6275       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6276            diag::err_thread_non_global)
6277         << DeclSpec::getSpecifierName(TSCS);
6278     else if (!Context.getTargetInfo().isTLSSupported()) {
6279       if (getLangOpts().CUDA) {
6280         // Postpone error emission until we've collected attributes required to
6281         // figure out whether it's a host or device variable and whether the
6282         // error should be ignored.
6283         EmitTLSUnsupportedError = true;
6284         // We still need to mark the variable as TLS so it shows up in AST with
6285         // proper storage class for other tools to use even if we're not going
6286         // to emit any code for it.
6287         NewVD->setTSCSpec(TSCS);
6288       } else
6289         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6290              diag::err_thread_unsupported);
6291     } else
6292       NewVD->setTSCSpec(TSCS);
6293   }
6294 
6295   // C99 6.7.4p3
6296   //   An inline definition of a function with external linkage shall
6297   //   not contain a definition of a modifiable object with static or
6298   //   thread storage duration...
6299   // We only apply this when the function is required to be defined
6300   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6301   // that a local variable with thread storage duration still has to
6302   // be marked 'static'.  Also note that it's possible to get these
6303   // semantics in C++ using __attribute__((gnu_inline)).
6304   if (SC == SC_Static && S->getFnParent() != nullptr &&
6305       !NewVD->getType().isConstQualified()) {
6306     FunctionDecl *CurFD = getCurFunctionDecl();
6307     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6308       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6309            diag::warn_static_local_in_extern_inline);
6310       MaybeSuggestAddingStaticToDecl(CurFD);
6311     }
6312   }
6313 
6314   if (D.getDeclSpec().isModulePrivateSpecified()) {
6315     if (IsVariableTemplateSpecialization)
6316       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6317           << (IsPartialSpecialization ? 1 : 0)
6318           << FixItHint::CreateRemoval(
6319                  D.getDeclSpec().getModulePrivateSpecLoc());
6320     else if (IsExplicitSpecialization)
6321       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6322         << 2
6323         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6324     else if (NewVD->hasLocalStorage())
6325       Diag(NewVD->getLocation(), diag::err_module_private_local)
6326         << 0 << NewVD->getDeclName()
6327         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6328         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6329     else {
6330       NewVD->setModulePrivate();
6331       if (NewTemplate)
6332         NewTemplate->setModulePrivate();
6333       for (auto *B : Bindings)
6334         B->setModulePrivate();
6335     }
6336   }
6337 
6338   // Handle attributes prior to checking for duplicates in MergeVarDecl
6339   ProcessDeclAttributes(S, NewVD, D);
6340 
6341   if (getLangOpts().CUDA) {
6342     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6343       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6344            diag::err_thread_unsupported);
6345     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6346     // storage [duration]."
6347     if (SC == SC_None && S->getFnParent() != nullptr &&
6348         (NewVD->hasAttr<CUDASharedAttr>() ||
6349          NewVD->hasAttr<CUDAConstantAttr>())) {
6350       NewVD->setStorageClass(SC_Static);
6351     }
6352   }
6353 
6354   // Ensure that dllimport globals without explicit storage class are treated as
6355   // extern. The storage class is set above using parsed attributes. Now we can
6356   // check the VarDecl itself.
6357   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6358          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6359          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6360 
6361   // In auto-retain/release, infer strong retension for variables of
6362   // retainable type.
6363   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6364     NewVD->setInvalidDecl();
6365 
6366   // Handle GNU asm-label extension (encoded as an attribute).
6367   if (Expr *E = (Expr*)D.getAsmLabel()) {
6368     // The parser guarantees this is a string.
6369     StringLiteral *SE = cast<StringLiteral>(E);
6370     StringRef Label = SE->getString();
6371     if (S->getFnParent() != nullptr) {
6372       switch (SC) {
6373       case SC_None:
6374       case SC_Auto:
6375         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6376         break;
6377       case SC_Register:
6378         // Local Named register
6379         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6380             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6381           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6382         break;
6383       case SC_Static:
6384       case SC_Extern:
6385       case SC_PrivateExtern:
6386         break;
6387       }
6388     } else if (SC == SC_Register) {
6389       // Global Named register
6390       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6391         const auto &TI = Context.getTargetInfo();
6392         bool HasSizeMismatch;
6393 
6394         if (!TI.isValidGCCRegisterName(Label))
6395           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6396         else if (!TI.validateGlobalRegisterVariable(Label,
6397                                                     Context.getTypeSize(R),
6398                                                     HasSizeMismatch))
6399           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6400         else if (HasSizeMismatch)
6401           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6402       }
6403 
6404       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6405         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6406         NewVD->setInvalidDecl(true);
6407       }
6408     }
6409 
6410     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6411                                                 Context, Label, 0));
6412   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6413     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6414       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6415     if (I != ExtnameUndeclaredIdentifiers.end()) {
6416       if (isDeclExternC(NewVD)) {
6417         NewVD->addAttr(I->second);
6418         ExtnameUndeclaredIdentifiers.erase(I);
6419       } else
6420         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6421             << /*Variable*/1 << NewVD;
6422     }
6423   }
6424 
6425   // Diagnose shadowed variables before filtering for scope.
6426   if (D.getCXXScopeSpec().isEmpty())
6427     CheckShadow(S, NewVD, Previous);
6428 
6429   // Don't consider existing declarations that are in a different
6430   // scope and are out-of-semantic-context declarations (if the new
6431   // declaration has linkage).
6432   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6433                        D.getCXXScopeSpec().isNotEmpty() ||
6434                        IsExplicitSpecialization ||
6435                        IsVariableTemplateSpecialization);
6436 
6437   // Check whether the previous declaration is in the same block scope. This
6438   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6439   if (getLangOpts().CPlusPlus &&
6440       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6441     NewVD->setPreviousDeclInSameBlockScope(
6442         Previous.isSingleResult() && !Previous.isShadowed() &&
6443         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6444 
6445   if (!getLangOpts().CPlusPlus) {
6446     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6447   } else {
6448     // If this is an explicit specialization of a static data member, check it.
6449     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6450         CheckMemberSpecialization(NewVD, Previous))
6451       NewVD->setInvalidDecl();
6452 
6453     // Merge the decl with the existing one if appropriate.
6454     if (!Previous.empty()) {
6455       if (Previous.isSingleResult() &&
6456           isa<FieldDecl>(Previous.getFoundDecl()) &&
6457           D.getCXXScopeSpec().isSet()) {
6458         // The user tried to define a non-static data member
6459         // out-of-line (C++ [dcl.meaning]p1).
6460         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6461           << D.getCXXScopeSpec().getRange();
6462         Previous.clear();
6463         NewVD->setInvalidDecl();
6464       }
6465     } else if (D.getCXXScopeSpec().isSet()) {
6466       // No previous declaration in the qualifying scope.
6467       Diag(D.getIdentifierLoc(), diag::err_no_member)
6468         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6469         << D.getCXXScopeSpec().getRange();
6470       NewVD->setInvalidDecl();
6471     }
6472 
6473     if (!IsVariableTemplateSpecialization)
6474       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6475 
6476     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6477     // an explicit specialization (14.8.3) or a partial specialization of a
6478     // concept definition.
6479     if (IsVariableTemplateSpecialization &&
6480         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6481         Previous.isSingleResult()) {
6482       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6483       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6484         if (VarTmpl->isConcept()) {
6485           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6486               << 1                            /*variable*/
6487               << (IsPartialSpecialization ? 2 /*partially specialized*/
6488                                           : 1 /*explicitly specialized*/);
6489           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6490           NewVD->setInvalidDecl();
6491         }
6492       }
6493     }
6494 
6495     if (NewTemplate) {
6496       VarTemplateDecl *PrevVarTemplate =
6497           NewVD->getPreviousDecl()
6498               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6499               : nullptr;
6500 
6501       // Check the template parameter list of this declaration, possibly
6502       // merging in the template parameter list from the previous variable
6503       // template declaration.
6504       if (CheckTemplateParameterList(
6505               TemplateParams,
6506               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6507                               : nullptr,
6508               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6509                DC->isDependentContext())
6510                   ? TPC_ClassTemplateMember
6511                   : TPC_VarTemplate))
6512         NewVD->setInvalidDecl();
6513 
6514       // If we are providing an explicit specialization of a static variable
6515       // template, make a note of that.
6516       if (PrevVarTemplate &&
6517           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6518         PrevVarTemplate->setMemberSpecialization();
6519     }
6520   }
6521 
6522   ProcessPragmaWeak(S, NewVD);
6523 
6524   // If this is the first declaration of an extern C variable, update
6525   // the map of such variables.
6526   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6527       isIncompleteDeclExternC(*this, NewVD))
6528     RegisterLocallyScopedExternCDecl(NewVD, S);
6529 
6530   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6531     Decl *ManglingContextDecl;
6532     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6533             NewVD->getDeclContext(), ManglingContextDecl)) {
6534       Context.setManglingNumber(
6535           NewVD, MCtx->getManglingNumber(
6536                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6537       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6538     }
6539   }
6540 
6541   // Special handling of variable named 'main'.
6542   if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
6543       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6544       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6545 
6546     // C++ [basic.start.main]p3
6547     // A program that declares a variable main at global scope is ill-formed.
6548     if (getLangOpts().CPlusPlus)
6549       Diag(D.getLocStart(), diag::err_main_global_variable);
6550 
6551     // In C, and external-linkage variable named main results in undefined
6552     // behavior.
6553     else if (NewVD->hasExternalFormalLinkage())
6554       Diag(D.getLocStart(), diag::warn_main_redefined);
6555   }
6556 
6557   if (D.isRedeclaration() && !Previous.empty()) {
6558     checkDLLAttributeRedeclaration(
6559         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6560         IsExplicitSpecialization, D.isFunctionDefinition());
6561   }
6562 
6563   if (NewTemplate) {
6564     if (NewVD->isInvalidDecl())
6565       NewTemplate->setInvalidDecl();
6566     ActOnDocumentableDecl(NewTemplate);
6567     return NewTemplate;
6568   }
6569 
6570   return NewVD;
6571 }
6572 
6573 /// Enum describing the %select options in diag::warn_decl_shadow.
6574 enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field };
6575 
6576 /// Determine what kind of declaration we're shadowing.
6577 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6578                                                 const DeclContext *OldDC) {
6579   if (isa<RecordDecl>(OldDC))
6580     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6581   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6582 }
6583 
6584 /// Return the location of the capture if the given lambda captures the given
6585 /// variable \p VD, or an invalid source location otherwise.
6586 static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI,
6587                                          const VarDecl *VD) {
6588   for (const LambdaScopeInfo::Capture &Capture : LSI->Captures) {
6589     if (Capture.isVariableCapture() && Capture.getVariable() == VD)
6590       return Capture.getLocation();
6591   }
6592   return SourceLocation();
6593 }
6594 
6595 /// \brief Diagnose variable or built-in function shadowing.  Implements
6596 /// -Wshadow.
6597 ///
6598 /// This method is called whenever a VarDecl is added to a "useful"
6599 /// scope.
6600 ///
6601 /// \param S the scope in which the shadowing name is being declared
6602 /// \param R the lookup of the name
6603 ///
6604 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
6605   // Return if warning is ignored.
6606   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6607     return;
6608 
6609   // Don't diagnose declarations at file scope.
6610   if (D->hasGlobalStorage())
6611     return;
6612 
6613   DeclContext *NewDC = D->getDeclContext();
6614 
6615   // Only diagnose if we're shadowing an unambiguous field or variable.
6616   if (R.getResultKind() != LookupResult::Found)
6617     return;
6618 
6619   NamedDecl* ShadowedDecl = R.getFoundDecl();
6620   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
6621     return;
6622 
6623   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6624     // Fields are not shadowed by variables in C++ static methods.
6625     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6626       if (MD->isStatic())
6627         return;
6628 
6629     // Fields shadowed by constructor parameters are a special case. Usually
6630     // the constructor initializes the field with the parameter.
6631     if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) {
6632       // Remember that this was shadowed so we can either warn about its
6633       // modification or its existence depending on warning settings.
6634       D = D->getCanonicalDecl();
6635       ShadowingDecls.insert({D, FD});
6636       return;
6637     }
6638   }
6639 
6640   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6641     if (shadowedVar->isExternC()) {
6642       // For shadowing external vars, make sure that we point to the global
6643       // declaration, not a locally scoped extern declaration.
6644       for (auto I : shadowedVar->redecls())
6645         if (I->isFileVarDecl()) {
6646           ShadowedDecl = I;
6647           break;
6648         }
6649     }
6650 
6651   DeclContext *OldDC = ShadowedDecl->getDeclContext();
6652 
6653   unsigned WarningDiag = diag::warn_decl_shadow;
6654   SourceLocation CaptureLoc;
6655   if (isa<VarDecl>(ShadowedDecl) && NewDC && isa<CXXMethodDecl>(NewDC)) {
6656     if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
6657       if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
6658         if (RD->getLambdaCaptureDefault() == LCD_None) {
6659           // Try to avoid warnings for lambdas with an explicit capture list.
6660           const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
6661           // Warn only when the lambda captures the shadowed decl explicitly.
6662           CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
6663           if (CaptureLoc.isInvalid())
6664             WarningDiag = diag::warn_decl_shadow_uncaptured_local;
6665         } else {
6666           // Remember that this was shadowed so we can avoid the warning if the
6667           // shadowed decl isn't captured and the warning settings allow it.
6668           cast<LambdaScopeInfo>(getCurFunction())
6669               ->ShadowingDecls.push_back({D, cast<VarDecl>(ShadowedDecl)});
6670           return;
6671         }
6672       }
6673     }
6674   }
6675 
6676   // Only warn about certain kinds of shadowing for class members.
6677   if (NewDC && NewDC->isRecord()) {
6678     // In particular, don't warn about shadowing non-class members.
6679     if (!OldDC->isRecord())
6680       return;
6681 
6682     // TODO: should we warn about static data members shadowing
6683     // static data members from base classes?
6684 
6685     // TODO: don't diagnose for inaccessible shadowed members.
6686     // This is hard to do perfectly because we might friend the
6687     // shadowing context, but that's just a false negative.
6688   }
6689 
6690 
6691   DeclarationName Name = R.getLookupName();
6692 
6693   // Emit warning and note.
6694   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6695     return;
6696   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
6697   Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
6698   if (!CaptureLoc.isInvalid())
6699     Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
6700         << Name << /*explicitly*/ 1;
6701   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6702 }
6703 
6704 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
6705 /// when these variables are captured by the lambda.
6706 void Sema::DiagnoseShadowingLambdaDecls(const LambdaScopeInfo *LSI) {
6707   for (const auto &Shadow : LSI->ShadowingDecls) {
6708     const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
6709     // Try to avoid the warning when the shadowed decl isn't captured.
6710     SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
6711     const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6712     Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
6713                                        ? diag::warn_decl_shadow_uncaptured_local
6714                                        : diag::warn_decl_shadow)
6715         << Shadow.VD->getDeclName()
6716         << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
6717     if (!CaptureLoc.isInvalid())
6718       Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
6719           << Shadow.VD->getDeclName() << /*explicitly*/ 0;
6720     Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6721   }
6722 }
6723 
6724 /// \brief Check -Wshadow without the advantage of a previous lookup.
6725 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6726   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6727     return;
6728 
6729   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6730                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6731   LookupName(R, S);
6732   CheckShadow(S, D, R);
6733 }
6734 
6735 /// Check if 'E', which is an expression that is about to be modified, refers
6736 /// to a constructor parameter that shadows a field.
6737 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
6738   // Quickly ignore expressions that can't be shadowing ctor parameters.
6739   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
6740     return;
6741   E = E->IgnoreParenImpCasts();
6742   auto *DRE = dyn_cast<DeclRefExpr>(E);
6743   if (!DRE)
6744     return;
6745   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
6746   auto I = ShadowingDecls.find(D);
6747   if (I == ShadowingDecls.end())
6748     return;
6749   const NamedDecl *ShadowedDecl = I->second;
6750   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6751   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
6752   Diag(D->getLocation(), diag::note_var_declared_here) << D;
6753   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6754 
6755   // Avoid issuing multiple warnings about the same decl.
6756   ShadowingDecls.erase(I);
6757 }
6758 
6759 /// Check for conflict between this global or extern "C" declaration and
6760 /// previous global or extern "C" declarations. This is only used in C++.
6761 template<typename T>
6762 static bool checkGlobalOrExternCConflict(
6763     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6764   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6765   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6766 
6767   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6768     // The common case: this global doesn't conflict with any extern "C"
6769     // declaration.
6770     return false;
6771   }
6772 
6773   if (Prev) {
6774     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6775       // Both the old and new declarations have C language linkage. This is a
6776       // redeclaration.
6777       Previous.clear();
6778       Previous.addDecl(Prev);
6779       return true;
6780     }
6781 
6782     // This is a global, non-extern "C" declaration, and there is a previous
6783     // non-global extern "C" declaration. Diagnose if this is a variable
6784     // declaration.
6785     if (!isa<VarDecl>(ND))
6786       return false;
6787   } else {
6788     // The declaration is extern "C". Check for any declaration in the
6789     // translation unit which might conflict.
6790     if (IsGlobal) {
6791       // We have already performed the lookup into the translation unit.
6792       IsGlobal = false;
6793       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6794            I != E; ++I) {
6795         if (isa<VarDecl>(*I)) {
6796           Prev = *I;
6797           break;
6798         }
6799       }
6800     } else {
6801       DeclContext::lookup_result R =
6802           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6803       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6804            I != E; ++I) {
6805         if (isa<VarDecl>(*I)) {
6806           Prev = *I;
6807           break;
6808         }
6809         // FIXME: If we have any other entity with this name in global scope,
6810         // the declaration is ill-formed, but that is a defect: it breaks the
6811         // 'stat' hack, for instance. Only variables can have mangled name
6812         // clashes with extern "C" declarations, so only they deserve a
6813         // diagnostic.
6814       }
6815     }
6816 
6817     if (!Prev)
6818       return false;
6819   }
6820 
6821   // Use the first declaration's location to ensure we point at something which
6822   // is lexically inside an extern "C" linkage-spec.
6823   assert(Prev && "should have found a previous declaration to diagnose");
6824   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6825     Prev = FD->getFirstDecl();
6826   else
6827     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6828 
6829   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6830     << IsGlobal << ND;
6831   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6832     << IsGlobal;
6833   return false;
6834 }
6835 
6836 /// Apply special rules for handling extern "C" declarations. Returns \c true
6837 /// if we have found that this is a redeclaration of some prior entity.
6838 ///
6839 /// Per C++ [dcl.link]p6:
6840 ///   Two declarations [for a function or variable] with C language linkage
6841 ///   with the same name that appear in different scopes refer to the same
6842 ///   [entity]. An entity with C language linkage shall not be declared with
6843 ///   the same name as an entity in global scope.
6844 template<typename T>
6845 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6846                                                   LookupResult &Previous) {
6847   if (!S.getLangOpts().CPlusPlus) {
6848     // In C, when declaring a global variable, look for a corresponding 'extern'
6849     // variable declared in function scope. We don't need this in C++, because
6850     // we find local extern decls in the surrounding file-scope DeclContext.
6851     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6852       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6853         Previous.clear();
6854         Previous.addDecl(Prev);
6855         return true;
6856       }
6857     }
6858     return false;
6859   }
6860 
6861   // A declaration in the translation unit can conflict with an extern "C"
6862   // declaration.
6863   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6864     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6865 
6866   // An extern "C" declaration can conflict with a declaration in the
6867   // translation unit or can be a redeclaration of an extern "C" declaration
6868   // in another scope.
6869   if (isIncompleteDeclExternC(S,ND))
6870     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6871 
6872   // Neither global nor extern "C": nothing to do.
6873   return false;
6874 }
6875 
6876 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6877   // If the decl is already known invalid, don't check it.
6878   if (NewVD->isInvalidDecl())
6879     return;
6880 
6881   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6882   QualType T = TInfo->getType();
6883 
6884   // Defer checking an 'auto' type until its initializer is attached.
6885   if (T->isUndeducedType())
6886     return;
6887 
6888   if (NewVD->hasAttrs())
6889     CheckAlignasUnderalignment(NewVD);
6890 
6891   if (T->isObjCObjectType()) {
6892     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6893       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6894     T = Context.getObjCObjectPointerType(T);
6895     NewVD->setType(T);
6896   }
6897 
6898   // Emit an error if an address space was applied to decl with local storage.
6899   // This includes arrays of objects with address space qualifiers, but not
6900   // automatic variables that point to other address spaces.
6901   // ISO/IEC TR 18037 S5.1.2
6902   if (!getLangOpts().OpenCL
6903       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6904     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6905     NewVD->setInvalidDecl();
6906     return;
6907   }
6908 
6909   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
6910   // scope.
6911   if (getLangOpts().OpenCLVersion == 120 &&
6912       !getOpenCLOptions().cl_clang_storage_class_specifiers &&
6913       NewVD->isStaticLocal()) {
6914     Diag(NewVD->getLocation(), diag::err_static_function_scope);
6915     NewVD->setInvalidDecl();
6916     return;
6917   }
6918 
6919   if (getLangOpts().OpenCL) {
6920     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
6921     if (NewVD->hasAttr<BlocksAttr>()) {
6922       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
6923       return;
6924     }
6925 
6926     if (T->isBlockPointerType()) {
6927       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
6928       // can't use 'extern' storage class.
6929       if (!T.isConstQualified()) {
6930         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
6931             << 0 /*const*/;
6932         NewVD->setInvalidDecl();
6933         return;
6934       }
6935       if (NewVD->hasExternalStorage()) {
6936         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
6937         NewVD->setInvalidDecl();
6938         return;
6939       }
6940     }
6941     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6942     // __constant address space.
6943     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6944     // variables inside a function can also be declared in the global
6945     // address space.
6946     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
6947         NewVD->hasExternalStorage()) {
6948       if (!T->isSamplerT() &&
6949           !(T.getAddressSpace() == LangAS::opencl_constant ||
6950             (T.getAddressSpace() == LangAS::opencl_global &&
6951              getLangOpts().OpenCLVersion == 200))) {
6952         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
6953         if (getLangOpts().OpenCLVersion == 200)
6954           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6955               << Scope << "global or constant";
6956         else
6957           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6958               << Scope << "constant";
6959         NewVD->setInvalidDecl();
6960         return;
6961       }
6962     } else {
6963       if (T.getAddressSpace() == LangAS::opencl_global) {
6964         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6965             << 1 /*is any function*/ << "global";
6966         NewVD->setInvalidDecl();
6967         return;
6968       }
6969       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
6970       // in functions.
6971       if (T.getAddressSpace() == LangAS::opencl_constant ||
6972           T.getAddressSpace() == LangAS::opencl_local) {
6973         FunctionDecl *FD = getCurFunctionDecl();
6974         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
6975           if (T.getAddressSpace() == LangAS::opencl_constant)
6976             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6977                 << 0 /*non-kernel only*/ << "constant";
6978           else
6979             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6980                 << 0 /*non-kernel only*/ << "local";
6981           NewVD->setInvalidDecl();
6982           return;
6983         }
6984       }
6985     }
6986   }
6987 
6988   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6989       && !NewVD->hasAttr<BlocksAttr>()) {
6990     if (getLangOpts().getGC() != LangOptions::NonGC)
6991       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6992     else {
6993       assert(!getLangOpts().ObjCAutoRefCount);
6994       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6995     }
6996   }
6997 
6998   bool isVM = T->isVariablyModifiedType();
6999   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
7000       NewVD->hasAttr<BlocksAttr>())
7001     getCurFunction()->setHasBranchProtectedScope();
7002 
7003   if ((isVM && NewVD->hasLinkage()) ||
7004       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
7005     bool SizeIsNegative;
7006     llvm::APSInt Oversized;
7007     TypeSourceInfo *FixedTInfo =
7008       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
7009                                                     SizeIsNegative, Oversized);
7010     if (!FixedTInfo && T->isVariableArrayType()) {
7011       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
7012       // FIXME: This won't give the correct result for
7013       // int a[10][n];
7014       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
7015 
7016       if (NewVD->isFileVarDecl())
7017         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
7018         << SizeRange;
7019       else if (NewVD->isStaticLocal())
7020         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
7021         << SizeRange;
7022       else
7023         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
7024         << SizeRange;
7025       NewVD->setInvalidDecl();
7026       return;
7027     }
7028 
7029     if (!FixedTInfo) {
7030       if (NewVD->isFileVarDecl())
7031         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
7032       else
7033         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
7034       NewVD->setInvalidDecl();
7035       return;
7036     }
7037 
7038     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
7039     NewVD->setType(FixedTInfo->getType());
7040     NewVD->setTypeSourceInfo(FixedTInfo);
7041   }
7042 
7043   if (T->isVoidType()) {
7044     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
7045     //                    of objects and functions.
7046     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
7047       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
7048         << T;
7049       NewVD->setInvalidDecl();
7050       return;
7051     }
7052   }
7053 
7054   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
7055     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
7056     NewVD->setInvalidDecl();
7057     return;
7058   }
7059 
7060   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
7061     Diag(NewVD->getLocation(), diag::err_block_on_vm);
7062     NewVD->setInvalidDecl();
7063     return;
7064   }
7065 
7066   if (NewVD->isConstexpr() && !T->isDependentType() &&
7067       RequireLiteralType(NewVD->getLocation(), T,
7068                          diag::err_constexpr_var_non_literal)) {
7069     NewVD->setInvalidDecl();
7070     return;
7071   }
7072 }
7073 
7074 /// \brief Perform semantic checking on a newly-created variable
7075 /// declaration.
7076 ///
7077 /// This routine performs all of the type-checking required for a
7078 /// variable declaration once it has been built. It is used both to
7079 /// check variables after they have been parsed and their declarators
7080 /// have been translated into a declaration, and to check variables
7081 /// that have been instantiated from a template.
7082 ///
7083 /// Sets NewVD->isInvalidDecl() if an error was encountered.
7084 ///
7085 /// Returns true if the variable declaration is a redeclaration.
7086 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
7087   CheckVariableDeclarationType(NewVD);
7088 
7089   // If the decl is already known invalid, don't check it.
7090   if (NewVD->isInvalidDecl())
7091     return false;
7092 
7093   // If we did not find anything by this name, look for a non-visible
7094   // extern "C" declaration with the same name.
7095   if (Previous.empty() &&
7096       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
7097     Previous.setShadowed();
7098 
7099   if (!Previous.empty()) {
7100     MergeVarDecl(NewVD, Previous);
7101     return true;
7102   }
7103   return false;
7104 }
7105 
7106 namespace {
7107 struct FindOverriddenMethod {
7108   Sema *S;
7109   CXXMethodDecl *Method;
7110 
7111   /// Member lookup function that determines whether a given C++
7112   /// method overrides a method in a base class, to be used with
7113   /// CXXRecordDecl::lookupInBases().
7114   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7115     RecordDecl *BaseRecord =
7116         Specifier->getType()->getAs<RecordType>()->getDecl();
7117 
7118     DeclarationName Name = Method->getDeclName();
7119 
7120     // FIXME: Do we care about other names here too?
7121     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7122       // We really want to find the base class destructor here.
7123       QualType T = S->Context.getTypeDeclType(BaseRecord);
7124       CanQualType CT = S->Context.getCanonicalType(T);
7125 
7126       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
7127     }
7128 
7129     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7130          Path.Decls = Path.Decls.slice(1)) {
7131       NamedDecl *D = Path.Decls.front();
7132       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7133         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
7134           return true;
7135       }
7136     }
7137 
7138     return false;
7139   }
7140 };
7141 
7142 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
7143 } // end anonymous namespace
7144 
7145 /// \brief Report an error regarding overriding, along with any relevant
7146 /// overriden methods.
7147 ///
7148 /// \param DiagID the primary error to report.
7149 /// \param MD the overriding method.
7150 /// \param OEK which overrides to include as notes.
7151 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
7152                             OverrideErrorKind OEK = OEK_All) {
7153   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
7154   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
7155                                       E = MD->end_overridden_methods();
7156        I != E; ++I) {
7157     // This check (& the OEK parameter) could be replaced by a predicate, but
7158     // without lambdas that would be overkill. This is still nicer than writing
7159     // out the diag loop 3 times.
7160     if ((OEK == OEK_All) ||
7161         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7162         (OEK == OEK_Deleted && (*I)->isDeleted()))
7163       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7164   }
7165 }
7166 
7167 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7168 /// and if so, check that it's a valid override and remember it.
7169 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7170   // Look for methods in base classes that this method might override.
7171   CXXBasePaths Paths;
7172   FindOverriddenMethod FOM;
7173   FOM.Method = MD;
7174   FOM.S = this;
7175   bool hasDeletedOverridenMethods = false;
7176   bool hasNonDeletedOverridenMethods = false;
7177   bool AddedAny = false;
7178   if (DC->lookupInBases(FOM, Paths)) {
7179     for (auto *I : Paths.found_decls()) {
7180       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7181         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7182         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7183             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7184             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7185             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7186           hasDeletedOverridenMethods |= OldMD->isDeleted();
7187           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7188           AddedAny = true;
7189         }
7190       }
7191     }
7192   }
7193 
7194   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7195     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7196   }
7197   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7198     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7199   }
7200 
7201   return AddedAny;
7202 }
7203 
7204 namespace {
7205   // Struct for holding all of the extra arguments needed by
7206   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7207   struct ActOnFDArgs {
7208     Scope *S;
7209     Declarator &D;
7210     MultiTemplateParamsArg TemplateParamLists;
7211     bool AddToScope;
7212   };
7213 } // end anonymous namespace
7214 
7215 namespace {
7216 
7217 // Callback to only accept typo corrections that have a non-zero edit distance.
7218 // Also only accept corrections that have the same parent decl.
7219 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7220  public:
7221   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7222                             CXXRecordDecl *Parent)
7223       : Context(Context), OriginalFD(TypoFD),
7224         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7225 
7226   bool ValidateCandidate(const TypoCorrection &candidate) override {
7227     if (candidate.getEditDistance() == 0)
7228       return false;
7229 
7230     SmallVector<unsigned, 1> MismatchedParams;
7231     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7232                                           CDeclEnd = candidate.end();
7233          CDecl != CDeclEnd; ++CDecl) {
7234       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7235 
7236       if (FD && !FD->hasBody() &&
7237           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7238         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7239           CXXRecordDecl *Parent = MD->getParent();
7240           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7241             return true;
7242         } else if (!ExpectedParent) {
7243           return true;
7244         }
7245       }
7246     }
7247 
7248     return false;
7249   }
7250 
7251  private:
7252   ASTContext &Context;
7253   FunctionDecl *OriginalFD;
7254   CXXRecordDecl *ExpectedParent;
7255 };
7256 
7257 } // end anonymous namespace
7258 
7259 /// \brief Generate diagnostics for an invalid function redeclaration.
7260 ///
7261 /// This routine handles generating the diagnostic messages for an invalid
7262 /// function redeclaration, including finding possible similar declarations
7263 /// or performing typo correction if there are no previous declarations with
7264 /// the same name.
7265 ///
7266 /// Returns a NamedDecl iff typo correction was performed and substituting in
7267 /// the new declaration name does not cause new errors.
7268 static NamedDecl *DiagnoseInvalidRedeclaration(
7269     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7270     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7271   DeclarationName Name = NewFD->getDeclName();
7272   DeclContext *NewDC = NewFD->getDeclContext();
7273   SmallVector<unsigned, 1> MismatchedParams;
7274   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7275   TypoCorrection Correction;
7276   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7277   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7278                                    : diag::err_member_decl_does_not_match;
7279   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7280                     IsLocalFriend ? Sema::LookupLocalFriendName
7281                                   : Sema::LookupOrdinaryName,
7282                     Sema::ForRedeclaration);
7283 
7284   NewFD->setInvalidDecl();
7285   if (IsLocalFriend)
7286     SemaRef.LookupName(Prev, S);
7287   else
7288     SemaRef.LookupQualifiedName(Prev, NewDC);
7289   assert(!Prev.isAmbiguous() &&
7290          "Cannot have an ambiguity in previous-declaration lookup");
7291   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7292   if (!Prev.empty()) {
7293     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7294          Func != FuncEnd; ++Func) {
7295       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7296       if (FD &&
7297           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7298         // Add 1 to the index so that 0 can mean the mismatch didn't
7299         // involve a parameter
7300         unsigned ParamNum =
7301             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7302         NearMatches.push_back(std::make_pair(FD, ParamNum));
7303       }
7304     }
7305   // If the qualified name lookup yielded nothing, try typo correction
7306   } else if ((Correction = SemaRef.CorrectTypo(
7307                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7308                   &ExtraArgs.D.getCXXScopeSpec(),
7309                   llvm::make_unique<DifferentNameValidatorCCC>(
7310                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7311                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7312     // Set up everything for the call to ActOnFunctionDeclarator
7313     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7314                               ExtraArgs.D.getIdentifierLoc());
7315     Previous.clear();
7316     Previous.setLookupName(Correction.getCorrection());
7317     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7318                                     CDeclEnd = Correction.end();
7319          CDecl != CDeclEnd; ++CDecl) {
7320       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7321       if (FD && !FD->hasBody() &&
7322           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7323         Previous.addDecl(FD);
7324       }
7325     }
7326     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7327 
7328     NamedDecl *Result;
7329     // Retry building the function declaration with the new previous
7330     // declarations, and with errors suppressed.
7331     {
7332       // Trap errors.
7333       Sema::SFINAETrap Trap(SemaRef);
7334 
7335       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7336       // pieces need to verify the typo-corrected C++ declaration and hopefully
7337       // eliminate the need for the parameter pack ExtraArgs.
7338       Result = SemaRef.ActOnFunctionDeclarator(
7339           ExtraArgs.S, ExtraArgs.D,
7340           Correction.getCorrectionDecl()->getDeclContext(),
7341           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7342           ExtraArgs.AddToScope);
7343 
7344       if (Trap.hasErrorOccurred())
7345         Result = nullptr;
7346     }
7347 
7348     if (Result) {
7349       // Determine which correction we picked.
7350       Decl *Canonical = Result->getCanonicalDecl();
7351       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7352            I != E; ++I)
7353         if ((*I)->getCanonicalDecl() == Canonical)
7354           Correction.setCorrectionDecl(*I);
7355 
7356       SemaRef.diagnoseTypo(
7357           Correction,
7358           SemaRef.PDiag(IsLocalFriend
7359                           ? diag::err_no_matching_local_friend_suggest
7360                           : diag::err_member_decl_does_not_match_suggest)
7361             << Name << NewDC << IsDefinition);
7362       return Result;
7363     }
7364 
7365     // Pretend the typo correction never occurred
7366     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7367                               ExtraArgs.D.getIdentifierLoc());
7368     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7369     Previous.clear();
7370     Previous.setLookupName(Name);
7371   }
7372 
7373   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7374       << Name << NewDC << IsDefinition << NewFD->getLocation();
7375 
7376   bool NewFDisConst = false;
7377   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7378     NewFDisConst = NewMD->isConst();
7379 
7380   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7381        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7382        NearMatch != NearMatchEnd; ++NearMatch) {
7383     FunctionDecl *FD = NearMatch->first;
7384     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7385     bool FDisConst = MD && MD->isConst();
7386     bool IsMember = MD || !IsLocalFriend;
7387 
7388     // FIXME: These notes are poorly worded for the local friend case.
7389     if (unsigned Idx = NearMatch->second) {
7390       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7391       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7392       if (Loc.isInvalid()) Loc = FD->getLocation();
7393       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7394                                  : diag::note_local_decl_close_param_match)
7395         << Idx << FDParam->getType()
7396         << NewFD->getParamDecl(Idx - 1)->getType();
7397     } else if (FDisConst != NewFDisConst) {
7398       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7399           << NewFDisConst << FD->getSourceRange().getEnd();
7400     } else
7401       SemaRef.Diag(FD->getLocation(),
7402                    IsMember ? diag::note_member_def_close_match
7403                             : diag::note_local_decl_close_match);
7404   }
7405   return nullptr;
7406 }
7407 
7408 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7409   switch (D.getDeclSpec().getStorageClassSpec()) {
7410   default: llvm_unreachable("Unknown storage class!");
7411   case DeclSpec::SCS_auto:
7412   case DeclSpec::SCS_register:
7413   case DeclSpec::SCS_mutable:
7414     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7415                  diag::err_typecheck_sclass_func);
7416     D.setInvalidType();
7417     break;
7418   case DeclSpec::SCS_unspecified: break;
7419   case DeclSpec::SCS_extern:
7420     if (D.getDeclSpec().isExternInLinkageSpec())
7421       return SC_None;
7422     return SC_Extern;
7423   case DeclSpec::SCS_static: {
7424     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7425       // C99 6.7.1p5:
7426       //   The declaration of an identifier for a function that has
7427       //   block scope shall have no explicit storage-class specifier
7428       //   other than extern
7429       // See also (C++ [dcl.stc]p4).
7430       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7431                    diag::err_static_block_func);
7432       break;
7433     } else
7434       return SC_Static;
7435   }
7436   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7437   }
7438 
7439   // No explicit storage class has already been returned
7440   return SC_None;
7441 }
7442 
7443 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7444                                            DeclContext *DC, QualType &R,
7445                                            TypeSourceInfo *TInfo,
7446                                            StorageClass SC,
7447                                            bool &IsVirtualOkay) {
7448   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7449   DeclarationName Name = NameInfo.getName();
7450 
7451   FunctionDecl *NewFD = nullptr;
7452   bool isInline = D.getDeclSpec().isInlineSpecified();
7453 
7454   if (!SemaRef.getLangOpts().CPlusPlus) {
7455     // Determine whether the function was written with a
7456     // prototype. This true when:
7457     //   - there is a prototype in the declarator, or
7458     //   - the type R of the function is some kind of typedef or other reference
7459     //     to a type name (which eventually refers to a function type).
7460     bool HasPrototype =
7461       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7462       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
7463 
7464     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7465                                  D.getLocStart(), NameInfo, R,
7466                                  TInfo, SC, isInline,
7467                                  HasPrototype, false);
7468     if (D.isInvalidType())
7469       NewFD->setInvalidDecl();
7470 
7471     return NewFD;
7472   }
7473 
7474   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7475   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7476 
7477   // Check that the return type is not an abstract class type.
7478   // For record types, this is done by the AbstractClassUsageDiagnoser once
7479   // the class has been completely parsed.
7480   if (!DC->isRecord() &&
7481       SemaRef.RequireNonAbstractType(
7482           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7483           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7484     D.setInvalidType();
7485 
7486   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7487     // This is a C++ constructor declaration.
7488     assert(DC->isRecord() &&
7489            "Constructors can only be declared in a member context");
7490 
7491     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7492     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7493                                       D.getLocStart(), NameInfo,
7494                                       R, TInfo, isExplicit, isInline,
7495                                       /*isImplicitlyDeclared=*/false,
7496                                       isConstexpr);
7497 
7498   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7499     // This is a C++ destructor declaration.
7500     if (DC->isRecord()) {
7501       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7502       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7503       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7504                                         SemaRef.Context, Record,
7505                                         D.getLocStart(),
7506                                         NameInfo, R, TInfo, isInline,
7507                                         /*isImplicitlyDeclared=*/false);
7508 
7509       // If the class is complete, then we now create the implicit exception
7510       // specification. If the class is incomplete or dependent, we can't do
7511       // it yet.
7512       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7513           Record->getDefinition() && !Record->isBeingDefined() &&
7514           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7515         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7516       }
7517 
7518       IsVirtualOkay = true;
7519       return NewDD;
7520 
7521     } else {
7522       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7523       D.setInvalidType();
7524 
7525       // Create a FunctionDecl to satisfy the function definition parsing
7526       // code path.
7527       return FunctionDecl::Create(SemaRef.Context, DC,
7528                                   D.getLocStart(),
7529                                   D.getIdentifierLoc(), Name, R, TInfo,
7530                                   SC, isInline,
7531                                   /*hasPrototype=*/true, isConstexpr);
7532     }
7533 
7534   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7535     if (!DC->isRecord()) {
7536       SemaRef.Diag(D.getIdentifierLoc(),
7537            diag::err_conv_function_not_member);
7538       return nullptr;
7539     }
7540 
7541     SemaRef.CheckConversionDeclarator(D, R, SC);
7542     IsVirtualOkay = true;
7543     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7544                                      D.getLocStart(), NameInfo,
7545                                      R, TInfo, isInline, isExplicit,
7546                                      isConstexpr, SourceLocation());
7547 
7548   } else if (DC->isRecord()) {
7549     // If the name of the function is the same as the name of the record,
7550     // then this must be an invalid constructor that has a return type.
7551     // (The parser checks for a return type and makes the declarator a
7552     // constructor if it has no return type).
7553     if (Name.getAsIdentifierInfo() &&
7554         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7555       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7556         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7557         << SourceRange(D.getIdentifierLoc());
7558       return nullptr;
7559     }
7560 
7561     // This is a C++ method declaration.
7562     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7563                                                cast<CXXRecordDecl>(DC),
7564                                                D.getLocStart(), NameInfo, R,
7565                                                TInfo, SC, isInline,
7566                                                isConstexpr, SourceLocation());
7567     IsVirtualOkay = !Ret->isStatic();
7568     return Ret;
7569   } else {
7570     bool isFriend =
7571         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7572     if (!isFriend && SemaRef.CurContext->isRecord())
7573       return nullptr;
7574 
7575     // Determine whether the function was written with a
7576     // prototype. This true when:
7577     //   - we're in C++ (where every function has a prototype),
7578     return FunctionDecl::Create(SemaRef.Context, DC,
7579                                 D.getLocStart(),
7580                                 NameInfo, R, TInfo, SC, isInline,
7581                                 true/*HasPrototype*/, isConstexpr);
7582   }
7583 }
7584 
7585 enum OpenCLParamType {
7586   ValidKernelParam,
7587   PtrPtrKernelParam,
7588   PtrKernelParam,
7589   PrivatePtrKernelParam,
7590   InvalidKernelParam,
7591   RecordKernelParam
7592 };
7593 
7594 static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT) {
7595   if (PT->isPointerType()) {
7596     QualType PointeeType = PT->getPointeeType();
7597     if (PointeeType->isPointerType())
7598       return PtrPtrKernelParam;
7599     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
7600                                               : PtrKernelParam;
7601   }
7602 
7603   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7604   // be used as builtin types.
7605 
7606   if (PT->isImageType())
7607     return PtrKernelParam;
7608 
7609   if (PT->isBooleanType())
7610     return InvalidKernelParam;
7611 
7612   if (PT->isEventT())
7613     return InvalidKernelParam;
7614 
7615   // OpenCL extension spec v1.2 s9.5:
7616   // This extension adds support for half scalar and vector types as built-in
7617   // types that can be used for arithmetic operations, conversions etc.
7618   if (!S.getOpenCLOptions().cl_khr_fp16 && PT->isHalfType())
7619     return InvalidKernelParam;
7620 
7621   if (PT->isRecordType())
7622     return RecordKernelParam;
7623 
7624   return ValidKernelParam;
7625 }
7626 
7627 static void checkIsValidOpenCLKernelParameter(
7628   Sema &S,
7629   Declarator &D,
7630   ParmVarDecl *Param,
7631   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7632   QualType PT = Param->getType();
7633 
7634   // Cache the valid types we encounter to avoid rechecking structs that are
7635   // used again
7636   if (ValidTypes.count(PT.getTypePtr()))
7637     return;
7638 
7639   switch (getOpenCLKernelParameterType(S, PT)) {
7640   case PtrPtrKernelParam:
7641     // OpenCL v1.2 s6.9.a:
7642     // A kernel function argument cannot be declared as a
7643     // pointer to a pointer type.
7644     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7645     D.setInvalidType();
7646     return;
7647 
7648   case PrivatePtrKernelParam:
7649     // OpenCL v1.2 s6.9.a:
7650     // A kernel function argument cannot be declared as a
7651     // pointer to the private address space.
7652     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
7653     D.setInvalidType();
7654     return;
7655 
7656     // OpenCL v1.2 s6.9.k:
7657     // Arguments to kernel functions in a program cannot be declared with the
7658     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7659     // uintptr_t or a struct and/or union that contain fields declared to be
7660     // one of these built-in scalar types.
7661 
7662   case InvalidKernelParam:
7663     // OpenCL v1.2 s6.8 n:
7664     // A kernel function argument cannot be declared
7665     // of event_t type.
7666     // Do not diagnose half type since it is diagnosed as invalid argument
7667     // type for any function elsewhere.
7668     if (!PT->isHalfType())
7669       S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7670     D.setInvalidType();
7671     return;
7672 
7673   case PtrKernelParam:
7674   case ValidKernelParam:
7675     ValidTypes.insert(PT.getTypePtr());
7676     return;
7677 
7678   case RecordKernelParam:
7679     break;
7680   }
7681 
7682   // Track nested structs we will inspect
7683   SmallVector<const Decl *, 4> VisitStack;
7684 
7685   // Track where we are in the nested structs. Items will migrate from
7686   // VisitStack to HistoryStack as we do the DFS for bad field.
7687   SmallVector<const FieldDecl *, 4> HistoryStack;
7688   HistoryStack.push_back(nullptr);
7689 
7690   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7691   VisitStack.push_back(PD);
7692 
7693   assert(VisitStack.back() && "First decl null?");
7694 
7695   do {
7696     const Decl *Next = VisitStack.pop_back_val();
7697     if (!Next) {
7698       assert(!HistoryStack.empty());
7699       // Found a marker, we have gone up a level
7700       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7701         ValidTypes.insert(Hist->getType().getTypePtr());
7702 
7703       continue;
7704     }
7705 
7706     // Adds everything except the original parameter declaration (which is not a
7707     // field itself) to the history stack.
7708     const RecordDecl *RD;
7709     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7710       HistoryStack.push_back(Field);
7711       RD = Field->getType()->castAs<RecordType>()->getDecl();
7712     } else {
7713       RD = cast<RecordDecl>(Next);
7714     }
7715 
7716     // Add a null marker so we know when we've gone back up a level
7717     VisitStack.push_back(nullptr);
7718 
7719     for (const auto *FD : RD->fields()) {
7720       QualType QT = FD->getType();
7721 
7722       if (ValidTypes.count(QT.getTypePtr()))
7723         continue;
7724 
7725       OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
7726       if (ParamType == ValidKernelParam)
7727         continue;
7728 
7729       if (ParamType == RecordKernelParam) {
7730         VisitStack.push_back(FD);
7731         continue;
7732       }
7733 
7734       // OpenCL v1.2 s6.9.p:
7735       // Arguments to kernel functions that are declared to be a struct or union
7736       // do not allow OpenCL objects to be passed as elements of the struct or
7737       // union.
7738       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7739           ParamType == PrivatePtrKernelParam) {
7740         S.Diag(Param->getLocation(),
7741                diag::err_record_with_pointers_kernel_param)
7742           << PT->isUnionType()
7743           << PT;
7744       } else {
7745         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7746       }
7747 
7748       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7749         << PD->getDeclName();
7750 
7751       // We have an error, now let's go back up through history and show where
7752       // the offending field came from
7753       for (ArrayRef<const FieldDecl *>::const_iterator
7754                I = HistoryStack.begin() + 1,
7755                E = HistoryStack.end();
7756            I != E; ++I) {
7757         const FieldDecl *OuterField = *I;
7758         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7759           << OuterField->getType();
7760       }
7761 
7762       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7763         << QT->isPointerType()
7764         << QT;
7765       D.setInvalidType();
7766       return;
7767     }
7768   } while (!VisitStack.empty());
7769 }
7770 
7771 NamedDecl*
7772 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7773                               TypeSourceInfo *TInfo, LookupResult &Previous,
7774                               MultiTemplateParamsArg TemplateParamLists,
7775                               bool &AddToScope) {
7776   QualType R = TInfo->getType();
7777 
7778   assert(R.getTypePtr()->isFunctionType());
7779 
7780   // TODO: consider using NameInfo for diagnostic.
7781   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7782   DeclarationName Name = NameInfo.getName();
7783   StorageClass SC = getFunctionStorageClass(*this, D);
7784 
7785   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7786     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7787          diag::err_invalid_thread)
7788       << DeclSpec::getSpecifierName(TSCS);
7789 
7790   if (D.isFirstDeclarationOfMember())
7791     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7792                            D.getIdentifierLoc());
7793 
7794   bool isFriend = false;
7795   FunctionTemplateDecl *FunctionTemplate = nullptr;
7796   bool isExplicitSpecialization = false;
7797   bool isFunctionTemplateSpecialization = false;
7798 
7799   bool isDependentClassScopeExplicitSpecialization = false;
7800   bool HasExplicitTemplateArgs = false;
7801   TemplateArgumentListInfo TemplateArgs;
7802 
7803   bool isVirtualOkay = false;
7804 
7805   DeclContext *OriginalDC = DC;
7806   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7807 
7808   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7809                                               isVirtualOkay);
7810   if (!NewFD) return nullptr;
7811 
7812   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7813     NewFD->setTopLevelDeclInObjCContainer();
7814 
7815   // Set the lexical context. If this is a function-scope declaration, or has a
7816   // C++ scope specifier, or is the object of a friend declaration, the lexical
7817   // context will be different from the semantic context.
7818   NewFD->setLexicalDeclContext(CurContext);
7819 
7820   if (IsLocalExternDecl)
7821     NewFD->setLocalExternDecl();
7822 
7823   if (getLangOpts().CPlusPlus) {
7824     bool isInline = D.getDeclSpec().isInlineSpecified();
7825     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7826     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7827     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7828     bool isConcept = D.getDeclSpec().isConceptSpecified();
7829     isFriend = D.getDeclSpec().isFriendSpecified();
7830     if (isFriend && !isInline && D.isFunctionDefinition()) {
7831       // C++ [class.friend]p5
7832       //   A function can be defined in a friend declaration of a
7833       //   class . . . . Such a function is implicitly inline.
7834       NewFD->setImplicitlyInline();
7835     }
7836 
7837     // If this is a method defined in an __interface, and is not a constructor
7838     // or an overloaded operator, then set the pure flag (isVirtual will already
7839     // return true).
7840     if (const CXXRecordDecl *Parent =
7841           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7842       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7843         NewFD->setPure(true);
7844 
7845       // C++ [class.union]p2
7846       //   A union can have member functions, but not virtual functions.
7847       if (isVirtual && Parent->isUnion())
7848         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7849     }
7850 
7851     SetNestedNameSpecifier(NewFD, D);
7852     isExplicitSpecialization = false;
7853     isFunctionTemplateSpecialization = false;
7854     if (D.isInvalidType())
7855       NewFD->setInvalidDecl();
7856 
7857     // Match up the template parameter lists with the scope specifier, then
7858     // determine whether we have a template or a template specialization.
7859     bool Invalid = false;
7860     if (TemplateParameterList *TemplateParams =
7861             MatchTemplateParametersToScopeSpecifier(
7862                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7863                 D.getCXXScopeSpec(),
7864                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7865                     ? D.getName().TemplateId
7866                     : nullptr,
7867                 TemplateParamLists, isFriend, isExplicitSpecialization,
7868                 Invalid)) {
7869       if (TemplateParams->size() > 0) {
7870         // This is a function template
7871 
7872         // Check that we can declare a template here.
7873         if (CheckTemplateDeclScope(S, TemplateParams))
7874           NewFD->setInvalidDecl();
7875 
7876         // A destructor cannot be a template.
7877         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7878           Diag(NewFD->getLocation(), diag::err_destructor_template);
7879           NewFD->setInvalidDecl();
7880         }
7881 
7882         // If we're adding a template to a dependent context, we may need to
7883         // rebuilding some of the types used within the template parameter list,
7884         // now that we know what the current instantiation is.
7885         if (DC->isDependentContext()) {
7886           ContextRAII SavedContext(*this, DC);
7887           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7888             Invalid = true;
7889         }
7890 
7891         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7892                                                         NewFD->getLocation(),
7893                                                         Name, TemplateParams,
7894                                                         NewFD);
7895         FunctionTemplate->setLexicalDeclContext(CurContext);
7896         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7897 
7898         // For source fidelity, store the other template param lists.
7899         if (TemplateParamLists.size() > 1) {
7900           NewFD->setTemplateParameterListsInfo(Context,
7901                                                TemplateParamLists.drop_back(1));
7902         }
7903       } else {
7904         // This is a function template specialization.
7905         isFunctionTemplateSpecialization = true;
7906         // For source fidelity, store all the template param lists.
7907         if (TemplateParamLists.size() > 0)
7908           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7909 
7910         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7911         if (isFriend) {
7912           // We want to remove the "template<>", found here.
7913           SourceRange RemoveRange = TemplateParams->getSourceRange();
7914 
7915           // If we remove the template<> and the name is not a
7916           // template-id, we're actually silently creating a problem:
7917           // the friend declaration will refer to an untemplated decl,
7918           // and clearly the user wants a template specialization.  So
7919           // we need to insert '<>' after the name.
7920           SourceLocation InsertLoc;
7921           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7922             InsertLoc = D.getName().getSourceRange().getEnd();
7923             InsertLoc = getLocForEndOfToken(InsertLoc);
7924           }
7925 
7926           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7927             << Name << RemoveRange
7928             << FixItHint::CreateRemoval(RemoveRange)
7929             << FixItHint::CreateInsertion(InsertLoc, "<>");
7930         }
7931       }
7932     }
7933     else {
7934       // All template param lists were matched against the scope specifier:
7935       // this is NOT (an explicit specialization of) a template.
7936       if (TemplateParamLists.size() > 0)
7937         // For source fidelity, store all the template param lists.
7938         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7939     }
7940 
7941     if (Invalid) {
7942       NewFD->setInvalidDecl();
7943       if (FunctionTemplate)
7944         FunctionTemplate->setInvalidDecl();
7945     }
7946 
7947     // C++ [dcl.fct.spec]p5:
7948     //   The virtual specifier shall only be used in declarations of
7949     //   nonstatic class member functions that appear within a
7950     //   member-specification of a class declaration; see 10.3.
7951     //
7952     if (isVirtual && !NewFD->isInvalidDecl()) {
7953       if (!isVirtualOkay) {
7954         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7955              diag::err_virtual_non_function);
7956       } else if (!CurContext->isRecord()) {
7957         // 'virtual' was specified outside of the class.
7958         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7959              diag::err_virtual_out_of_class)
7960           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7961       } else if (NewFD->getDescribedFunctionTemplate()) {
7962         // C++ [temp.mem]p3:
7963         //  A member function template shall not be virtual.
7964         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7965              diag::err_virtual_member_function_template)
7966           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7967       } else {
7968         // Okay: Add virtual to the method.
7969         NewFD->setVirtualAsWritten(true);
7970       }
7971 
7972       if (getLangOpts().CPlusPlus14 &&
7973           NewFD->getReturnType()->isUndeducedType())
7974         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7975     }
7976 
7977     if (getLangOpts().CPlusPlus14 &&
7978         (NewFD->isDependentContext() ||
7979          (isFriend && CurContext->isDependentContext())) &&
7980         NewFD->getReturnType()->isUndeducedType()) {
7981       // If the function template is referenced directly (for instance, as a
7982       // member of the current instantiation), pretend it has a dependent type.
7983       // This is not really justified by the standard, but is the only sane
7984       // thing to do.
7985       // FIXME: For a friend function, we have not marked the function as being
7986       // a friend yet, so 'isDependentContext' on the FD doesn't work.
7987       const FunctionProtoType *FPT =
7988           NewFD->getType()->castAs<FunctionProtoType>();
7989       QualType Result =
7990           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7991       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7992                                              FPT->getExtProtoInfo()));
7993     }
7994 
7995     // C++ [dcl.fct.spec]p3:
7996     //  The inline specifier shall not appear on a block scope function
7997     //  declaration.
7998     if (isInline && !NewFD->isInvalidDecl()) {
7999       if (CurContext->isFunctionOrMethod()) {
8000         // 'inline' is not allowed on block scope function declaration.
8001         Diag(D.getDeclSpec().getInlineSpecLoc(),
8002              diag::err_inline_declaration_block_scope) << Name
8003           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
8004       }
8005     }
8006 
8007     // C++ [dcl.fct.spec]p6:
8008     //  The explicit specifier shall be used only in the declaration of a
8009     //  constructor or conversion function within its class definition;
8010     //  see 12.3.1 and 12.3.2.
8011     if (isExplicit && !NewFD->isInvalidDecl()) {
8012       if (!CurContext->isRecord()) {
8013         // 'explicit' was specified outside of the class.
8014         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8015              diag::err_explicit_out_of_class)
8016           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8017       } else if (!isa<CXXConstructorDecl>(NewFD) &&
8018                  !isa<CXXConversionDecl>(NewFD)) {
8019         // 'explicit' was specified on a function that wasn't a constructor
8020         // or conversion function.
8021         Diag(D.getDeclSpec().getExplicitSpecLoc(),
8022              diag::err_explicit_non_ctor_or_conv_function)
8023           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
8024       }
8025     }
8026 
8027     if (isConstexpr) {
8028       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
8029       // are implicitly inline.
8030       NewFD->setImplicitlyInline();
8031 
8032       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
8033       // be either constructors or to return a literal type. Therefore,
8034       // destructors cannot be declared constexpr.
8035       if (isa<CXXDestructorDecl>(NewFD))
8036         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
8037     }
8038 
8039     if (isConcept) {
8040       // This is a function concept.
8041       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
8042         FTD->setConcept();
8043 
8044       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8045       // applied only to the definition of a function template [...]
8046       if (!D.isFunctionDefinition()) {
8047         Diag(D.getDeclSpec().getConceptSpecLoc(),
8048              diag::err_function_concept_not_defined);
8049         NewFD->setInvalidDecl();
8050       }
8051 
8052       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
8053       // have no exception-specification and is treated as if it were specified
8054       // with noexcept(true) (15.4). [...]
8055       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
8056         if (FPT->hasExceptionSpec()) {
8057           SourceRange Range;
8058           if (D.isFunctionDeclarator())
8059             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
8060           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
8061               << FixItHint::CreateRemoval(Range);
8062           NewFD->setInvalidDecl();
8063         } else {
8064           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
8065         }
8066 
8067         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8068         // following restrictions:
8069         // - The declared return type shall have the type bool.
8070         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
8071           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
8072           NewFD->setInvalidDecl();
8073         }
8074 
8075         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
8076         // following restrictions:
8077         // - The declaration's parameter list shall be equivalent to an empty
8078         //   parameter list.
8079         if (FPT->getNumParams() > 0 || FPT->isVariadic())
8080           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
8081       }
8082 
8083       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
8084       // implicity defined to be a constexpr declaration (implicitly inline)
8085       NewFD->setImplicitlyInline();
8086 
8087       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
8088       // be declared with the thread_local, inline, friend, or constexpr
8089       // specifiers, [...]
8090       if (isInline) {
8091         Diag(D.getDeclSpec().getInlineSpecLoc(),
8092              diag::err_concept_decl_invalid_specifiers)
8093             << 1 << 1;
8094         NewFD->setInvalidDecl(true);
8095       }
8096 
8097       if (isFriend) {
8098         Diag(D.getDeclSpec().getFriendSpecLoc(),
8099              diag::err_concept_decl_invalid_specifiers)
8100             << 1 << 2;
8101         NewFD->setInvalidDecl(true);
8102       }
8103 
8104       if (isConstexpr) {
8105         Diag(D.getDeclSpec().getConstexprSpecLoc(),
8106              diag::err_concept_decl_invalid_specifiers)
8107             << 1 << 3;
8108         NewFD->setInvalidDecl(true);
8109       }
8110 
8111       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
8112       // applied only to the definition of a function template or variable
8113       // template, declared in namespace scope.
8114       if (isFunctionTemplateSpecialization) {
8115         Diag(D.getDeclSpec().getConceptSpecLoc(),
8116              diag::err_concept_specified_specialization) << 1;
8117         NewFD->setInvalidDecl(true);
8118         return NewFD;
8119       }
8120     }
8121 
8122     // If __module_private__ was specified, mark the function accordingly.
8123     if (D.getDeclSpec().isModulePrivateSpecified()) {
8124       if (isFunctionTemplateSpecialization) {
8125         SourceLocation ModulePrivateLoc
8126           = D.getDeclSpec().getModulePrivateSpecLoc();
8127         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
8128           << 0
8129           << FixItHint::CreateRemoval(ModulePrivateLoc);
8130       } else {
8131         NewFD->setModulePrivate();
8132         if (FunctionTemplate)
8133           FunctionTemplate->setModulePrivate();
8134       }
8135     }
8136 
8137     if (isFriend) {
8138       if (FunctionTemplate) {
8139         FunctionTemplate->setObjectOfFriendDecl();
8140         FunctionTemplate->setAccess(AS_public);
8141       }
8142       NewFD->setObjectOfFriendDecl();
8143       NewFD->setAccess(AS_public);
8144     }
8145 
8146     // If a function is defined as defaulted or deleted, mark it as such now.
8147     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
8148     // definition kind to FDK_Definition.
8149     switch (D.getFunctionDefinitionKind()) {
8150       case FDK_Declaration:
8151       case FDK_Definition:
8152         break;
8153 
8154       case FDK_Defaulted:
8155         NewFD->setDefaulted();
8156         break;
8157 
8158       case FDK_Deleted:
8159         NewFD->setDeletedAsWritten();
8160         break;
8161     }
8162 
8163     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
8164         D.isFunctionDefinition()) {
8165       // C++ [class.mfct]p2:
8166       //   A member function may be defined (8.4) in its class definition, in
8167       //   which case it is an inline member function (7.1.2)
8168       NewFD->setImplicitlyInline();
8169     }
8170 
8171     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8172         !CurContext->isRecord()) {
8173       // C++ [class.static]p1:
8174       //   A data or function member of a class may be declared static
8175       //   in a class definition, in which case it is a static member of
8176       //   the class.
8177 
8178       // Complain about the 'static' specifier if it's on an out-of-line
8179       // member function definition.
8180       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8181            diag::err_static_out_of_line)
8182         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8183     }
8184 
8185     // C++11 [except.spec]p15:
8186     //   A deallocation function with no exception-specification is treated
8187     //   as if it were specified with noexcept(true).
8188     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8189     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8190          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8191         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8192       NewFD->setType(Context.getFunctionType(
8193           FPT->getReturnType(), FPT->getParamTypes(),
8194           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8195   }
8196 
8197   // Filter out previous declarations that don't match the scope.
8198   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8199                        D.getCXXScopeSpec().isNotEmpty() ||
8200                        isExplicitSpecialization ||
8201                        isFunctionTemplateSpecialization);
8202 
8203   // Handle GNU asm-label extension (encoded as an attribute).
8204   if (Expr *E = (Expr*) D.getAsmLabel()) {
8205     // The parser guarantees this is a string.
8206     StringLiteral *SE = cast<StringLiteral>(E);
8207     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8208                                                 SE->getString(), 0));
8209   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8210     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8211       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8212     if (I != ExtnameUndeclaredIdentifiers.end()) {
8213       if (isDeclExternC(NewFD)) {
8214         NewFD->addAttr(I->second);
8215         ExtnameUndeclaredIdentifiers.erase(I);
8216       } else
8217         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8218             << /*Variable*/0 << NewFD;
8219     }
8220   }
8221 
8222   // Copy the parameter declarations from the declarator D to the function
8223   // declaration NewFD, if they are available.  First scavenge them into Params.
8224   SmallVector<ParmVarDecl*, 16> Params;
8225   unsigned FTIIdx;
8226   if (D.isFunctionDeclarator(FTIIdx)) {
8227     DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(FTIIdx).Fun;
8228 
8229     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8230     // function that takes no arguments, not a function that takes a
8231     // single void argument.
8232     // We let through "const void" here because Sema::GetTypeForDeclarator
8233     // already checks for that case.
8234     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8235       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8236         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8237         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8238         Param->setDeclContext(NewFD);
8239         Params.push_back(Param);
8240 
8241         if (Param->isInvalidDecl())
8242           NewFD->setInvalidDecl();
8243       }
8244     }
8245 
8246     if (!getLangOpts().CPlusPlus) {
8247       // In C, find all the non-parameter declarations from the prototype and
8248       // move them into the new function decl context as well. Typically they
8249       // will have been added to the surrounding context of the prototype.
8250       for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
8251         DeclContext *OldDC = NonParmDecl->getDeclContext();
8252         if (OldDC->containsDecl(NonParmDecl))
8253           OldDC->removeDecl(NonParmDecl);
8254         NonParmDecl->setDeclContext(NewFD);
8255         NewFD->addDecl(NonParmDecl);
8256       }
8257     }
8258   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8259     // When we're declaring a function with a typedef, typeof, etc as in the
8260     // following example, we'll need to synthesize (unnamed)
8261     // parameters for use in the declaration.
8262     //
8263     // @code
8264     // typedef void fn(int);
8265     // fn f;
8266     // @endcode
8267 
8268     // Synthesize a parameter for each argument type.
8269     for (const auto &AI : FT->param_types()) {
8270       ParmVarDecl *Param =
8271           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8272       Param->setScopeInfo(0, Params.size());
8273       Params.push_back(Param);
8274     }
8275   } else {
8276     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8277            "Should not need args for typedef of non-prototype fn");
8278   }
8279 
8280   // Finally, we know we have the right number of parameters, install them.
8281   NewFD->setParams(Params);
8282 
8283   if (D.getDeclSpec().isNoreturnSpecified())
8284     NewFD->addAttr(
8285         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8286                                        Context, 0));
8287 
8288   // Functions returning a variably modified type violate C99 6.7.5.2p2
8289   // because all functions have linkage.
8290   if (!NewFD->isInvalidDecl() &&
8291       NewFD->getReturnType()->isVariablyModifiedType()) {
8292     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8293     NewFD->setInvalidDecl();
8294   }
8295 
8296   // Apply an implicit SectionAttr if #pragma code_seg is active.
8297   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8298       !NewFD->hasAttr<SectionAttr>()) {
8299     NewFD->addAttr(
8300         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8301                                     CodeSegStack.CurrentValue->getString(),
8302                                     CodeSegStack.CurrentPragmaLocation));
8303     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8304                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8305                          ASTContext::PSF_Read,
8306                      NewFD))
8307       NewFD->dropAttr<SectionAttr>();
8308   }
8309 
8310   // Handle attributes.
8311   ProcessDeclAttributes(S, NewFD, D);
8312 
8313   if (getLangOpts().OpenCL) {
8314     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8315     // type declaration will generate a compilation error.
8316     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8317     if (AddressSpace == LangAS::opencl_local ||
8318         AddressSpace == LangAS::opencl_global ||
8319         AddressSpace == LangAS::opencl_constant) {
8320       Diag(NewFD->getLocation(),
8321            diag::err_opencl_return_value_with_address_space);
8322       NewFD->setInvalidDecl();
8323     }
8324   }
8325 
8326   if (!getLangOpts().CPlusPlus) {
8327     // Perform semantic checking on the function declaration.
8328     bool isExplicitSpecialization=false;
8329     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8330       CheckMain(NewFD, D.getDeclSpec());
8331 
8332     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8333       CheckMSVCRTEntryPoint(NewFD);
8334 
8335     if (!NewFD->isInvalidDecl())
8336       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8337                                                   isExplicitSpecialization));
8338     else if (!Previous.empty())
8339       // Recover gracefully from an invalid redeclaration.
8340       D.setRedeclaration(true);
8341     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8342             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8343            "previous declaration set still overloaded");
8344 
8345     // Diagnose no-prototype function declarations with calling conventions that
8346     // don't support variadic calls. Only do this in C and do it after merging
8347     // possibly prototyped redeclarations.
8348     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8349     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8350       CallingConv CC = FT->getExtInfo().getCC();
8351       if (!supportsVariadicCall(CC)) {
8352         // Windows system headers sometimes accidentally use stdcall without
8353         // (void) parameters, so we relax this to a warning.
8354         int DiagID =
8355             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8356         Diag(NewFD->getLocation(), DiagID)
8357             << FunctionType::getNameForCallConv(CC);
8358       }
8359     }
8360   } else {
8361     // C++11 [replacement.functions]p3:
8362     //  The program's definitions shall not be specified as inline.
8363     //
8364     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8365     //
8366     // Suppress the diagnostic if the function is __attribute__((used)), since
8367     // that forces an external definition to be emitted.
8368     if (D.getDeclSpec().isInlineSpecified() &&
8369         NewFD->isReplaceableGlobalAllocationFunction() &&
8370         !NewFD->hasAttr<UsedAttr>())
8371       Diag(D.getDeclSpec().getInlineSpecLoc(),
8372            diag::ext_operator_new_delete_declared_inline)
8373         << NewFD->getDeclName();
8374 
8375     // If the declarator is a template-id, translate the parser's template
8376     // argument list into our AST format.
8377     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8378       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8379       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8380       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8381       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8382                                          TemplateId->NumArgs);
8383       translateTemplateArguments(TemplateArgsPtr,
8384                                  TemplateArgs);
8385 
8386       HasExplicitTemplateArgs = true;
8387 
8388       if (NewFD->isInvalidDecl()) {
8389         HasExplicitTemplateArgs = false;
8390       } else if (FunctionTemplate) {
8391         // Function template with explicit template arguments.
8392         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8393           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8394 
8395         HasExplicitTemplateArgs = false;
8396       } else {
8397         assert((isFunctionTemplateSpecialization ||
8398                 D.getDeclSpec().isFriendSpecified()) &&
8399                "should have a 'template<>' for this decl");
8400         // "friend void foo<>(int);" is an implicit specialization decl.
8401         isFunctionTemplateSpecialization = true;
8402       }
8403     } else if (isFriend && isFunctionTemplateSpecialization) {
8404       // This combination is only possible in a recovery case;  the user
8405       // wrote something like:
8406       //   template <> friend void foo(int);
8407       // which we're recovering from as if the user had written:
8408       //   friend void foo<>(int);
8409       // Go ahead and fake up a template id.
8410       HasExplicitTemplateArgs = true;
8411       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8412       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8413     }
8414 
8415     // We do not add HD attributes to specializations here because
8416     // they may have different constexpr-ness compared to their
8417     // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
8418     // may end up with different effective targets. Instead, a
8419     // specialization inherits its target attributes from its template
8420     // in the CheckFunctionTemplateSpecialization() call below.
8421     if (getLangOpts().CUDA & !isFunctionTemplateSpecialization)
8422       maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
8423 
8424     // If it's a friend (and only if it's a friend), it's possible
8425     // that either the specialized function type or the specialized
8426     // template is dependent, and therefore matching will fail.  In
8427     // this case, don't check the specialization yet.
8428     bool InstantiationDependent = false;
8429     if (isFunctionTemplateSpecialization && isFriend &&
8430         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8431          TemplateSpecializationType::anyDependentTemplateArguments(
8432             TemplateArgs,
8433             InstantiationDependent))) {
8434       assert(HasExplicitTemplateArgs &&
8435              "friend function specialization without template args");
8436       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8437                                                        Previous))
8438         NewFD->setInvalidDecl();
8439     } else if (isFunctionTemplateSpecialization) {
8440       if (CurContext->isDependentContext() && CurContext->isRecord()
8441           && !isFriend) {
8442         isDependentClassScopeExplicitSpecialization = true;
8443         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8444           diag::ext_function_specialization_in_class :
8445           diag::err_function_specialization_in_class)
8446           << NewFD->getDeclName();
8447       } else if (CheckFunctionTemplateSpecialization(NewFD,
8448                                   (HasExplicitTemplateArgs ? &TemplateArgs
8449                                                            : nullptr),
8450                                                      Previous))
8451         NewFD->setInvalidDecl();
8452 
8453       // C++ [dcl.stc]p1:
8454       //   A storage-class-specifier shall not be specified in an explicit
8455       //   specialization (14.7.3)
8456       FunctionTemplateSpecializationInfo *Info =
8457           NewFD->getTemplateSpecializationInfo();
8458       if (Info && SC != SC_None) {
8459         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8460           Diag(NewFD->getLocation(),
8461                diag::err_explicit_specialization_inconsistent_storage_class)
8462             << SC
8463             << FixItHint::CreateRemoval(
8464                                       D.getDeclSpec().getStorageClassSpecLoc());
8465 
8466         else
8467           Diag(NewFD->getLocation(),
8468                diag::ext_explicit_specialization_storage_class)
8469             << FixItHint::CreateRemoval(
8470                                       D.getDeclSpec().getStorageClassSpecLoc());
8471       }
8472     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
8473       if (CheckMemberSpecialization(NewFD, Previous))
8474           NewFD->setInvalidDecl();
8475     }
8476 
8477     // Perform semantic checking on the function declaration.
8478     if (!isDependentClassScopeExplicitSpecialization) {
8479       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8480         CheckMain(NewFD, D.getDeclSpec());
8481 
8482       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8483         CheckMSVCRTEntryPoint(NewFD);
8484 
8485       if (!NewFD->isInvalidDecl())
8486         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8487                                                     isExplicitSpecialization));
8488       else if (!Previous.empty())
8489         // Recover gracefully from an invalid redeclaration.
8490         D.setRedeclaration(true);
8491     }
8492 
8493     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8494             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8495            "previous declaration set still overloaded");
8496 
8497     NamedDecl *PrincipalDecl = (FunctionTemplate
8498                                 ? cast<NamedDecl>(FunctionTemplate)
8499                                 : NewFD);
8500 
8501     if (isFriend && NewFD->getPreviousDecl()) {
8502       AccessSpecifier Access = AS_public;
8503       if (!NewFD->isInvalidDecl())
8504         Access = NewFD->getPreviousDecl()->getAccess();
8505 
8506       NewFD->setAccess(Access);
8507       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8508     }
8509 
8510     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8511         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8512       PrincipalDecl->setNonMemberOperator();
8513 
8514     // If we have a function template, check the template parameter
8515     // list. This will check and merge default template arguments.
8516     if (FunctionTemplate) {
8517       FunctionTemplateDecl *PrevTemplate =
8518                                      FunctionTemplate->getPreviousDecl();
8519       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8520                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8521                                     : nullptr,
8522                             D.getDeclSpec().isFriendSpecified()
8523                               ? (D.isFunctionDefinition()
8524                                    ? TPC_FriendFunctionTemplateDefinition
8525                                    : TPC_FriendFunctionTemplate)
8526                               : (D.getCXXScopeSpec().isSet() &&
8527                                  DC && DC->isRecord() &&
8528                                  DC->isDependentContext())
8529                                   ? TPC_ClassTemplateMember
8530                                   : TPC_FunctionTemplate);
8531     }
8532 
8533     if (NewFD->isInvalidDecl()) {
8534       // Ignore all the rest of this.
8535     } else if (!D.isRedeclaration()) {
8536       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8537                                        AddToScope };
8538       // Fake up an access specifier if it's supposed to be a class member.
8539       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8540         NewFD->setAccess(AS_public);
8541 
8542       // Qualified decls generally require a previous declaration.
8543       if (D.getCXXScopeSpec().isSet()) {
8544         // ...with the major exception of templated-scope or
8545         // dependent-scope friend declarations.
8546 
8547         // TODO: we currently also suppress this check in dependent
8548         // contexts because (1) the parameter depth will be off when
8549         // matching friend templates and (2) we might actually be
8550         // selecting a friend based on a dependent factor.  But there
8551         // are situations where these conditions don't apply and we
8552         // can actually do this check immediately.
8553         if (isFriend &&
8554             (TemplateParamLists.size() ||
8555              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8556              CurContext->isDependentContext())) {
8557           // ignore these
8558         } else {
8559           // The user tried to provide an out-of-line definition for a
8560           // function that is a member of a class or namespace, but there
8561           // was no such member function declared (C++ [class.mfct]p2,
8562           // C++ [namespace.memdef]p2). For example:
8563           //
8564           // class X {
8565           //   void f() const;
8566           // };
8567           //
8568           // void X::f() { } // ill-formed
8569           //
8570           // Complain about this problem, and attempt to suggest close
8571           // matches (e.g., those that differ only in cv-qualifiers and
8572           // whether the parameter types are references).
8573 
8574           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8575                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8576             AddToScope = ExtraArgs.AddToScope;
8577             return Result;
8578           }
8579         }
8580 
8581         // Unqualified local friend declarations are required to resolve
8582         // to something.
8583       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8584         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8585                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8586           AddToScope = ExtraArgs.AddToScope;
8587           return Result;
8588         }
8589       }
8590     } else if (!D.isFunctionDefinition() &&
8591                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8592                !isFriend && !isFunctionTemplateSpecialization &&
8593                !isExplicitSpecialization) {
8594       // An out-of-line member function declaration must also be a
8595       // definition (C++ [class.mfct]p2).
8596       // Note that this is not the case for explicit specializations of
8597       // function templates or member functions of class templates, per
8598       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8599       // extension for compatibility with old SWIG code which likes to
8600       // generate them.
8601       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8602         << D.getCXXScopeSpec().getRange();
8603     }
8604   }
8605 
8606   ProcessPragmaWeak(S, NewFD);
8607   checkAttributesAfterMerging(*this, *NewFD);
8608 
8609   AddKnownFunctionAttributes(NewFD);
8610 
8611   if (NewFD->hasAttr<OverloadableAttr>() &&
8612       !NewFD->getType()->getAs<FunctionProtoType>()) {
8613     Diag(NewFD->getLocation(),
8614          diag::err_attribute_overloadable_no_prototype)
8615       << NewFD;
8616 
8617     // Turn this into a variadic function with no parameters.
8618     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8619     FunctionProtoType::ExtProtoInfo EPI(
8620         Context.getDefaultCallingConvention(true, false));
8621     EPI.Variadic = true;
8622     EPI.ExtInfo = FT->getExtInfo();
8623 
8624     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8625     NewFD->setType(R);
8626   }
8627 
8628   // If there's a #pragma GCC visibility in scope, and this isn't a class
8629   // member, set the visibility of this function.
8630   if (!DC->isRecord() && NewFD->isExternallyVisible())
8631     AddPushedVisibilityAttribute(NewFD);
8632 
8633   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8634   // marking the function.
8635   AddCFAuditedAttribute(NewFD);
8636 
8637   // If this is a function definition, check if we have to apply optnone due to
8638   // a pragma.
8639   if(D.isFunctionDefinition())
8640     AddRangeBasedOptnone(NewFD);
8641 
8642   // If this is the first declaration of an extern C variable, update
8643   // the map of such variables.
8644   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8645       isIncompleteDeclExternC(*this, NewFD))
8646     RegisterLocallyScopedExternCDecl(NewFD, S);
8647 
8648   // Set this FunctionDecl's range up to the right paren.
8649   NewFD->setRangeEnd(D.getSourceRange().getEnd());
8650 
8651   if (D.isRedeclaration() && !Previous.empty()) {
8652     checkDLLAttributeRedeclaration(
8653         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8654         isExplicitSpecialization || isFunctionTemplateSpecialization,
8655         D.isFunctionDefinition());
8656   }
8657 
8658   if (getLangOpts().CUDA) {
8659     IdentifierInfo *II = NewFD->getIdentifier();
8660     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
8661         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8662       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8663         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8664 
8665       Context.setcudaConfigureCallDecl(NewFD);
8666     }
8667 
8668     // Variadic functions, other than a *declaration* of printf, are not allowed
8669     // in device-side CUDA code, unless someone passed
8670     // -fcuda-allow-variadic-functions.
8671     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
8672         (NewFD->hasAttr<CUDADeviceAttr>() ||
8673          NewFD->hasAttr<CUDAGlobalAttr>()) &&
8674         !(II && II->isStr("printf") && NewFD->isExternC() &&
8675           !D.isFunctionDefinition())) {
8676       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
8677     }
8678   }
8679 
8680   if (getLangOpts().CPlusPlus) {
8681     if (FunctionTemplate) {
8682       if (NewFD->isInvalidDecl())
8683         FunctionTemplate->setInvalidDecl();
8684       return FunctionTemplate;
8685     }
8686   }
8687 
8688   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8689     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8690     if ((getLangOpts().OpenCLVersion >= 120)
8691         && (SC == SC_Static)) {
8692       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8693       D.setInvalidType();
8694     }
8695 
8696     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8697     if (!NewFD->getReturnType()->isVoidType()) {
8698       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8699       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8700           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8701                                 : FixItHint());
8702       D.setInvalidType();
8703     }
8704 
8705     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8706     for (auto Param : NewFD->parameters())
8707       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8708   }
8709   for (const ParmVarDecl *Param : NewFD->parameters()) {
8710     QualType PT = Param->getType();
8711 
8712     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8713     // types.
8714     if (getLangOpts().OpenCLVersion >= 200) {
8715       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8716         QualType ElemTy = PipeTy->getElementType();
8717           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8718             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8719             D.setInvalidType();
8720           }
8721       }
8722     }
8723   }
8724 
8725   MarkUnusedFileScopedDecl(NewFD);
8726 
8727   // Here we have an function template explicit specialization at class scope.
8728   // The actually specialization will be postponed to template instatiation
8729   // time via the ClassScopeFunctionSpecializationDecl node.
8730   if (isDependentClassScopeExplicitSpecialization) {
8731     ClassScopeFunctionSpecializationDecl *NewSpec =
8732                          ClassScopeFunctionSpecializationDecl::Create(
8733                                 Context, CurContext, SourceLocation(),
8734                                 cast<CXXMethodDecl>(NewFD),
8735                                 HasExplicitTemplateArgs, TemplateArgs);
8736     CurContext->addDecl(NewSpec);
8737     AddToScope = false;
8738   }
8739 
8740   return NewFD;
8741 }
8742 
8743 /// \brief Checks if the new declaration declared in dependent context must be
8744 /// put in the same redeclaration chain as the specified declaration.
8745 ///
8746 /// \param D Declaration that is checked.
8747 /// \param PrevDecl Previous declaration found with proper lookup method for the
8748 ///                 same declaration name.
8749 /// \returns True if D must be added to the redeclaration chain which PrevDecl
8750 ///          belongs to.
8751 ///
8752 bool Sema::shouldLinkDependentDeclWithPrevious(Decl *D, Decl *PrevDecl) {
8753   // Any declarations should be put into redeclaration chains except for
8754   // friend declaration in a dependent context that names a function in
8755   // namespace scope.
8756   //
8757   // This allows to compile code like:
8758   //
8759   //       void func();
8760   //       template<typename T> class C1 { friend void func() { } };
8761   //       template<typename T> class C2 { friend void func() { } };
8762   //
8763   // This code snippet is a valid code unless both templates are instantiated.
8764   return !(D->getLexicalDeclContext()->isDependentContext() &&
8765            D->getDeclContext()->isFileContext() &&
8766            D->getFriendObjectKind() != Decl::FOK_None);
8767 }
8768 
8769 /// \brief Perform semantic checking of a new function declaration.
8770 ///
8771 /// Performs semantic analysis of the new function declaration
8772 /// NewFD. This routine performs all semantic checking that does not
8773 /// require the actual declarator involved in the declaration, and is
8774 /// used both for the declaration of functions as they are parsed
8775 /// (called via ActOnDeclarator) and for the declaration of functions
8776 /// that have been instantiated via C++ template instantiation (called
8777 /// via InstantiateDecl).
8778 ///
8779 /// \param IsExplicitSpecialization whether this new function declaration is
8780 /// an explicit specialization of the previous declaration.
8781 ///
8782 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8783 ///
8784 /// \returns true if the function declaration is a redeclaration.
8785 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8786                                     LookupResult &Previous,
8787                                     bool IsExplicitSpecialization) {
8788   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8789          "Variably modified return types are not handled here");
8790 
8791   // Determine whether the type of this function should be merged with
8792   // a previous visible declaration. This never happens for functions in C++,
8793   // and always happens in C if the previous declaration was visible.
8794   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8795                                !Previous.isShadowed();
8796 
8797   bool Redeclaration = false;
8798   NamedDecl *OldDecl = nullptr;
8799 
8800   // Merge or overload the declaration with an existing declaration of
8801   // the same name, if appropriate.
8802   if (!Previous.empty()) {
8803     // Determine whether NewFD is an overload of PrevDecl or
8804     // a declaration that requires merging. If it's an overload,
8805     // there's no more work to do here; we'll just add the new
8806     // function to the scope.
8807     if (!AllowOverloadingOfFunction(Previous, Context)) {
8808       NamedDecl *Candidate = Previous.getRepresentativeDecl();
8809       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8810         Redeclaration = true;
8811         OldDecl = Candidate;
8812       }
8813     } else {
8814       switch (CheckOverload(S, NewFD, Previous, OldDecl,
8815                             /*NewIsUsingDecl*/ false)) {
8816       case Ovl_Match:
8817         Redeclaration = true;
8818         break;
8819 
8820       case Ovl_NonFunction:
8821         Redeclaration = true;
8822         break;
8823 
8824       case Ovl_Overload:
8825         Redeclaration = false;
8826         break;
8827       }
8828 
8829       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8830         // If a function name is overloadable in C, then every function
8831         // with that name must be marked "overloadable".
8832         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8833           << Redeclaration << NewFD;
8834         NamedDecl *OverloadedDecl = nullptr;
8835         if (Redeclaration)
8836           OverloadedDecl = OldDecl;
8837         else if (!Previous.empty())
8838           OverloadedDecl = Previous.getRepresentativeDecl();
8839         if (OverloadedDecl)
8840           Diag(OverloadedDecl->getLocation(),
8841                diag::note_attribute_overloadable_prev_overload);
8842         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8843       }
8844     }
8845   }
8846 
8847   // Check for a previous extern "C" declaration with this name.
8848   if (!Redeclaration &&
8849       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8850     if (!Previous.empty()) {
8851       // This is an extern "C" declaration with the same name as a previous
8852       // declaration, and thus redeclares that entity...
8853       Redeclaration = true;
8854       OldDecl = Previous.getFoundDecl();
8855       MergeTypeWithPrevious = false;
8856 
8857       // ... except in the presence of __attribute__((overloadable)).
8858       if (OldDecl->hasAttr<OverloadableAttr>()) {
8859         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8860           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8861             << Redeclaration << NewFD;
8862           Diag(Previous.getFoundDecl()->getLocation(),
8863                diag::note_attribute_overloadable_prev_overload);
8864           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8865         }
8866         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8867           Redeclaration = false;
8868           OldDecl = nullptr;
8869         }
8870       }
8871     }
8872   }
8873 
8874   // C++11 [dcl.constexpr]p8:
8875   //   A constexpr specifier for a non-static member function that is not
8876   //   a constructor declares that member function to be const.
8877   //
8878   // This needs to be delayed until we know whether this is an out-of-line
8879   // definition of a static member function.
8880   //
8881   // This rule is not present in C++1y, so we produce a backwards
8882   // compatibility warning whenever it happens in C++11.
8883   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8884   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8885       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8886       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8887     CXXMethodDecl *OldMD = nullptr;
8888     if (OldDecl)
8889       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8890     if (!OldMD || !OldMD->isStatic()) {
8891       const FunctionProtoType *FPT =
8892         MD->getType()->castAs<FunctionProtoType>();
8893       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8894       EPI.TypeQuals |= Qualifiers::Const;
8895       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8896                                           FPT->getParamTypes(), EPI));
8897 
8898       // Warn that we did this, if we're not performing template instantiation.
8899       // In that case, we'll have warned already when the template was defined.
8900       if (ActiveTemplateInstantiations.empty()) {
8901         SourceLocation AddConstLoc;
8902         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
8903                 .IgnoreParens().getAs<FunctionTypeLoc>())
8904           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
8905 
8906         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
8907           << FixItHint::CreateInsertion(AddConstLoc, " const");
8908       }
8909     }
8910   }
8911 
8912   if (Redeclaration) {
8913     // NewFD and OldDecl represent declarations that need to be
8914     // merged.
8915     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
8916       NewFD->setInvalidDecl();
8917       return Redeclaration;
8918     }
8919 
8920     Previous.clear();
8921     Previous.addDecl(OldDecl);
8922 
8923     if (FunctionTemplateDecl *OldTemplateDecl
8924                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
8925       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
8926       FunctionTemplateDecl *NewTemplateDecl
8927         = NewFD->getDescribedFunctionTemplate();
8928       assert(NewTemplateDecl && "Template/non-template mismatch");
8929       if (CXXMethodDecl *Method
8930             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
8931         Method->setAccess(OldTemplateDecl->getAccess());
8932         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8933       }
8934 
8935       // If this is an explicit specialization of a member that is a function
8936       // template, mark it as a member specialization.
8937       if (IsExplicitSpecialization &&
8938           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
8939         NewTemplateDecl->setMemberSpecialization();
8940         assert(OldTemplateDecl->isMemberSpecialization());
8941         // Explicit specializations of a member template do not inherit deleted
8942         // status from the parent member template that they are specializing.
8943         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
8944           FunctionDecl *const OldTemplatedDecl =
8945               OldTemplateDecl->getTemplatedDecl();
8946           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
8947           OldTemplatedDecl->setDeletedAsWritten(false);
8948         }
8949       }
8950 
8951     } else {
8952       if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
8953         // This needs to happen first so that 'inline' propagates.
8954         NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
8955         if (isa<CXXMethodDecl>(NewFD))
8956           NewFD->setAccess(OldDecl->getAccess());
8957       }
8958     }
8959   }
8960 
8961   // Semantic checking for this function declaration (in isolation).
8962 
8963   if (getLangOpts().CPlusPlus) {
8964     // C++-specific checks.
8965     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
8966       CheckConstructor(Constructor);
8967     } else if (CXXDestructorDecl *Destructor =
8968                 dyn_cast<CXXDestructorDecl>(NewFD)) {
8969       CXXRecordDecl *Record = Destructor->getParent();
8970       QualType ClassType = Context.getTypeDeclType(Record);
8971 
8972       // FIXME: Shouldn't we be able to perform this check even when the class
8973       // type is dependent? Both gcc and edg can handle that.
8974       if (!ClassType->isDependentType()) {
8975         DeclarationName Name
8976           = Context.DeclarationNames.getCXXDestructorName(
8977                                         Context.getCanonicalType(ClassType));
8978         if (NewFD->getDeclName() != Name) {
8979           Diag(NewFD->getLocation(), diag::err_destructor_name);
8980           NewFD->setInvalidDecl();
8981           return Redeclaration;
8982         }
8983       }
8984     } else if (CXXConversionDecl *Conversion
8985                = dyn_cast<CXXConversionDecl>(NewFD)) {
8986       ActOnConversionDeclarator(Conversion);
8987     }
8988 
8989     // Find any virtual functions that this function overrides.
8990     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8991       if (!Method->isFunctionTemplateSpecialization() &&
8992           !Method->getDescribedFunctionTemplate() &&
8993           Method->isCanonicalDecl()) {
8994         if (AddOverriddenMethods(Method->getParent(), Method)) {
8995           // If the function was marked as "static", we have a problem.
8996           if (NewFD->getStorageClass() == SC_Static) {
8997             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8998           }
8999         }
9000       }
9001 
9002       if (Method->isStatic())
9003         checkThisInStaticMemberFunctionType(Method);
9004     }
9005 
9006     // Extra checking for C++ overloaded operators (C++ [over.oper]).
9007     if (NewFD->isOverloadedOperator() &&
9008         CheckOverloadedOperatorDeclaration(NewFD)) {
9009       NewFD->setInvalidDecl();
9010       return Redeclaration;
9011     }
9012 
9013     // Extra checking for C++0x literal operators (C++0x [over.literal]).
9014     if (NewFD->getLiteralIdentifier() &&
9015         CheckLiteralOperatorDeclaration(NewFD)) {
9016       NewFD->setInvalidDecl();
9017       return Redeclaration;
9018     }
9019 
9020     // In C++, check default arguments now that we have merged decls. Unless
9021     // the lexical context is the class, because in this case this is done
9022     // during delayed parsing anyway.
9023     if (!CurContext->isRecord())
9024       CheckCXXDefaultArguments(NewFD);
9025 
9026     // If this function declares a builtin function, check the type of this
9027     // declaration against the expected type for the builtin.
9028     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
9029       ASTContext::GetBuiltinTypeError Error;
9030       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
9031       QualType T = Context.GetBuiltinType(BuiltinID, Error);
9032       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
9033         auto WithoutExceptionSpec = [&](QualType T) -> QualType {
9034           auto *Proto = T->getAs<FunctionProtoType>();
9035           if (!Proto)
9036             return T;
9037           return Context.getFunctionType(
9038               Proto->getReturnType(), Proto->getParamTypes(),
9039               Proto->getExtProtoInfo().withExceptionSpec(EST_None));
9040         };
9041 
9042         // If the type of the builtin differs only in its exception
9043         // specification, that's OK.
9044         // FIXME: If the types do differ in this way, it would be better to
9045         // retain the 'noexcept' form of the type.
9046         if (!getLangOpts().CPlusPlus1z ||
9047             !Context.hasSameType(WithoutExceptionSpec(T),
9048                                  WithoutExceptionSpec(NewFD->getType())))
9049           // The type of this function differs from the type of the builtin,
9050           // so forget about the builtin entirely.
9051           Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
9052       }
9053     }
9054 
9055     // If this function is declared as being extern "C", then check to see if
9056     // the function returns a UDT (class, struct, or union type) that is not C
9057     // compatible, and if it does, warn the user.
9058     // But, issue any diagnostic on the first declaration only.
9059     if (Previous.empty() && NewFD->isExternC()) {
9060       QualType R = NewFD->getReturnType();
9061       if (R->isIncompleteType() && !R->isVoidType())
9062         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
9063             << NewFD << R;
9064       else if (!R.isPODType(Context) && !R->isVoidType() &&
9065                !R->isObjCObjectPointerType())
9066         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
9067     }
9068 
9069     // C++1z [dcl.fct]p6:
9070     //   [...] whether the function has a non-throwing exception-specification
9071     //   [is] part of the function type
9072     //
9073     // This results in an ABI break between C++14 and C++17 for functions whose
9074     // declared type includes an exception-specification in a parameter or
9075     // return type. (Exception specifications on the function itself are OK in
9076     // most cases, and exception specifications are not permitted in most other
9077     // contexts where they could make it into a mangling.)
9078     if (!getLangOpts().CPlusPlus1z && !NewFD->getPrimaryTemplate()) {
9079       auto HasNoexcept = [&](QualType T) -> bool {
9080         // Strip off declarator chunks that could be between us and a function
9081         // type. We don't need to look far, exception specifications are very
9082         // restricted prior to C++17.
9083         if (auto *RT = T->getAs<ReferenceType>())
9084           T = RT->getPointeeType();
9085         else if (T->isAnyPointerType())
9086           T = T->getPointeeType();
9087         else if (auto *MPT = T->getAs<MemberPointerType>())
9088           T = MPT->getPointeeType();
9089         if (auto *FPT = T->getAs<FunctionProtoType>())
9090           if (FPT->isNothrow(Context))
9091             return true;
9092         return false;
9093       };
9094 
9095       auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
9096       bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
9097       for (QualType T : FPT->param_types())
9098         AnyNoexcept |= HasNoexcept(T);
9099       if (AnyNoexcept)
9100         Diag(NewFD->getLocation(),
9101              diag::warn_cxx1z_compat_exception_spec_in_signature)
9102             << NewFD;
9103     }
9104 
9105     if (!Redeclaration && LangOpts.CUDA)
9106       checkCUDATargetOverload(NewFD, Previous);
9107   }
9108   return Redeclaration;
9109 }
9110 
9111 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
9112   // C++11 [basic.start.main]p3:
9113   //   A program that [...] declares main to be inline, static or
9114   //   constexpr is ill-formed.
9115   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
9116   //   appear in a declaration of main.
9117   // static main is not an error under C99, but we should warn about it.
9118   // We accept _Noreturn main as an extension.
9119   if (FD->getStorageClass() == SC_Static)
9120     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
9121          ? diag::err_static_main : diag::warn_static_main)
9122       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
9123   if (FD->isInlineSpecified())
9124     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
9125       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
9126   if (DS.isNoreturnSpecified()) {
9127     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
9128     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
9129     Diag(NoreturnLoc, diag::ext_noreturn_main);
9130     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
9131       << FixItHint::CreateRemoval(NoreturnRange);
9132   }
9133   if (FD->isConstexpr()) {
9134     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
9135       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
9136     FD->setConstexpr(false);
9137   }
9138 
9139   if (getLangOpts().OpenCL) {
9140     Diag(FD->getLocation(), diag::err_opencl_no_main)
9141         << FD->hasAttr<OpenCLKernelAttr>();
9142     FD->setInvalidDecl();
9143     return;
9144   }
9145 
9146   QualType T = FD->getType();
9147   assert(T->isFunctionType() && "function decl is not of function type");
9148   const FunctionType* FT = T->castAs<FunctionType>();
9149 
9150   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
9151     // In C with GNU extensions we allow main() to have non-integer return
9152     // type, but we should warn about the extension, and we disable the
9153     // implicit-return-zero rule.
9154 
9155     // GCC in C mode accepts qualified 'int'.
9156     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
9157       FD->setHasImplicitReturnZero(true);
9158     else {
9159       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
9160       SourceRange RTRange = FD->getReturnTypeSourceRange();
9161       if (RTRange.isValid())
9162         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
9163             << FixItHint::CreateReplacement(RTRange, "int");
9164     }
9165   } else {
9166     // In C and C++, main magically returns 0 if you fall off the end;
9167     // set the flag which tells us that.
9168     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
9169 
9170     // All the standards say that main() should return 'int'.
9171     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
9172       FD->setHasImplicitReturnZero(true);
9173     else {
9174       // Otherwise, this is just a flat-out error.
9175       SourceRange RTRange = FD->getReturnTypeSourceRange();
9176       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
9177           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
9178                                 : FixItHint());
9179       FD->setInvalidDecl(true);
9180     }
9181   }
9182 
9183   // Treat protoless main() as nullary.
9184   if (isa<FunctionNoProtoType>(FT)) return;
9185 
9186   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
9187   unsigned nparams = FTP->getNumParams();
9188   assert(FD->getNumParams() == nparams);
9189 
9190   bool HasExtraParameters = (nparams > 3);
9191 
9192   if (FTP->isVariadic()) {
9193     Diag(FD->getLocation(), diag::ext_variadic_main);
9194     // FIXME: if we had information about the location of the ellipsis, we
9195     // could add a FixIt hint to remove it as a parameter.
9196   }
9197 
9198   // Darwin passes an undocumented fourth argument of type char**.  If
9199   // other platforms start sprouting these, the logic below will start
9200   // getting shifty.
9201   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
9202     HasExtraParameters = false;
9203 
9204   if (HasExtraParameters) {
9205     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
9206     FD->setInvalidDecl(true);
9207     nparams = 3;
9208   }
9209 
9210   // FIXME: a lot of the following diagnostics would be improved
9211   // if we had some location information about types.
9212 
9213   QualType CharPP =
9214     Context.getPointerType(Context.getPointerType(Context.CharTy));
9215   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
9216 
9217   for (unsigned i = 0; i < nparams; ++i) {
9218     QualType AT = FTP->getParamType(i);
9219 
9220     bool mismatch = true;
9221 
9222     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
9223       mismatch = false;
9224     else if (Expected[i] == CharPP) {
9225       // As an extension, the following forms are okay:
9226       //   char const **
9227       //   char const * const *
9228       //   char * const *
9229 
9230       QualifierCollector qs;
9231       const PointerType* PT;
9232       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
9233           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
9234           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
9235                               Context.CharTy)) {
9236         qs.removeConst();
9237         mismatch = !qs.empty();
9238       }
9239     }
9240 
9241     if (mismatch) {
9242       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
9243       // TODO: suggest replacing given type with expected type
9244       FD->setInvalidDecl(true);
9245     }
9246   }
9247 
9248   if (nparams == 1 && !FD->isInvalidDecl()) {
9249     Diag(FD->getLocation(), diag::warn_main_one_arg);
9250   }
9251 
9252   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9253     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9254     FD->setInvalidDecl();
9255   }
9256 }
9257 
9258 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9259   QualType T = FD->getType();
9260   assert(T->isFunctionType() && "function decl is not of function type");
9261   const FunctionType *FT = T->castAs<FunctionType>();
9262 
9263   // Set an implicit return of 'zero' if the function can return some integral,
9264   // enumeration, pointer or nullptr type.
9265   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9266       FT->getReturnType()->isAnyPointerType() ||
9267       FT->getReturnType()->isNullPtrType())
9268     // DllMain is exempt because a return value of zero means it failed.
9269     if (FD->getName() != "DllMain")
9270       FD->setHasImplicitReturnZero(true);
9271 
9272   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9273     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9274     FD->setInvalidDecl();
9275   }
9276 }
9277 
9278 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9279   // FIXME: Need strict checking.  In C89, we need to check for
9280   // any assignment, increment, decrement, function-calls, or
9281   // commas outside of a sizeof.  In C99, it's the same list,
9282   // except that the aforementioned are allowed in unevaluated
9283   // expressions.  Everything else falls under the
9284   // "may accept other forms of constant expressions" exception.
9285   // (We never end up here for C++, so the constant expression
9286   // rules there don't matter.)
9287   const Expr *Culprit;
9288   if (Init->isConstantInitializer(Context, false, &Culprit))
9289     return false;
9290   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9291     << Culprit->getSourceRange();
9292   return true;
9293 }
9294 
9295 namespace {
9296   // Visits an initialization expression to see if OrigDecl is evaluated in
9297   // its own initialization and throws a warning if it does.
9298   class SelfReferenceChecker
9299       : public EvaluatedExprVisitor<SelfReferenceChecker> {
9300     Sema &S;
9301     Decl *OrigDecl;
9302     bool isRecordType;
9303     bool isPODType;
9304     bool isReferenceType;
9305 
9306     bool isInitList;
9307     llvm::SmallVector<unsigned, 4> InitFieldIndex;
9308 
9309   public:
9310     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9311 
9312     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9313                                                     S(S), OrigDecl(OrigDecl) {
9314       isPODType = false;
9315       isRecordType = false;
9316       isReferenceType = false;
9317       isInitList = false;
9318       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9319         isPODType = VD->getType().isPODType(S.Context);
9320         isRecordType = VD->getType()->isRecordType();
9321         isReferenceType = VD->getType()->isReferenceType();
9322       }
9323     }
9324 
9325     // For most expressions, just call the visitor.  For initializer lists,
9326     // track the index of the field being initialized since fields are
9327     // initialized in order allowing use of previously initialized fields.
9328     void CheckExpr(Expr *E) {
9329       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9330       if (!InitList) {
9331         Visit(E);
9332         return;
9333       }
9334 
9335       // Track and increment the index here.
9336       isInitList = true;
9337       InitFieldIndex.push_back(0);
9338       for (auto Child : InitList->children()) {
9339         CheckExpr(cast<Expr>(Child));
9340         ++InitFieldIndex.back();
9341       }
9342       InitFieldIndex.pop_back();
9343     }
9344 
9345     // Returns true if MemberExpr is checked and no futher checking is needed.
9346     // Returns false if additional checking is required.
9347     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9348       llvm::SmallVector<FieldDecl*, 4> Fields;
9349       Expr *Base = E;
9350       bool ReferenceField = false;
9351 
9352       // Get the field memebers used.
9353       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9354         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9355         if (!FD)
9356           return false;
9357         Fields.push_back(FD);
9358         if (FD->getType()->isReferenceType())
9359           ReferenceField = true;
9360         Base = ME->getBase()->IgnoreParenImpCasts();
9361       }
9362 
9363       // Keep checking only if the base Decl is the same.
9364       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9365       if (!DRE || DRE->getDecl() != OrigDecl)
9366         return false;
9367 
9368       // A reference field can be bound to an unininitialized field.
9369       if (CheckReference && !ReferenceField)
9370         return true;
9371 
9372       // Convert FieldDecls to their index number.
9373       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9374       for (const FieldDecl *I : llvm::reverse(Fields))
9375         UsedFieldIndex.push_back(I->getFieldIndex());
9376 
9377       // See if a warning is needed by checking the first difference in index
9378       // numbers.  If field being used has index less than the field being
9379       // initialized, then the use is safe.
9380       for (auto UsedIter = UsedFieldIndex.begin(),
9381                 UsedEnd = UsedFieldIndex.end(),
9382                 OrigIter = InitFieldIndex.begin(),
9383                 OrigEnd = InitFieldIndex.end();
9384            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9385         if (*UsedIter < *OrigIter)
9386           return true;
9387         if (*UsedIter > *OrigIter)
9388           break;
9389       }
9390 
9391       // TODO: Add a different warning which will print the field names.
9392       HandleDeclRefExpr(DRE);
9393       return true;
9394     }
9395 
9396     // For most expressions, the cast is directly above the DeclRefExpr.
9397     // For conditional operators, the cast can be outside the conditional
9398     // operator if both expressions are DeclRefExpr's.
9399     void HandleValue(Expr *E) {
9400       E = E->IgnoreParens();
9401       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9402         HandleDeclRefExpr(DRE);
9403         return;
9404       }
9405 
9406       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9407         Visit(CO->getCond());
9408         HandleValue(CO->getTrueExpr());
9409         HandleValue(CO->getFalseExpr());
9410         return;
9411       }
9412 
9413       if (BinaryConditionalOperator *BCO =
9414               dyn_cast<BinaryConditionalOperator>(E)) {
9415         Visit(BCO->getCond());
9416         HandleValue(BCO->getFalseExpr());
9417         return;
9418       }
9419 
9420       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9421         HandleValue(OVE->getSourceExpr());
9422         return;
9423       }
9424 
9425       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9426         if (BO->getOpcode() == BO_Comma) {
9427           Visit(BO->getLHS());
9428           HandleValue(BO->getRHS());
9429           return;
9430         }
9431       }
9432 
9433       if (isa<MemberExpr>(E)) {
9434         if (isInitList) {
9435           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9436                                       false /*CheckReference*/))
9437             return;
9438         }
9439 
9440         Expr *Base = E->IgnoreParenImpCasts();
9441         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9442           // Check for static member variables and don't warn on them.
9443           if (!isa<FieldDecl>(ME->getMemberDecl()))
9444             return;
9445           Base = ME->getBase()->IgnoreParenImpCasts();
9446         }
9447         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9448           HandleDeclRefExpr(DRE);
9449         return;
9450       }
9451 
9452       Visit(E);
9453     }
9454 
9455     // Reference types not handled in HandleValue are handled here since all
9456     // uses of references are bad, not just r-value uses.
9457     void VisitDeclRefExpr(DeclRefExpr *E) {
9458       if (isReferenceType)
9459         HandleDeclRefExpr(E);
9460     }
9461 
9462     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9463       if (E->getCastKind() == CK_LValueToRValue) {
9464         HandleValue(E->getSubExpr());
9465         return;
9466       }
9467 
9468       Inherited::VisitImplicitCastExpr(E);
9469     }
9470 
9471     void VisitMemberExpr(MemberExpr *E) {
9472       if (isInitList) {
9473         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9474           return;
9475       }
9476 
9477       // Don't warn on arrays since they can be treated as pointers.
9478       if (E->getType()->canDecayToPointerType()) return;
9479 
9480       // Warn when a non-static method call is followed by non-static member
9481       // field accesses, which is followed by a DeclRefExpr.
9482       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9483       bool Warn = (MD && !MD->isStatic());
9484       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9485       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9486         if (!isa<FieldDecl>(ME->getMemberDecl()))
9487           Warn = false;
9488         Base = ME->getBase()->IgnoreParenImpCasts();
9489       }
9490 
9491       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9492         if (Warn)
9493           HandleDeclRefExpr(DRE);
9494         return;
9495       }
9496 
9497       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9498       // Visit that expression.
9499       Visit(Base);
9500     }
9501 
9502     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9503       Expr *Callee = E->getCallee();
9504 
9505       if (isa<UnresolvedLookupExpr>(Callee))
9506         return Inherited::VisitCXXOperatorCallExpr(E);
9507 
9508       Visit(Callee);
9509       for (auto Arg: E->arguments())
9510         HandleValue(Arg->IgnoreParenImpCasts());
9511     }
9512 
9513     void VisitUnaryOperator(UnaryOperator *E) {
9514       // For POD record types, addresses of its own members are well-defined.
9515       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9516           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9517         if (!isPODType)
9518           HandleValue(E->getSubExpr());
9519         return;
9520       }
9521 
9522       if (E->isIncrementDecrementOp()) {
9523         HandleValue(E->getSubExpr());
9524         return;
9525       }
9526 
9527       Inherited::VisitUnaryOperator(E);
9528     }
9529 
9530     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9531 
9532     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9533       if (E->getConstructor()->isCopyConstructor()) {
9534         Expr *ArgExpr = E->getArg(0);
9535         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9536           if (ILE->getNumInits() == 1)
9537             ArgExpr = ILE->getInit(0);
9538         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9539           if (ICE->getCastKind() == CK_NoOp)
9540             ArgExpr = ICE->getSubExpr();
9541         HandleValue(ArgExpr);
9542         return;
9543       }
9544       Inherited::VisitCXXConstructExpr(E);
9545     }
9546 
9547     void VisitCallExpr(CallExpr *E) {
9548       // Treat std::move as a use.
9549       if (E->getNumArgs() == 1) {
9550         if (FunctionDecl *FD = E->getDirectCallee()) {
9551           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9552               FD->getIdentifier()->isStr("move")) {
9553             HandleValue(E->getArg(0));
9554             return;
9555           }
9556         }
9557       }
9558 
9559       Inherited::VisitCallExpr(E);
9560     }
9561 
9562     void VisitBinaryOperator(BinaryOperator *E) {
9563       if (E->isCompoundAssignmentOp()) {
9564         HandleValue(E->getLHS());
9565         Visit(E->getRHS());
9566         return;
9567       }
9568 
9569       Inherited::VisitBinaryOperator(E);
9570     }
9571 
9572     // A custom visitor for BinaryConditionalOperator is needed because the
9573     // regular visitor would check the condition and true expression separately
9574     // but both point to the same place giving duplicate diagnostics.
9575     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9576       Visit(E->getCond());
9577       Visit(E->getFalseExpr());
9578     }
9579 
9580     void HandleDeclRefExpr(DeclRefExpr *DRE) {
9581       Decl* ReferenceDecl = DRE->getDecl();
9582       if (OrigDecl != ReferenceDecl) return;
9583       unsigned diag;
9584       if (isReferenceType) {
9585         diag = diag::warn_uninit_self_reference_in_reference_init;
9586       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9587         diag = diag::warn_static_self_reference_in_init;
9588       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9589                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9590                  DRE->getDecl()->getType()->isRecordType()) {
9591         diag = diag::warn_uninit_self_reference_in_init;
9592       } else {
9593         // Local variables will be handled by the CFG analysis.
9594         return;
9595       }
9596 
9597       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9598                             S.PDiag(diag)
9599                               << DRE->getNameInfo().getName()
9600                               << OrigDecl->getLocation()
9601                               << DRE->getSourceRange());
9602     }
9603   };
9604 
9605   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9606   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9607                                  bool DirectInit) {
9608     // Parameters arguments are occassionially constructed with itself,
9609     // for instance, in recursive functions.  Skip them.
9610     if (isa<ParmVarDecl>(OrigDecl))
9611       return;
9612 
9613     E = E->IgnoreParens();
9614 
9615     // Skip checking T a = a where T is not a record or reference type.
9616     // Doing so is a way to silence uninitialized warnings.
9617     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9618       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9619         if (ICE->getCastKind() == CK_LValueToRValue)
9620           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9621             if (DRE->getDecl() == OrigDecl)
9622               return;
9623 
9624     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9625   }
9626 } // end anonymous namespace
9627 
9628 namespace {
9629   // Simple wrapper to add the name of a variable or (if no variable is
9630   // available) a DeclarationName into a diagnostic.
9631   struct VarDeclOrName {
9632     VarDecl *VDecl;
9633     DeclarationName Name;
9634 
9635     friend const Sema::SemaDiagnosticBuilder &
9636     operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
9637       return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
9638     }
9639   };
9640 } // end anonymous namespace
9641 
9642 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9643                                             DeclarationName Name, QualType Type,
9644                                             TypeSourceInfo *TSI,
9645                                             SourceRange Range, bool DirectInit,
9646                                             Expr *Init) {
9647   bool IsInitCapture = !VDecl;
9648   assert((!VDecl || !VDecl->isInitCapture()) &&
9649          "init captures are expected to be deduced prior to initialization");
9650 
9651   VarDeclOrName VN{VDecl, Name};
9652 
9653   // FIXME: Deduction for a decomposition declaration does weird things if the
9654   // initializer is an array.
9655 
9656   ArrayRef<Expr *> DeduceInits = Init;
9657   if (DirectInit) {
9658     if (auto *PL = dyn_cast<ParenListExpr>(Init))
9659       DeduceInits = PL->exprs();
9660     else if (auto *IL = dyn_cast<InitListExpr>(Init))
9661       DeduceInits = IL->inits();
9662   }
9663 
9664   // Deduction only works if we have exactly one source expression.
9665   if (DeduceInits.empty()) {
9666     // It isn't possible to write this directly, but it is possible to
9667     // end up in this situation with "auto x(some_pack...);"
9668     Diag(Init->getLocStart(), IsInitCapture
9669                                   ? diag::err_init_capture_no_expression
9670                                   : diag::err_auto_var_init_no_expression)
9671         << VN << Type << Range;
9672     return QualType();
9673   }
9674 
9675   if (DeduceInits.size() > 1) {
9676     Diag(DeduceInits[1]->getLocStart(),
9677          IsInitCapture ? diag::err_init_capture_multiple_expressions
9678                        : diag::err_auto_var_init_multiple_expressions)
9679         << VN << Type << Range;
9680     return QualType();
9681   }
9682 
9683   Expr *DeduceInit = DeduceInits[0];
9684   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9685     Diag(Init->getLocStart(), IsInitCapture
9686                                   ? diag::err_init_capture_paren_braces
9687                                   : diag::err_auto_var_init_paren_braces)
9688         << isa<InitListExpr>(Init) << VN << Type << Range;
9689     return QualType();
9690   }
9691 
9692   // Expressions default to 'id' when we're in a debugger.
9693   bool DefaultedAnyToId = false;
9694   if (getLangOpts().DebuggerCastResultToId &&
9695       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9696     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9697     if (Result.isInvalid()) {
9698       return QualType();
9699     }
9700     Init = Result.get();
9701     DefaultedAnyToId = true;
9702   }
9703 
9704   QualType DeducedType;
9705   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9706     if (!IsInitCapture)
9707       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9708     else if (isa<InitListExpr>(Init))
9709       Diag(Range.getBegin(),
9710            diag::err_init_capture_deduction_failure_from_init_list)
9711           << VN
9712           << (DeduceInit->getType().isNull() ? TSI->getType()
9713                                              : DeduceInit->getType())
9714           << DeduceInit->getSourceRange();
9715     else
9716       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9717           << VN << TSI->getType()
9718           << (DeduceInit->getType().isNull() ? TSI->getType()
9719                                              : DeduceInit->getType())
9720           << DeduceInit->getSourceRange();
9721   }
9722 
9723   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9724   // 'id' instead of a specific object type prevents most of our usual
9725   // checks.
9726   // We only want to warn outside of template instantiations, though:
9727   // inside a template, the 'id' could have come from a parameter.
9728   if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
9729       !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9730     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9731     Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
9732   }
9733 
9734   return DeducedType;
9735 }
9736 
9737 /// AddInitializerToDecl - Adds the initializer Init to the
9738 /// declaration dcl. If DirectInit is true, this is C++ direct
9739 /// initialization rather than copy initialization.
9740 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
9741                                 bool DirectInit, bool TypeMayContainAuto) {
9742   // If there is no declaration, there was an error parsing it.  Just ignore
9743   // the initializer.
9744   if (!RealDecl || RealDecl->isInvalidDecl()) {
9745     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
9746     return;
9747   }
9748 
9749   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
9750     // Pure-specifiers are handled in ActOnPureSpecifier.
9751     Diag(Method->getLocation(), diag::err_member_function_initialization)
9752       << Method->getDeclName() << Init->getSourceRange();
9753     Method->setInvalidDecl();
9754     return;
9755   }
9756 
9757   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9758   if (!VDecl) {
9759     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
9760     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9761     RealDecl->setInvalidDecl();
9762     return;
9763   }
9764 
9765   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9766   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
9767     // Attempt typo correction early so that the type of the init expression can
9768     // be deduced based on the chosen correction if the original init contains a
9769     // TypoExpr.
9770     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
9771     if (!Res.isUsable()) {
9772       RealDecl->setInvalidDecl();
9773       return;
9774     }
9775     Init = Res.get();
9776 
9777     QualType DeducedType = deduceVarTypeFromInitializer(
9778         VDecl, VDecl->getDeclName(), VDecl->getType(),
9779         VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
9780     if (DeducedType.isNull()) {
9781       RealDecl->setInvalidDecl();
9782       return;
9783     }
9784 
9785     VDecl->setType(DeducedType);
9786     assert(VDecl->isLinkageValid());
9787 
9788     // In ARC, infer lifetime.
9789     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9790       VDecl->setInvalidDecl();
9791 
9792     // If this is a redeclaration, check that the type we just deduced matches
9793     // the previously declared type.
9794     if (VarDecl *Old = VDecl->getPreviousDecl()) {
9795       // We never need to merge the type, because we cannot form an incomplete
9796       // array of auto, nor deduce such a type.
9797       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9798     }
9799 
9800     // Check the deduced type is valid for a variable declaration.
9801     CheckVariableDeclarationType(VDecl);
9802     if (VDecl->isInvalidDecl())
9803       return;
9804   }
9805 
9806   // dllimport cannot be used on variable definitions.
9807   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
9808     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
9809     VDecl->setInvalidDecl();
9810     return;
9811   }
9812 
9813   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
9814     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
9815     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
9816     VDecl->setInvalidDecl();
9817     return;
9818   }
9819 
9820   if (!VDecl->getType()->isDependentType()) {
9821     // A definition must end up with a complete type, which means it must be
9822     // complete with the restriction that an array type might be completed by
9823     // the initializer; note that later code assumes this restriction.
9824     QualType BaseDeclType = VDecl->getType();
9825     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
9826       BaseDeclType = Array->getElementType();
9827     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
9828                             diag::err_typecheck_decl_incomplete_type)) {
9829       RealDecl->setInvalidDecl();
9830       return;
9831     }
9832 
9833     // The variable can not have an abstract class type.
9834     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9835                                diag::err_abstract_type_in_decl,
9836                                AbstractVariableType))
9837       VDecl->setInvalidDecl();
9838   }
9839 
9840   // If adding the initializer will turn this declaration into a definition,
9841   // and we already have a definition for this variable, diagnose or otherwise
9842   // handle the situation.
9843   VarDecl *Def;
9844   if ((Def = VDecl->getDefinition()) && Def != VDecl &&
9845       (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
9846       !VDecl->isThisDeclarationADemotedDefinition() &&
9847       checkVarDeclRedefinition(Def, VDecl))
9848     return;
9849 
9850   if (getLangOpts().CPlusPlus) {
9851     // C++ [class.static.data]p4
9852     //   If a static data member is of const integral or const
9853     //   enumeration type, its declaration in the class definition can
9854     //   specify a constant-initializer which shall be an integral
9855     //   constant expression (5.19). In that case, the member can appear
9856     //   in integral constant expressions. The member shall still be
9857     //   defined in a namespace scope if it is used in the program and the
9858     //   namespace scope definition shall not contain an initializer.
9859     //
9860     // We already performed a redefinition check above, but for static
9861     // data members we also need to check whether there was an in-class
9862     // declaration with an initializer.
9863     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9864       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9865           << VDecl->getDeclName();
9866       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9867            diag::note_previous_initializer)
9868           << 0;
9869       return;
9870     }
9871 
9872     if (VDecl->hasLocalStorage())
9873       getCurFunction()->setHasBranchProtectedScope();
9874 
9875     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9876       VDecl->setInvalidDecl();
9877       return;
9878     }
9879   }
9880 
9881   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9882   // a kernel function cannot be initialized."
9883   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
9884     Diag(VDecl->getLocation(), diag::err_local_cant_init);
9885     VDecl->setInvalidDecl();
9886     return;
9887   }
9888 
9889   // Get the decls type and save a reference for later, since
9890   // CheckInitializerTypes may change it.
9891   QualType DclT = VDecl->getType(), SavT = DclT;
9892 
9893   // Expressions default to 'id' when we're in a debugger
9894   // and we are assigning it to a variable of Objective-C pointer type.
9895   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9896       Init->getType() == Context.UnknownAnyTy) {
9897     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9898     if (Result.isInvalid()) {
9899       VDecl->setInvalidDecl();
9900       return;
9901     }
9902     Init = Result.get();
9903   }
9904 
9905   // Perform the initialization.
9906   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
9907   if (!VDecl->isInvalidDecl()) {
9908     // Handle errors like: int a({0})
9909     if (CXXDirectInit && CXXDirectInit->getNumExprs() == 1 &&
9910         !canInitializeWithParenthesizedList(VDecl->getType()))
9911       if (auto IList = dyn_cast<InitListExpr>(CXXDirectInit->getExpr(0))) {
9912         Diag(VDecl->getLocation(), diag::err_list_init_in_parens)
9913             << VDecl->getType() << CXXDirectInit->getSourceRange()
9914             << FixItHint::CreateRemoval(CXXDirectInit->getLocStart())
9915             << FixItHint::CreateRemoval(CXXDirectInit->getLocEnd());
9916         Init = IList;
9917         CXXDirectInit = nullptr;
9918       }
9919 
9920     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9921     InitializationKind Kind =
9922         DirectInit
9923             ? CXXDirectInit
9924                   ? InitializationKind::CreateDirect(VDecl->getLocation(),
9925                                                      Init->getLocStart(),
9926                                                      Init->getLocEnd())
9927                   : InitializationKind::CreateDirectList(VDecl->getLocation())
9928             : InitializationKind::CreateCopy(VDecl->getLocation(),
9929                                              Init->getLocStart());
9930 
9931     MultiExprArg Args = Init;
9932     if (CXXDirectInit)
9933       Args = MultiExprArg(CXXDirectInit->getExprs(),
9934                           CXXDirectInit->getNumExprs());
9935 
9936     // Try to correct any TypoExprs in the initialization arguments.
9937     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
9938       ExprResult Res = CorrectDelayedTyposInExpr(
9939           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
9940             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
9941             return Init.Failed() ? ExprError() : E;
9942           });
9943       if (Res.isInvalid()) {
9944         VDecl->setInvalidDecl();
9945       } else if (Res.get() != Args[Idx]) {
9946         Args[Idx] = Res.get();
9947       }
9948     }
9949     if (VDecl->isInvalidDecl())
9950       return;
9951 
9952     InitializationSequence InitSeq(*this, Entity, Kind, Args,
9953                                    /*TopLevelOfInitList=*/false,
9954                                    /*TreatUnavailableAsInvalid=*/false);
9955     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
9956     if (Result.isInvalid()) {
9957       VDecl->setInvalidDecl();
9958       return;
9959     }
9960 
9961     Init = Result.getAs<Expr>();
9962   }
9963 
9964   // Check for self-references within variable initializers.
9965   // Variables declared within a function/method body (except for references)
9966   // are handled by a dataflow analysis.
9967   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
9968       VDecl->getType()->isReferenceType()) {
9969     CheckSelfReference(*this, RealDecl, Init, DirectInit);
9970   }
9971 
9972   // If the type changed, it means we had an incomplete type that was
9973   // completed by the initializer. For example:
9974   //   int ary[] = { 1, 3, 5 };
9975   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
9976   if (!VDecl->isInvalidDecl() && (DclT != SavT))
9977     VDecl->setType(DclT);
9978 
9979   if (!VDecl->isInvalidDecl()) {
9980     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
9981 
9982     if (VDecl->hasAttr<BlocksAttr>())
9983       checkRetainCycles(VDecl, Init);
9984 
9985     // It is safe to assign a weak reference into a strong variable.
9986     // Although this code can still have problems:
9987     //   id x = self.weakProp;
9988     //   id y = self.weakProp;
9989     // we do not warn to warn spuriously when 'x' and 'y' are on separate
9990     // paths through the function. This should be revisited if
9991     // -Wrepeated-use-of-weak is made flow-sensitive.
9992     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
9993         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9994                          Init->getLocStart()))
9995       getCurFunction()->markSafeWeakUse(Init);
9996   }
9997 
9998   // The initialization is usually a full-expression.
9999   //
10000   // FIXME: If this is a braced initialization of an aggregate, it is not
10001   // an expression, and each individual field initializer is a separate
10002   // full-expression. For instance, in:
10003   //
10004   //   struct Temp { ~Temp(); };
10005   //   struct S { S(Temp); };
10006   //   struct T { S a, b; } t = { Temp(), Temp() }
10007   //
10008   // we should destroy the first Temp before constructing the second.
10009   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
10010                                           false,
10011                                           VDecl->isConstexpr());
10012   if (Result.isInvalid()) {
10013     VDecl->setInvalidDecl();
10014     return;
10015   }
10016   Init = Result.get();
10017 
10018   // Attach the initializer to the decl.
10019   VDecl->setInit(Init);
10020 
10021   if (VDecl->isLocalVarDecl()) {
10022     // C99 6.7.8p4: All the expressions in an initializer for an object that has
10023     // static storage duration shall be constant expressions or string literals.
10024     // C++ does not have this restriction.
10025     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
10026       const Expr *Culprit;
10027       if (VDecl->getStorageClass() == SC_Static)
10028         CheckForConstantInitializer(Init, DclT);
10029       // C89 is stricter than C99 for non-static aggregate types.
10030       // C89 6.5.7p3: All the expressions [...] in an initializer list
10031       // for an object that has aggregate or union type shall be
10032       // constant expressions.
10033       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
10034                isa<InitListExpr>(Init) &&
10035                !Init->isConstantInitializer(Context, false, &Culprit))
10036         Diag(Culprit->getExprLoc(),
10037              diag::ext_aggregate_init_not_constant)
10038           << Culprit->getSourceRange();
10039     }
10040   } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
10041              VDecl->getLexicalDeclContext()->isRecord()) {
10042     // This is an in-class initialization for a static data member, e.g.,
10043     //
10044     // struct S {
10045     //   static const int value = 17;
10046     // };
10047 
10048     // C++ [class.mem]p4:
10049     //   A member-declarator can contain a constant-initializer only
10050     //   if it declares a static member (9.4) of const integral or
10051     //   const enumeration type, see 9.4.2.
10052     //
10053     // C++11 [class.static.data]p3:
10054     //   If a non-volatile non-inline const static data member is of integral
10055     //   or enumeration type, its declaration in the class definition can
10056     //   specify a brace-or-equal-initializer in which every initalizer-clause
10057     //   that is an assignment-expression is a constant expression. A static
10058     //   data member of literal type can be declared in the class definition
10059     //   with the constexpr specifier; if so, its declaration shall specify a
10060     //   brace-or-equal-initializer in which every initializer-clause that is
10061     //   an assignment-expression is a constant expression.
10062 
10063     // Do nothing on dependent types.
10064     if (DclT->isDependentType()) {
10065 
10066     // Allow any 'static constexpr' members, whether or not they are of literal
10067     // type. We separately check that every constexpr variable is of literal
10068     // type.
10069     } else if (VDecl->isConstexpr()) {
10070 
10071     // Require constness.
10072     } else if (!DclT.isConstQualified()) {
10073       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
10074         << Init->getSourceRange();
10075       VDecl->setInvalidDecl();
10076 
10077     // We allow integer constant expressions in all cases.
10078     } else if (DclT->isIntegralOrEnumerationType()) {
10079       // Check whether the expression is a constant expression.
10080       SourceLocation Loc;
10081       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
10082         // In C++11, a non-constexpr const static data member with an
10083         // in-class initializer cannot be volatile.
10084         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
10085       else if (Init->isValueDependent())
10086         ; // Nothing to check.
10087       else if (Init->isIntegerConstantExpr(Context, &Loc))
10088         ; // Ok, it's an ICE!
10089       else if (Init->isEvaluatable(Context)) {
10090         // If we can constant fold the initializer through heroics, accept it,
10091         // but report this as a use of an extension for -pedantic.
10092         Diag(Loc, diag::ext_in_class_initializer_non_constant)
10093           << Init->getSourceRange();
10094       } else {
10095         // Otherwise, this is some crazy unknown case.  Report the issue at the
10096         // location provided by the isIntegerConstantExpr failed check.
10097         Diag(Loc, diag::err_in_class_initializer_non_constant)
10098           << Init->getSourceRange();
10099         VDecl->setInvalidDecl();
10100       }
10101 
10102     // We allow foldable floating-point constants as an extension.
10103     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
10104       // In C++98, this is a GNU extension. In C++11, it is not, but we support
10105       // it anyway and provide a fixit to add the 'constexpr'.
10106       if (getLangOpts().CPlusPlus11) {
10107         Diag(VDecl->getLocation(),
10108              diag::ext_in_class_initializer_float_type_cxx11)
10109             << DclT << Init->getSourceRange();
10110         Diag(VDecl->getLocStart(),
10111              diag::note_in_class_initializer_float_type_cxx11)
10112             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10113       } else {
10114         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
10115           << DclT << Init->getSourceRange();
10116 
10117         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
10118           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
10119             << Init->getSourceRange();
10120           VDecl->setInvalidDecl();
10121         }
10122       }
10123 
10124     // Suggest adding 'constexpr' in C++11 for literal types.
10125     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
10126       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
10127         << DclT << Init->getSourceRange()
10128         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
10129       VDecl->setConstexpr(true);
10130 
10131     } else {
10132       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
10133         << DclT << Init->getSourceRange();
10134       VDecl->setInvalidDecl();
10135     }
10136   } else if (VDecl->isFileVarDecl()) {
10137     // In C, extern is typically used to avoid tentative definitions when
10138     // declaring variables in headers, but adding an intializer makes it a
10139     // defintion. This is somewhat confusing, so GCC and Clang both warn on it.
10140     // In C++, extern is often used to give implictly static const variables
10141     // external linkage, so don't warn in that case. If selectany is present,
10142     // this might be header code intended for C and C++ inclusion, so apply the
10143     // C++ rules.
10144     if (VDecl->getStorageClass() == SC_Extern &&
10145         ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
10146          !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
10147         !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
10148         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
10149       Diag(VDecl->getLocation(), diag::warn_extern_init);
10150 
10151     // C99 6.7.8p4. All file scoped initializers need to be constant.
10152     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
10153       CheckForConstantInitializer(Init, DclT);
10154   }
10155 
10156   // We will represent direct-initialization similarly to copy-initialization:
10157   //    int x(1);  -as-> int x = 1;
10158   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
10159   //
10160   // Clients that want to distinguish between the two forms, can check for
10161   // direct initializer using VarDecl::getInitStyle().
10162   // A major benefit is that clients that don't particularly care about which
10163   // exactly form was it (like the CodeGen) can handle both cases without
10164   // special case code.
10165 
10166   // C++ 8.5p11:
10167   // The form of initialization (using parentheses or '=') is generally
10168   // insignificant, but does matter when the entity being initialized has a
10169   // class type.
10170   if (CXXDirectInit) {
10171     assert(DirectInit && "Call-style initializer must be direct init.");
10172     VDecl->setInitStyle(VarDecl::CallInit);
10173   } else if (DirectInit) {
10174     // This must be list-initialization. No other way is direct-initialization.
10175     VDecl->setInitStyle(VarDecl::ListInit);
10176   }
10177 
10178   CheckCompleteVariableDeclaration(VDecl);
10179 }
10180 
10181 /// ActOnInitializerError - Given that there was an error parsing an
10182 /// initializer for the given declaration, try to return to some form
10183 /// of sanity.
10184 void Sema::ActOnInitializerError(Decl *D) {
10185   // Our main concern here is re-establishing invariants like "a
10186   // variable's type is either dependent or complete".
10187   if (!D || D->isInvalidDecl()) return;
10188 
10189   VarDecl *VD = dyn_cast<VarDecl>(D);
10190   if (!VD) return;
10191 
10192   // Bindings are not usable if we can't make sense of the initializer.
10193   if (auto *DD = dyn_cast<DecompositionDecl>(D))
10194     for (auto *BD : DD->bindings())
10195       BD->setInvalidDecl();
10196 
10197   // Auto types are meaningless if we can't make sense of the initializer.
10198   if (ParsingInitForAutoVars.count(D)) {
10199     D->setInvalidDecl();
10200     return;
10201   }
10202 
10203   QualType Ty = VD->getType();
10204   if (Ty->isDependentType()) return;
10205 
10206   // Require a complete type.
10207   if (RequireCompleteType(VD->getLocation(),
10208                           Context.getBaseElementType(Ty),
10209                           diag::err_typecheck_decl_incomplete_type)) {
10210     VD->setInvalidDecl();
10211     return;
10212   }
10213 
10214   // Require a non-abstract type.
10215   if (RequireNonAbstractType(VD->getLocation(), Ty,
10216                              diag::err_abstract_type_in_decl,
10217                              AbstractVariableType)) {
10218     VD->setInvalidDecl();
10219     return;
10220   }
10221 
10222   // Don't bother complaining about constructors or destructors,
10223   // though.
10224 }
10225 
10226 /// Checks if an object of the given type can be initialized with parenthesized
10227 /// init-list.
10228 ///
10229 /// \param TargetType Type of object being initialized.
10230 ///
10231 /// The function is used to detect wrong initializations, such as 'int({0})'.
10232 ///
10233 bool Sema::canInitializeWithParenthesizedList(QualType TargetType) {
10234   return TargetType->isDependentType() || TargetType->isRecordType() ||
10235          TargetType->getContainedAutoType();
10236 }
10237 
10238 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
10239                                   bool TypeMayContainAuto) {
10240   // If there is no declaration, there was an error parsing it. Just ignore it.
10241   if (!RealDecl)
10242     return;
10243 
10244   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
10245     QualType Type = Var->getType();
10246 
10247     // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
10248     if (isa<DecompositionDecl>(RealDecl)) {
10249       Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
10250       Var->setInvalidDecl();
10251       return;
10252     }
10253 
10254     // C++11 [dcl.spec.auto]p3
10255     if (TypeMayContainAuto && Type->getContainedAutoType()) {
10256       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
10257         << Var->getDeclName() << Type;
10258       Var->setInvalidDecl();
10259       return;
10260     }
10261 
10262     // C++11 [class.static.data]p3: A static data member can be declared with
10263     // the constexpr specifier; if so, its declaration shall specify
10264     // a brace-or-equal-initializer.
10265     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
10266     // the definition of a variable [...] or the declaration of a static data
10267     // member.
10268     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
10269         !Var->isThisDeclarationADemotedDefinition()) {
10270       if (Var->isStaticDataMember()) {
10271         // C++1z removes the relevant rule; the in-class declaration is always
10272         // a definition there.
10273         if (!getLangOpts().CPlusPlus1z) {
10274           Diag(Var->getLocation(),
10275                diag::err_constexpr_static_mem_var_requires_init)
10276             << Var->getDeclName();
10277           Var->setInvalidDecl();
10278           return;
10279         }
10280       } else {
10281         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
10282         Var->setInvalidDecl();
10283         return;
10284       }
10285     }
10286 
10287     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
10288     // definition having the concept specifier is called a variable concept. A
10289     // concept definition refers to [...] a variable concept and its initializer.
10290     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
10291       if (VTD->isConcept()) {
10292         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
10293         Var->setInvalidDecl();
10294         return;
10295       }
10296     }
10297 
10298     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
10299     // be initialized.
10300     if (!Var->isInvalidDecl() &&
10301         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
10302         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
10303       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
10304       Var->setInvalidDecl();
10305       return;
10306     }
10307 
10308     switch (Var->isThisDeclarationADefinition()) {
10309     case VarDecl::Definition:
10310       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
10311         break;
10312 
10313       // We have an out-of-line definition of a static data member
10314       // that has an in-class initializer, so we type-check this like
10315       // a declaration.
10316       //
10317       // Fall through
10318 
10319     case VarDecl::DeclarationOnly:
10320       // It's only a declaration.
10321 
10322       // Block scope. C99 6.7p7: If an identifier for an object is
10323       // declared with no linkage (C99 6.2.2p6), the type for the
10324       // object shall be complete.
10325       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10326           !Var->hasLinkage() && !Var->isInvalidDecl() &&
10327           RequireCompleteType(Var->getLocation(), Type,
10328                               diag::err_typecheck_decl_incomplete_type))
10329         Var->setInvalidDecl();
10330 
10331       // Make sure that the type is not abstract.
10332       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10333           RequireNonAbstractType(Var->getLocation(), Type,
10334                                  diag::err_abstract_type_in_decl,
10335                                  AbstractVariableType))
10336         Var->setInvalidDecl();
10337       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10338           Var->getStorageClass() == SC_PrivateExtern) {
10339         Diag(Var->getLocation(), diag::warn_private_extern);
10340         Diag(Var->getLocation(), diag::note_private_extern);
10341       }
10342 
10343       return;
10344 
10345     case VarDecl::TentativeDefinition:
10346       // File scope. C99 6.9.2p2: A declaration of an identifier for an
10347       // object that has file scope without an initializer, and without a
10348       // storage-class specifier or with the storage-class specifier "static",
10349       // constitutes a tentative definition. Note: A tentative definition with
10350       // external linkage is valid (C99 6.2.2p5).
10351       if (!Var->isInvalidDecl()) {
10352         if (const IncompleteArrayType *ArrayT
10353                                     = Context.getAsIncompleteArrayType(Type)) {
10354           if (RequireCompleteType(Var->getLocation(),
10355                                   ArrayT->getElementType(),
10356                                   diag::err_illegal_decl_array_incomplete_type))
10357             Var->setInvalidDecl();
10358         } else if (Var->getStorageClass() == SC_Static) {
10359           // C99 6.9.2p3: If the declaration of an identifier for an object is
10360           // a tentative definition and has internal linkage (C99 6.2.2p3), the
10361           // declared type shall not be an incomplete type.
10362           // NOTE: code such as the following
10363           //     static struct s;
10364           //     struct s { int a; };
10365           // is accepted by gcc. Hence here we issue a warning instead of
10366           // an error and we do not invalidate the static declaration.
10367           // NOTE: to avoid multiple warnings, only check the first declaration.
10368           if (Var->isFirstDecl())
10369             RequireCompleteType(Var->getLocation(), Type,
10370                                 diag::ext_typecheck_decl_incomplete_type);
10371         }
10372       }
10373 
10374       // Record the tentative definition; we're done.
10375       if (!Var->isInvalidDecl())
10376         TentativeDefinitions.push_back(Var);
10377       return;
10378     }
10379 
10380     // Provide a specific diagnostic for uninitialized variable
10381     // definitions with incomplete array type.
10382     if (Type->isIncompleteArrayType()) {
10383       Diag(Var->getLocation(),
10384            diag::err_typecheck_incomplete_array_needs_initializer);
10385       Var->setInvalidDecl();
10386       return;
10387     }
10388 
10389     // Provide a specific diagnostic for uninitialized variable
10390     // definitions with reference type.
10391     if (Type->isReferenceType()) {
10392       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10393         << Var->getDeclName()
10394         << SourceRange(Var->getLocation(), Var->getLocation());
10395       Var->setInvalidDecl();
10396       return;
10397     }
10398 
10399     // Do not attempt to type-check the default initializer for a
10400     // variable with dependent type.
10401     if (Type->isDependentType())
10402       return;
10403 
10404     if (Var->isInvalidDecl())
10405       return;
10406 
10407     if (!Var->hasAttr<AliasAttr>()) {
10408       if (RequireCompleteType(Var->getLocation(),
10409                               Context.getBaseElementType(Type),
10410                               diag::err_typecheck_decl_incomplete_type)) {
10411         Var->setInvalidDecl();
10412         return;
10413       }
10414     } else {
10415       return;
10416     }
10417 
10418     // The variable can not have an abstract class type.
10419     if (RequireNonAbstractType(Var->getLocation(), Type,
10420                                diag::err_abstract_type_in_decl,
10421                                AbstractVariableType)) {
10422       Var->setInvalidDecl();
10423       return;
10424     }
10425 
10426     // Check for jumps past the implicit initializer.  C++0x
10427     // clarifies that this applies to a "variable with automatic
10428     // storage duration", not a "local variable".
10429     // C++11 [stmt.dcl]p3
10430     //   A program that jumps from a point where a variable with automatic
10431     //   storage duration is not in scope to a point where it is in scope is
10432     //   ill-formed unless the variable has scalar type, class type with a
10433     //   trivial default constructor and a trivial destructor, a cv-qualified
10434     //   version of one of these types, or an array of one of the preceding
10435     //   types and is declared without an initializer.
10436     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10437       if (const RecordType *Record
10438             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10439         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10440         // Mark the function for further checking even if the looser rules of
10441         // C++11 do not require such checks, so that we can diagnose
10442         // incompatibilities with C++98.
10443         if (!CXXRecord->isPOD())
10444           getCurFunction()->setHasBranchProtectedScope();
10445       }
10446     }
10447 
10448     // C++03 [dcl.init]p9:
10449     //   If no initializer is specified for an object, and the
10450     //   object is of (possibly cv-qualified) non-POD class type (or
10451     //   array thereof), the object shall be default-initialized; if
10452     //   the object is of const-qualified type, the underlying class
10453     //   type shall have a user-declared default
10454     //   constructor. Otherwise, if no initializer is specified for
10455     //   a non- static object, the object and its subobjects, if
10456     //   any, have an indeterminate initial value); if the object
10457     //   or any of its subobjects are of const-qualified type, the
10458     //   program is ill-formed.
10459     // C++0x [dcl.init]p11:
10460     //   If no initializer is specified for an object, the object is
10461     //   default-initialized; [...].
10462     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10463     InitializationKind Kind
10464       = InitializationKind::CreateDefault(Var->getLocation());
10465 
10466     InitializationSequence InitSeq(*this, Entity, Kind, None);
10467     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10468     if (Init.isInvalid())
10469       Var->setInvalidDecl();
10470     else if (Init.get()) {
10471       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10472       // This is important for template substitution.
10473       Var->setInitStyle(VarDecl::CallInit);
10474     }
10475 
10476     CheckCompleteVariableDeclaration(Var);
10477   }
10478 }
10479 
10480 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10481   // If there is no declaration, there was an error parsing it. Ignore it.
10482   if (!D)
10483     return;
10484 
10485   VarDecl *VD = dyn_cast<VarDecl>(D);
10486   if (!VD) {
10487     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10488     D->setInvalidDecl();
10489     return;
10490   }
10491 
10492   VD->setCXXForRangeDecl(true);
10493 
10494   // for-range-declaration cannot be given a storage class specifier.
10495   int Error = -1;
10496   switch (VD->getStorageClass()) {
10497   case SC_None:
10498     break;
10499   case SC_Extern:
10500     Error = 0;
10501     break;
10502   case SC_Static:
10503     Error = 1;
10504     break;
10505   case SC_PrivateExtern:
10506     Error = 2;
10507     break;
10508   case SC_Auto:
10509     Error = 3;
10510     break;
10511   case SC_Register:
10512     Error = 4;
10513     break;
10514   }
10515   if (Error != -1) {
10516     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10517       << VD->getDeclName() << Error;
10518     D->setInvalidDecl();
10519   }
10520 }
10521 
10522 StmtResult
10523 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10524                                  IdentifierInfo *Ident,
10525                                  ParsedAttributes &Attrs,
10526                                  SourceLocation AttrEnd) {
10527   // C++1y [stmt.iter]p1:
10528   //   A range-based for statement of the form
10529   //      for ( for-range-identifier : for-range-initializer ) statement
10530   //   is equivalent to
10531   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
10532   DeclSpec DS(Attrs.getPool().getFactory());
10533 
10534   const char *PrevSpec;
10535   unsigned DiagID;
10536   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10537                      getPrintingPolicy());
10538 
10539   Declarator D(DS, Declarator::ForContext);
10540   D.SetIdentifier(Ident, IdentLoc);
10541   D.takeAttributes(Attrs, AttrEnd);
10542 
10543   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10544   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10545                 EmptyAttrs, IdentLoc);
10546   Decl *Var = ActOnDeclarator(S, D);
10547   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10548   FinalizeDeclaration(Var);
10549   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10550                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
10551 }
10552 
10553 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10554   if (var->isInvalidDecl()) return;
10555 
10556   if (getLangOpts().OpenCL) {
10557     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10558     // initialiser
10559     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10560         !var->hasInit()) {
10561       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10562           << 1 /*Init*/;
10563       var->setInvalidDecl();
10564       return;
10565     }
10566   }
10567 
10568   // In Objective-C, don't allow jumps past the implicit initialization of a
10569   // local retaining variable.
10570   if (getLangOpts().ObjC1 &&
10571       var->hasLocalStorage()) {
10572     switch (var->getType().getObjCLifetime()) {
10573     case Qualifiers::OCL_None:
10574     case Qualifiers::OCL_ExplicitNone:
10575     case Qualifiers::OCL_Autoreleasing:
10576       break;
10577 
10578     case Qualifiers::OCL_Weak:
10579     case Qualifiers::OCL_Strong:
10580       getCurFunction()->setHasBranchProtectedScope();
10581       break;
10582     }
10583   }
10584 
10585   // Warn about externally-visible variables being defined without a
10586   // prior declaration.  We only want to do this for global
10587   // declarations, but we also specifically need to avoid doing it for
10588   // class members because the linkage of an anonymous class can
10589   // change if it's later given a typedef name.
10590   if (var->isThisDeclarationADefinition() &&
10591       var->getDeclContext()->getRedeclContext()->isFileContext() &&
10592       var->isExternallyVisible() && var->hasLinkage() &&
10593       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10594                                   var->getLocation())) {
10595     // Find a previous declaration that's not a definition.
10596     VarDecl *prev = var->getPreviousDecl();
10597     while (prev && prev->isThisDeclarationADefinition())
10598       prev = prev->getPreviousDecl();
10599 
10600     if (!prev)
10601       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10602   }
10603 
10604   // Cache the result of checking for constant initialization.
10605   Optional<bool> CacheHasConstInit;
10606   const Expr *CacheCulprit;
10607   auto checkConstInit = [&]() mutable {
10608     if (!CacheHasConstInit)
10609       CacheHasConstInit = var->getInit()->isConstantInitializer(
10610             Context, var->getType()->isReferenceType(), &CacheCulprit);
10611     return *CacheHasConstInit;
10612   };
10613 
10614   if (var->getTLSKind() == VarDecl::TLS_Static) {
10615     if (var->getType().isDestructedType()) {
10616       // GNU C++98 edits for __thread, [basic.start.term]p3:
10617       //   The type of an object with thread storage duration shall not
10618       //   have a non-trivial destructor.
10619       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10620       if (getLangOpts().CPlusPlus11)
10621         Diag(var->getLocation(), diag::note_use_thread_local);
10622     } else if (getLangOpts().CPlusPlus && var->hasInit()) {
10623       if (!checkConstInit()) {
10624         // GNU C++98 edits for __thread, [basic.start.init]p4:
10625         //   An object of thread storage duration shall not require dynamic
10626         //   initialization.
10627         // FIXME: Need strict checking here.
10628         Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
10629           << CacheCulprit->getSourceRange();
10630         if (getLangOpts().CPlusPlus11)
10631           Diag(var->getLocation(), diag::note_use_thread_local);
10632       }
10633     }
10634   }
10635 
10636   // Apply section attributes and pragmas to global variables.
10637   bool GlobalStorage = var->hasGlobalStorage();
10638   if (GlobalStorage && var->isThisDeclarationADefinition() &&
10639       ActiveTemplateInstantiations.empty()) {
10640     PragmaStack<StringLiteral *> *Stack = nullptr;
10641     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10642     if (var->getType().isConstQualified())
10643       Stack = &ConstSegStack;
10644     else if (!var->getInit()) {
10645       Stack = &BSSSegStack;
10646       SectionFlags |= ASTContext::PSF_Write;
10647     } else {
10648       Stack = &DataSegStack;
10649       SectionFlags |= ASTContext::PSF_Write;
10650     }
10651     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10652       var->addAttr(SectionAttr::CreateImplicit(
10653           Context, SectionAttr::Declspec_allocate,
10654           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10655     }
10656     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10657       if (UnifySection(SA->getName(), SectionFlags, var))
10658         var->dropAttr<SectionAttr>();
10659 
10660     // Apply the init_seg attribute if this has an initializer.  If the
10661     // initializer turns out to not be dynamic, we'll end up ignoring this
10662     // attribute.
10663     if (CurInitSeg && var->getInit())
10664       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10665                                                CurInitSegLoc));
10666   }
10667 
10668   // All the following checks are C++ only.
10669   if (!getLangOpts().CPlusPlus) {
10670       // If this variable must be emitted, add it as an initializer for the
10671       // current module.
10672      if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
10673        Context.addModuleInitializer(ModuleScopes.back().Module, var);
10674      return;
10675   }
10676 
10677   if (auto *DD = dyn_cast<DecompositionDecl>(var))
10678     CheckCompleteDecompositionDeclaration(DD);
10679 
10680   QualType type = var->getType();
10681   if (type->isDependentType()) return;
10682 
10683   // __block variables might require us to capture a copy-initializer.
10684   if (var->hasAttr<BlocksAttr>()) {
10685     // It's currently invalid to ever have a __block variable with an
10686     // array type; should we diagnose that here?
10687 
10688     // Regardless, we don't want to ignore array nesting when
10689     // constructing this copy.
10690     if (type->isStructureOrClassType()) {
10691       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10692       SourceLocation poi = var->getLocation();
10693       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10694       ExprResult result
10695         = PerformMoveOrCopyInitialization(
10696             InitializedEntity::InitializeBlock(poi, type, false),
10697             var, var->getType(), varRef, /*AllowNRVO=*/true);
10698       if (!result.isInvalid()) {
10699         result = MaybeCreateExprWithCleanups(result);
10700         Expr *init = result.getAs<Expr>();
10701         Context.setBlockVarCopyInits(var, init);
10702       }
10703     }
10704   }
10705 
10706   Expr *Init = var->getInit();
10707   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10708   QualType baseType = Context.getBaseElementType(type);
10709 
10710   if (!var->getDeclContext()->isDependentContext() &&
10711       Init && !Init->isValueDependent()) {
10712 
10713     if (var->isConstexpr()) {
10714       SmallVector<PartialDiagnosticAt, 8> Notes;
10715       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10716         SourceLocation DiagLoc = var->getLocation();
10717         // If the note doesn't add any useful information other than a source
10718         // location, fold it into the primary diagnostic.
10719         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10720               diag::note_invalid_subexpr_in_const_expr) {
10721           DiagLoc = Notes[0].first;
10722           Notes.clear();
10723         }
10724         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10725           << var << Init->getSourceRange();
10726         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10727           Diag(Notes[I].first, Notes[I].second);
10728       }
10729     } else if (var->isUsableInConstantExpressions(Context)) {
10730       // Check whether the initializer of a const variable of integral or
10731       // enumeration type is an ICE now, since we can't tell whether it was
10732       // initialized by a constant expression if we check later.
10733       var->checkInitIsICE();
10734     }
10735 
10736     // Don't emit further diagnostics about constexpr globals since they
10737     // were just diagnosed.
10738     if (!var->isConstexpr() && GlobalStorage &&
10739             var->hasAttr<RequireConstantInitAttr>()) {
10740       // FIXME: Need strict checking in C++03 here.
10741       bool DiagErr = getLangOpts().CPlusPlus11
10742           ? !var->checkInitIsICE() : !checkConstInit();
10743       if (DiagErr) {
10744         auto attr = var->getAttr<RequireConstantInitAttr>();
10745         Diag(var->getLocation(), diag::err_require_constant_init_failed)
10746           << Init->getSourceRange();
10747         Diag(attr->getLocation(), diag::note_declared_required_constant_init_here)
10748           << attr->getRange();
10749       }
10750     }
10751     else if (!var->isConstexpr() && IsGlobal &&
10752              !getDiagnostics().isIgnored(diag::warn_global_constructor,
10753                                     var->getLocation())) {
10754       // Warn about globals which don't have a constant initializer.  Don't
10755       // warn about globals with a non-trivial destructor because we already
10756       // warned about them.
10757       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10758       if (!(RD && !RD->hasTrivialDestructor())) {
10759         if (!checkConstInit())
10760           Diag(var->getLocation(), diag::warn_global_constructor)
10761             << Init->getSourceRange();
10762       }
10763     }
10764   }
10765 
10766   // Require the destructor.
10767   if (const RecordType *recordType = baseType->getAs<RecordType>())
10768     FinalizeVarWithDestructor(var, recordType);
10769 
10770   // If this variable must be emitted, add it as an initializer for the current
10771   // module.
10772   if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
10773     Context.addModuleInitializer(ModuleScopes.back().Module, var);
10774 }
10775 
10776 /// \brief Determines if a variable's alignment is dependent.
10777 static bool hasDependentAlignment(VarDecl *VD) {
10778   if (VD->getType()->isDependentType())
10779     return true;
10780   for (auto *I : VD->specific_attrs<AlignedAttr>())
10781     if (I->isAlignmentDependent())
10782       return true;
10783   return false;
10784 }
10785 
10786 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10787 /// any semantic actions necessary after any initializer has been attached.
10788 void
10789 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10790   // Note that we are no longer parsing the initializer for this declaration.
10791   ParsingInitForAutoVars.erase(ThisDecl);
10792 
10793   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10794   if (!VD)
10795     return;
10796 
10797   if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
10798     for (auto *BD : DD->bindings()) {
10799       FinalizeDeclaration(BD);
10800     }
10801   }
10802 
10803   checkAttributesAfterMerging(*this, *VD);
10804 
10805   // Perform TLS alignment check here after attributes attached to the variable
10806   // which may affect the alignment have been processed. Only perform the check
10807   // if the target has a maximum TLS alignment (zero means no constraints).
10808   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
10809     // Protect the check so that it's not performed on dependent types and
10810     // dependent alignments (we can't determine the alignment in that case).
10811     if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
10812       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
10813       if (Context.getDeclAlign(VD) > MaxAlignChars) {
10814         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
10815           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
10816           << (unsigned)MaxAlignChars.getQuantity();
10817       }
10818     }
10819   }
10820 
10821   if (VD->isStaticLocal()) {
10822     if (FunctionDecl *FD =
10823             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
10824       // Static locals inherit dll attributes from their function.
10825       if (Attr *A = getDLLAttr(FD)) {
10826         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
10827         NewAttr->setInherited(true);
10828         VD->addAttr(NewAttr);
10829       }
10830       // CUDA E.2.9.4: Within the body of a __device__ or __global__
10831       // function, only __shared__ variables may be declared with
10832       // static storage class.
10833       if (getLangOpts().CUDA && !VD->hasAttr<CUDASharedAttr>() &&
10834           CUDADiagIfDeviceCode(VD->getLocation(),
10835                                diag::err_device_static_local_var)
10836               << CurrentCUDATarget())
10837         VD->setInvalidDecl();
10838     }
10839   }
10840 
10841   // Perform check for initializers of device-side global variables.
10842   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
10843   // 7.5). We must also apply the same checks to all __shared__
10844   // variables whether they are local or not. CUDA also allows
10845   // constant initializers for __constant__ and __device__ variables.
10846   if (getLangOpts().CUDA) {
10847     const Expr *Init = VD->getInit();
10848     if (Init && VD->hasGlobalStorage()) {
10849       if (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
10850           VD->hasAttr<CUDASharedAttr>()) {
10851         assert(!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>());
10852         bool AllowedInit = false;
10853         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
10854           AllowedInit =
10855               isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
10856         // We'll allow constant initializers even if it's a non-empty
10857         // constructor according to CUDA rules. This deviates from NVCC,
10858         // but allows us to handle things like constexpr constructors.
10859         if (!AllowedInit &&
10860             (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
10861           AllowedInit = VD->getInit()->isConstantInitializer(
10862               Context, VD->getType()->isReferenceType());
10863 
10864         // Also make sure that destructor, if there is one, is empty.
10865         if (AllowedInit)
10866           if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
10867             AllowedInit =
10868                 isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
10869 
10870         if (!AllowedInit) {
10871           Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
10872                                       ? diag::err_shared_var_init
10873                                       : diag::err_dynamic_var_init)
10874               << Init->getSourceRange();
10875           VD->setInvalidDecl();
10876         }
10877       } else {
10878         // This is a host-side global variable.  Check that the initializer is
10879         // callable from the host side.
10880         const FunctionDecl *InitFn = nullptr;
10881         if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init)) {
10882           InitFn = CE->getConstructor();
10883         } else if (const CallExpr *CE = dyn_cast<CallExpr>(Init)) {
10884           InitFn = CE->getDirectCallee();
10885         }
10886         if (InitFn) {
10887           CUDAFunctionTarget InitFnTarget = IdentifyCUDATarget(InitFn);
10888           if (InitFnTarget != CFT_Host && InitFnTarget != CFT_HostDevice) {
10889             Diag(VD->getLocation(), diag::err_ref_bad_target_global_initializer)
10890                 << InitFnTarget << InitFn;
10891             Diag(InitFn->getLocation(), diag::note_previous_decl) << InitFn;
10892             VD->setInvalidDecl();
10893           }
10894         }
10895       }
10896     }
10897   }
10898 
10899   // Grab the dllimport or dllexport attribute off of the VarDecl.
10900   const InheritableAttr *DLLAttr = getDLLAttr(VD);
10901 
10902   // Imported static data members cannot be defined out-of-line.
10903   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
10904     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
10905         VD->isThisDeclarationADefinition()) {
10906       // We allow definitions of dllimport class template static data members
10907       // with a warning.
10908       CXXRecordDecl *Context =
10909         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
10910       bool IsClassTemplateMember =
10911           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
10912           Context->getDescribedClassTemplate();
10913 
10914       Diag(VD->getLocation(),
10915            IsClassTemplateMember
10916                ? diag::warn_attribute_dllimport_static_field_definition
10917                : diag::err_attribute_dllimport_static_field_definition);
10918       Diag(IA->getLocation(), diag::note_attribute);
10919       if (!IsClassTemplateMember)
10920         VD->setInvalidDecl();
10921     }
10922   }
10923 
10924   // dllimport/dllexport variables cannot be thread local, their TLS index
10925   // isn't exported with the variable.
10926   if (DLLAttr && VD->getTLSKind()) {
10927     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
10928     if (F && getDLLAttr(F)) {
10929       assert(VD->isStaticLocal());
10930       // But if this is a static local in a dlimport/dllexport function, the
10931       // function will never be inlined, which means the var would never be
10932       // imported, so having it marked import/export is safe.
10933     } else {
10934       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
10935                                                                     << DLLAttr;
10936       VD->setInvalidDecl();
10937     }
10938   }
10939 
10940   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
10941     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
10942       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
10943       VD->dropAttr<UsedAttr>();
10944     }
10945   }
10946 
10947   const DeclContext *DC = VD->getDeclContext();
10948   // If there's a #pragma GCC visibility in scope, and this isn't a class
10949   // member, set the visibility of this variable.
10950   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
10951     AddPushedVisibilityAttribute(VD);
10952 
10953   // FIXME: Warn on unused templates.
10954   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
10955       !isa<VarTemplatePartialSpecializationDecl>(VD))
10956     MarkUnusedFileScopedDecl(VD);
10957 
10958   // Now we have parsed the initializer and can update the table of magic
10959   // tag values.
10960   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
10961       !VD->getType()->isIntegralOrEnumerationType())
10962     return;
10963 
10964   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
10965     const Expr *MagicValueExpr = VD->getInit();
10966     if (!MagicValueExpr) {
10967       continue;
10968     }
10969     llvm::APSInt MagicValueInt;
10970     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
10971       Diag(I->getRange().getBegin(),
10972            diag::err_type_tag_for_datatype_not_ice)
10973         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10974       continue;
10975     }
10976     if (MagicValueInt.getActiveBits() > 64) {
10977       Diag(I->getRange().getBegin(),
10978            diag::err_type_tag_for_datatype_too_large)
10979         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10980       continue;
10981     }
10982     uint64_t MagicValue = MagicValueInt.getZExtValue();
10983     RegisterTypeTagForDatatype(I->getArgumentKind(),
10984                                MagicValue,
10985                                I->getMatchingCType(),
10986                                I->getLayoutCompatible(),
10987                                I->getMustBeNull());
10988   }
10989 }
10990 
10991 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
10992                                                    ArrayRef<Decl *> Group) {
10993   SmallVector<Decl*, 8> Decls;
10994 
10995   if (DS.isTypeSpecOwned())
10996     Decls.push_back(DS.getRepAsDecl());
10997 
10998   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
10999   DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
11000   bool DiagnosedMultipleDecomps = false;
11001 
11002   for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11003     if (Decl *D = Group[i]) {
11004       auto *DD = dyn_cast<DeclaratorDecl>(D);
11005       if (DD && !FirstDeclaratorInGroup)
11006         FirstDeclaratorInGroup = DD;
11007 
11008       auto *Decomp = dyn_cast<DecompositionDecl>(D);
11009       if (Decomp && !FirstDecompDeclaratorInGroup)
11010         FirstDecompDeclaratorInGroup = Decomp;
11011 
11012       // A decomposition declaration cannot be combined with any other
11013       // declaration in the same group.
11014       auto *OtherDD = FirstDeclaratorInGroup;
11015       if (OtherDD == FirstDecompDeclaratorInGroup)
11016         OtherDD = DD;
11017       if (OtherDD && FirstDecompDeclaratorInGroup &&
11018           OtherDD != FirstDecompDeclaratorInGroup &&
11019           !DiagnosedMultipleDecomps) {
11020         Diag(FirstDecompDeclaratorInGroup->getLocation(),
11021              diag::err_decomp_decl_not_alone)
11022           << OtherDD->getSourceRange();
11023         DiagnosedMultipleDecomps = true;
11024       }
11025 
11026       Decls.push_back(D);
11027     }
11028   }
11029 
11030   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
11031     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
11032       handleTagNumbering(Tag, S);
11033       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
11034           getLangOpts().CPlusPlus)
11035         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
11036     }
11037   }
11038 
11039   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
11040 }
11041 
11042 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
11043 /// group, performing any necessary semantic checking.
11044 Sema::DeclGroupPtrTy
11045 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
11046                            bool TypeMayContainAuto) {
11047   // C++0x [dcl.spec.auto]p7:
11048   //   If the type deduced for the template parameter U is not the same in each
11049   //   deduction, the program is ill-formed.
11050   // FIXME: When initializer-list support is added, a distinction is needed
11051   // between the deduced type U and the deduced type which 'auto' stands for.
11052   //   auto a = 0, b = { 1, 2, 3 };
11053   // is legal because the deduced type U is 'int' in both cases.
11054   if (TypeMayContainAuto && Group.size() > 1) {
11055     QualType Deduced;
11056     CanQualType DeducedCanon;
11057     VarDecl *DeducedDecl = nullptr;
11058     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
11059       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
11060         AutoType *AT = D->getType()->getContainedAutoType();
11061         // Don't reissue diagnostics when instantiating a template.
11062         if (AT && D->isInvalidDecl())
11063           break;
11064         QualType U = AT ? AT->getDeducedType() : QualType();
11065         if (!U.isNull()) {
11066           CanQualType UCanon = Context.getCanonicalType(U);
11067           if (Deduced.isNull()) {
11068             Deduced = U;
11069             DeducedCanon = UCanon;
11070             DeducedDecl = D;
11071           } else if (DeducedCanon != UCanon) {
11072             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
11073                  diag::err_auto_different_deductions)
11074               << (unsigned)AT->getKeyword()
11075               << Deduced << DeducedDecl->getDeclName()
11076               << U << D->getDeclName()
11077               << DeducedDecl->getInit()->getSourceRange()
11078               << D->getInit()->getSourceRange();
11079             D->setInvalidDecl();
11080             break;
11081           }
11082         }
11083       }
11084     }
11085   }
11086 
11087   ActOnDocumentableDecls(Group);
11088 
11089   return DeclGroupPtrTy::make(
11090       DeclGroupRef::Create(Context, Group.data(), Group.size()));
11091 }
11092 
11093 void Sema::ActOnDocumentableDecl(Decl *D) {
11094   ActOnDocumentableDecls(D);
11095 }
11096 
11097 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
11098   // Don't parse the comment if Doxygen diagnostics are ignored.
11099   if (Group.empty() || !Group[0])
11100     return;
11101 
11102   if (Diags.isIgnored(diag::warn_doc_param_not_found,
11103                       Group[0]->getLocation()) &&
11104       Diags.isIgnored(diag::warn_unknown_comment_command_name,
11105                       Group[0]->getLocation()))
11106     return;
11107 
11108   if (Group.size() >= 2) {
11109     // This is a decl group.  Normally it will contain only declarations
11110     // produced from declarator list.  But in case we have any definitions or
11111     // additional declaration references:
11112     //   'typedef struct S {} S;'
11113     //   'typedef struct S *S;'
11114     //   'struct S *pS;'
11115     // FinalizeDeclaratorGroup adds these as separate declarations.
11116     Decl *MaybeTagDecl = Group[0];
11117     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
11118       Group = Group.slice(1);
11119     }
11120   }
11121 
11122   // See if there are any new comments that are not attached to a decl.
11123   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
11124   if (!Comments.empty() &&
11125       !Comments.back()->isAttached()) {
11126     // There is at least one comment that not attached to a decl.
11127     // Maybe it should be attached to one of these decls?
11128     //
11129     // Note that this way we pick up not only comments that precede the
11130     // declaration, but also comments that *follow* the declaration -- thanks to
11131     // the lookahead in the lexer: we've consumed the semicolon and looked
11132     // ahead through comments.
11133     for (unsigned i = 0, e = Group.size(); i != e; ++i)
11134       Context.getCommentForDecl(Group[i], &PP);
11135   }
11136 }
11137 
11138 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
11139 /// to introduce parameters into function prototype scope.
11140 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
11141   const DeclSpec &DS = D.getDeclSpec();
11142 
11143   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
11144 
11145   // C++03 [dcl.stc]p2 also permits 'auto'.
11146   StorageClass SC = SC_None;
11147   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
11148     SC = SC_Register;
11149   } else if (getLangOpts().CPlusPlus &&
11150              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
11151     SC = SC_Auto;
11152   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
11153     Diag(DS.getStorageClassSpecLoc(),
11154          diag::err_invalid_storage_class_in_func_decl);
11155     D.getMutableDeclSpec().ClearStorageClassSpecs();
11156   }
11157 
11158   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
11159     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
11160       << DeclSpec::getSpecifierName(TSCS);
11161   if (DS.isInlineSpecified())
11162     Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
11163         << getLangOpts().CPlusPlus1z;
11164   if (DS.isConstexprSpecified())
11165     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
11166       << 0;
11167   if (DS.isConceptSpecified())
11168     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
11169 
11170   DiagnoseFunctionSpecifiers(DS);
11171 
11172   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
11173   QualType parmDeclType = TInfo->getType();
11174 
11175   if (getLangOpts().CPlusPlus) {
11176     // Check that there are no default arguments inside the type of this
11177     // parameter.
11178     CheckExtraCXXDefaultArguments(D);
11179 
11180     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
11181     if (D.getCXXScopeSpec().isSet()) {
11182       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
11183         << D.getCXXScopeSpec().getRange();
11184       D.getCXXScopeSpec().clear();
11185     }
11186   }
11187 
11188   // Ensure we have a valid name
11189   IdentifierInfo *II = nullptr;
11190   if (D.hasName()) {
11191     II = D.getIdentifier();
11192     if (!II) {
11193       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
11194         << GetNameForDeclarator(D).getName();
11195       D.setInvalidType(true);
11196     }
11197   }
11198 
11199   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
11200   if (II) {
11201     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
11202                    ForRedeclaration);
11203     LookupName(R, S);
11204     if (R.isSingleResult()) {
11205       NamedDecl *PrevDecl = R.getFoundDecl();
11206       if (PrevDecl->isTemplateParameter()) {
11207         // Maybe we will complain about the shadowed template parameter.
11208         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
11209         // Just pretend that we didn't see the previous declaration.
11210         PrevDecl = nullptr;
11211       } else if (S->isDeclScope(PrevDecl)) {
11212         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
11213         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
11214 
11215         // Recover by removing the name
11216         II = nullptr;
11217         D.SetIdentifier(nullptr, D.getIdentifierLoc());
11218         D.setInvalidType(true);
11219       }
11220     }
11221   }
11222 
11223   // Temporarily put parameter variables in the translation unit, not
11224   // the enclosing context.  This prevents them from accidentally
11225   // looking like class members in C++.
11226   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
11227                                     D.getLocStart(),
11228                                     D.getIdentifierLoc(), II,
11229                                     parmDeclType, TInfo,
11230                                     SC);
11231 
11232   if (D.isInvalidType())
11233     New->setInvalidDecl();
11234 
11235   assert(S->isFunctionPrototypeScope());
11236   assert(S->getFunctionPrototypeDepth() >= 1);
11237   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
11238                     S->getNextFunctionPrototypeIndex());
11239 
11240   // Add the parameter declaration into this scope.
11241   S->AddDecl(New);
11242   if (II)
11243     IdResolver.AddDecl(New);
11244 
11245   ProcessDeclAttributes(S, New, D);
11246 
11247   if (D.getDeclSpec().isModulePrivateSpecified())
11248     Diag(New->getLocation(), diag::err_module_private_local)
11249       << 1 << New->getDeclName()
11250       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11251       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11252 
11253   if (New->hasAttr<BlocksAttr>()) {
11254     Diag(New->getLocation(), diag::err_block_on_nonlocal);
11255   }
11256   return New;
11257 }
11258 
11259 /// \brief Synthesizes a variable for a parameter arising from a
11260 /// typedef.
11261 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
11262                                               SourceLocation Loc,
11263                                               QualType T) {
11264   /* FIXME: setting StartLoc == Loc.
11265      Would it be worth to modify callers so as to provide proper source
11266      location for the unnamed parameters, embedding the parameter's type? */
11267   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
11268                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
11269                                            SC_None, nullptr);
11270   Param->setImplicit();
11271   return Param;
11272 }
11273 
11274 void Sema::DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters) {
11275   // Don't diagnose unused-parameter errors in template instantiations; we
11276   // will already have done so in the template itself.
11277   if (!ActiveTemplateInstantiations.empty())
11278     return;
11279 
11280   for (const ParmVarDecl *Parameter : Parameters) {
11281     if (!Parameter->isReferenced() && Parameter->getDeclName() &&
11282         !Parameter->hasAttr<UnusedAttr>()) {
11283       Diag(Parameter->getLocation(), diag::warn_unused_parameter)
11284         << Parameter->getDeclName();
11285     }
11286   }
11287 }
11288 
11289 void Sema::DiagnoseSizeOfParametersAndReturnValue(
11290     ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
11291   if (LangOpts.NumLargeByValueCopy == 0) // No check.
11292     return;
11293 
11294   // Warn if the return value is pass-by-value and larger than the specified
11295   // threshold.
11296   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
11297     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
11298     if (Size > LangOpts.NumLargeByValueCopy)
11299       Diag(D->getLocation(), diag::warn_return_value_size)
11300           << D->getDeclName() << Size;
11301   }
11302 
11303   // Warn if any parameter is pass-by-value and larger than the specified
11304   // threshold.
11305   for (const ParmVarDecl *Parameter : Parameters) {
11306     QualType T = Parameter->getType();
11307     if (T->isDependentType() || !T.isPODType(Context))
11308       continue;
11309     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
11310     if (Size > LangOpts.NumLargeByValueCopy)
11311       Diag(Parameter->getLocation(), diag::warn_parameter_size)
11312           << Parameter->getDeclName() << Size;
11313   }
11314 }
11315 
11316 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
11317                                   SourceLocation NameLoc, IdentifierInfo *Name,
11318                                   QualType T, TypeSourceInfo *TSInfo,
11319                                   StorageClass SC) {
11320   // In ARC, infer a lifetime qualifier for appropriate parameter types.
11321   if (getLangOpts().ObjCAutoRefCount &&
11322       T.getObjCLifetime() == Qualifiers::OCL_None &&
11323       T->isObjCLifetimeType()) {
11324 
11325     Qualifiers::ObjCLifetime lifetime;
11326 
11327     // Special cases for arrays:
11328     //   - if it's const, use __unsafe_unretained
11329     //   - otherwise, it's an error
11330     if (T->isArrayType()) {
11331       if (!T.isConstQualified()) {
11332         DelayedDiagnostics.add(
11333             sema::DelayedDiagnostic::makeForbiddenType(
11334             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
11335       }
11336       lifetime = Qualifiers::OCL_ExplicitNone;
11337     } else {
11338       lifetime = T->getObjCARCImplicitLifetime();
11339     }
11340     T = Context.getLifetimeQualifiedType(T, lifetime);
11341   }
11342 
11343   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
11344                                          Context.getAdjustedParameterType(T),
11345                                          TSInfo, SC, nullptr);
11346 
11347   // Parameters can not be abstract class types.
11348   // For record types, this is done by the AbstractClassUsageDiagnoser once
11349   // the class has been completely parsed.
11350   if (!CurContext->isRecord() &&
11351       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
11352                              AbstractParamType))
11353     New->setInvalidDecl();
11354 
11355   // Parameter declarators cannot be interface types. All ObjC objects are
11356   // passed by reference.
11357   if (T->isObjCObjectType()) {
11358     SourceLocation TypeEndLoc =
11359         getLocForEndOfToken(TSInfo->getTypeLoc().getLocEnd());
11360     Diag(NameLoc,
11361          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
11362       << FixItHint::CreateInsertion(TypeEndLoc, "*");
11363     T = Context.getObjCObjectPointerType(T);
11364     New->setType(T);
11365   }
11366 
11367   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
11368   // duration shall not be qualified by an address-space qualifier."
11369   // Since all parameters have automatic store duration, they can not have
11370   // an address space.
11371   if (T.getAddressSpace() != 0) {
11372     // OpenCL allows function arguments declared to be an array of a type
11373     // to be qualified with an address space.
11374     if (!(getLangOpts().OpenCL && T->isArrayType())) {
11375       Diag(NameLoc, diag::err_arg_with_address_space);
11376       New->setInvalidDecl();
11377     }
11378   }
11379 
11380   return New;
11381 }
11382 
11383 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
11384                                            SourceLocation LocAfterDecls) {
11385   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11386 
11387   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
11388   // for a K&R function.
11389   if (!FTI.hasPrototype) {
11390     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
11391       --i;
11392       if (FTI.Params[i].Param == nullptr) {
11393         SmallString<256> Code;
11394         llvm::raw_svector_ostream(Code)
11395             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
11396         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
11397             << FTI.Params[i].Ident
11398             << FixItHint::CreateInsertion(LocAfterDecls, Code);
11399 
11400         // Implicitly declare the argument as type 'int' for lack of a better
11401         // type.
11402         AttributeFactory attrs;
11403         DeclSpec DS(attrs);
11404         const char* PrevSpec; // unused
11405         unsigned DiagID; // unused
11406         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11407                            DiagID, Context.getPrintingPolicy());
11408         // Use the identifier location for the type source range.
11409         DS.SetRangeStart(FTI.Params[i].IdentLoc);
11410         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11411         Declarator ParamD(DS, Declarator::KNRTypeListContext);
11412         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11413         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11414       }
11415     }
11416   }
11417 }
11418 
11419 Decl *
11420 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11421                               MultiTemplateParamsArg TemplateParameterLists,
11422                               SkipBodyInfo *SkipBody) {
11423   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11424   assert(D.isFunctionDeclarator() && "Not a function declarator!");
11425   Scope *ParentScope = FnBodyScope->getParent();
11426 
11427   D.setFunctionDefinitionKind(FDK_Definition);
11428   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11429   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11430 }
11431 
11432 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11433   Consumer.HandleInlineFunctionDefinition(D);
11434 }
11435 
11436 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11437                              const FunctionDecl*& PossibleZeroParamPrototype) {
11438   // Don't warn about invalid declarations.
11439   if (FD->isInvalidDecl())
11440     return false;
11441 
11442   // Or declarations that aren't global.
11443   if (!FD->isGlobal())
11444     return false;
11445 
11446   // Don't warn about C++ member functions.
11447   if (isa<CXXMethodDecl>(FD))
11448     return false;
11449 
11450   // Don't warn about 'main'.
11451   if (FD->isMain())
11452     return false;
11453 
11454   // Don't warn about inline functions.
11455   if (FD->isInlined())
11456     return false;
11457 
11458   // Don't warn about function templates.
11459   if (FD->getDescribedFunctionTemplate())
11460     return false;
11461 
11462   // Don't warn about function template specializations.
11463   if (FD->isFunctionTemplateSpecialization())
11464     return false;
11465 
11466   // Don't warn for OpenCL kernels.
11467   if (FD->hasAttr<OpenCLKernelAttr>())
11468     return false;
11469 
11470   // Don't warn on explicitly deleted functions.
11471   if (FD->isDeleted())
11472     return false;
11473 
11474   bool MissingPrototype = true;
11475   for (const FunctionDecl *Prev = FD->getPreviousDecl();
11476        Prev; Prev = Prev->getPreviousDecl()) {
11477     // Ignore any declarations that occur in function or method
11478     // scope, because they aren't visible from the header.
11479     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11480       continue;
11481 
11482     MissingPrototype = !Prev->getType()->isFunctionProtoType();
11483     if (FD->getNumParams() == 0)
11484       PossibleZeroParamPrototype = Prev;
11485     break;
11486   }
11487 
11488   return MissingPrototype;
11489 }
11490 
11491 void
11492 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11493                                    const FunctionDecl *EffectiveDefinition,
11494                                    SkipBodyInfo *SkipBody) {
11495   // Don't complain if we're in GNU89 mode and the previous definition
11496   // was an extern inline function.
11497   const FunctionDecl *Definition = EffectiveDefinition;
11498   if (!Definition)
11499     if (!FD->isDefined(Definition))
11500       return;
11501 
11502   if (canRedefineFunction(Definition, getLangOpts()))
11503     return;
11504 
11505   // If we don't have a visible definition of the function, and it's inline or
11506   // a template, skip the new definition.
11507   if (SkipBody && !hasVisibleDefinition(Definition) &&
11508       (Definition->getFormalLinkage() == InternalLinkage ||
11509        Definition->isInlined() ||
11510        Definition->getDescribedFunctionTemplate() ||
11511        Definition->getNumTemplateParameterLists())) {
11512     SkipBody->ShouldSkip = true;
11513     if (auto *TD = Definition->getDescribedFunctionTemplate())
11514       makeMergedDefinitionVisible(TD, FD->getLocation());
11515     makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
11516                                 FD->getLocation());
11517     return;
11518   }
11519 
11520   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11521       Definition->getStorageClass() == SC_Extern)
11522     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11523         << FD->getDeclName() << getLangOpts().CPlusPlus;
11524   else
11525     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11526 
11527   Diag(Definition->getLocation(), diag::note_previous_definition);
11528   FD->setInvalidDecl();
11529 }
11530 
11531 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11532                                    Sema &S) {
11533   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11534 
11535   LambdaScopeInfo *LSI = S.PushLambdaScope();
11536   LSI->CallOperator = CallOperator;
11537   LSI->Lambda = LambdaClass;
11538   LSI->ReturnType = CallOperator->getReturnType();
11539   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11540 
11541   if (LCD == LCD_None)
11542     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
11543   else if (LCD == LCD_ByCopy)
11544     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
11545   else if (LCD == LCD_ByRef)
11546     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
11547   DeclarationNameInfo DNI = CallOperator->getNameInfo();
11548 
11549   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
11550   LSI->Mutable = !CallOperator->isConst();
11551 
11552   // Add the captures to the LSI so they can be noted as already
11553   // captured within tryCaptureVar.
11554   auto I = LambdaClass->field_begin();
11555   for (const auto &C : LambdaClass->captures()) {
11556     if (C.capturesVariable()) {
11557       VarDecl *VD = C.getCapturedVar();
11558       if (VD->isInitCapture())
11559         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11560       QualType CaptureType = VD->getType();
11561       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11562       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11563           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11564           /*EllipsisLoc*/C.isPackExpansion()
11565                          ? C.getEllipsisLoc() : SourceLocation(),
11566           CaptureType, /*Expr*/ nullptr);
11567 
11568     } else if (C.capturesThis()) {
11569       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11570                               /*Expr*/ nullptr,
11571                               C.getCaptureKind() == LCK_StarThis);
11572     } else {
11573       LSI->addVLATypeCapture(C.getLocation(), I->getType());
11574     }
11575     ++I;
11576   }
11577 }
11578 
11579 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
11580                                     SkipBodyInfo *SkipBody) {
11581   // Clear the last template instantiation error context.
11582   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
11583 
11584   if (!D)
11585     return D;
11586   FunctionDecl *FD = nullptr;
11587 
11588   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
11589     FD = FunTmpl->getTemplatedDecl();
11590   else
11591     FD = cast<FunctionDecl>(D);
11592 
11593   // See if this is a redefinition.
11594   if (!FD->isLateTemplateParsed()) {
11595     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
11596 
11597     // If we're skipping the body, we're done. Don't enter the scope.
11598     if (SkipBody && SkipBody->ShouldSkip)
11599       return D;
11600   }
11601 
11602   // Mark this function as "will have a body eventually".  This lets users to
11603   // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
11604   // this function.
11605   FD->setWillHaveBody();
11606 
11607   // If we are instantiating a generic lambda call operator, push
11608   // a LambdaScopeInfo onto the function stack.  But use the information
11609   // that's already been calculated (ActOnLambdaExpr) to prime the current
11610   // LambdaScopeInfo.
11611   // When the template operator is being specialized, the LambdaScopeInfo,
11612   // has to be properly restored so that tryCaptureVariable doesn't try
11613   // and capture any new variables. In addition when calculating potential
11614   // captures during transformation of nested lambdas, it is necessary to
11615   // have the LSI properly restored.
11616   if (isGenericLambdaCallOperatorSpecialization(FD)) {
11617     assert(ActiveTemplateInstantiations.size() &&
11618       "There should be an active template instantiation on the stack "
11619       "when instantiating a generic lambda!");
11620     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
11621   }
11622   else
11623     // Enter a new function scope
11624     PushFunctionScope();
11625 
11626   // Builtin functions cannot be defined.
11627   if (unsigned BuiltinID = FD->getBuiltinID()) {
11628     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
11629         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
11630       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
11631       FD->setInvalidDecl();
11632     }
11633   }
11634 
11635   // The return type of a function definition must be complete
11636   // (C99 6.9.1p3, C++ [dcl.fct]p6).
11637   QualType ResultType = FD->getReturnType();
11638   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
11639       !FD->isInvalidDecl() &&
11640       RequireCompleteType(FD->getLocation(), ResultType,
11641                           diag::err_func_def_incomplete_result))
11642     FD->setInvalidDecl();
11643 
11644   if (FnBodyScope)
11645     PushDeclContext(FnBodyScope, FD);
11646 
11647   // Check the validity of our function parameters
11648   CheckParmsForFunctionDef(FD->parameters(),
11649                            /*CheckParameterNames=*/true);
11650 
11651   // Add non-parameter declarations already in the function to the current
11652   // scope.
11653   if (FnBodyScope) {
11654     for (Decl *NPD : FD->decls()) {
11655       auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
11656       if (!NonParmDecl)
11657         continue;
11658       assert(!isa<ParmVarDecl>(NonParmDecl) &&
11659              "parameters should not be in newly created FD yet");
11660 
11661       // If the decl has a name, make it accessible in the current scope.
11662       if (NonParmDecl->getDeclName())
11663         PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
11664 
11665       // Similarly, dive into enums and fish their constants out, making them
11666       // accessible in this scope.
11667       if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
11668         for (auto *EI : ED->enumerators())
11669           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
11670       }
11671     }
11672   }
11673 
11674   // Introduce our parameters into the function scope
11675   for (auto Param : FD->parameters()) {
11676     Param->setOwningFunction(FD);
11677 
11678     // If this has an identifier, add it to the scope stack.
11679     if (Param->getIdentifier() && FnBodyScope) {
11680       CheckShadow(FnBodyScope, Param);
11681 
11682       PushOnScopeChains(Param, FnBodyScope);
11683     }
11684   }
11685 
11686   // Ensure that the function's exception specification is instantiated.
11687   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
11688     ResolveExceptionSpec(D->getLocation(), FPT);
11689 
11690   // dllimport cannot be applied to non-inline function definitions.
11691   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
11692       !FD->isTemplateInstantiation()) {
11693     assert(!FD->hasAttr<DLLExportAttr>());
11694     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
11695     FD->setInvalidDecl();
11696     return D;
11697   }
11698   // We want to attach documentation to original Decl (which might be
11699   // a function template).
11700   ActOnDocumentableDecl(D);
11701   if (getCurLexicalContext()->isObjCContainer() &&
11702       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
11703       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
11704     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
11705 
11706   return D;
11707 }
11708 
11709 /// \brief Given the set of return statements within a function body,
11710 /// compute the variables that are subject to the named return value
11711 /// optimization.
11712 ///
11713 /// Each of the variables that is subject to the named return value
11714 /// optimization will be marked as NRVO variables in the AST, and any
11715 /// return statement that has a marked NRVO variable as its NRVO candidate can
11716 /// use the named return value optimization.
11717 ///
11718 /// This function applies a very simplistic algorithm for NRVO: if every return
11719 /// statement in the scope of a variable has the same NRVO candidate, that
11720 /// candidate is an NRVO variable.
11721 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
11722   ReturnStmt **Returns = Scope->Returns.data();
11723 
11724   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
11725     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
11726       if (!NRVOCandidate->isNRVOVariable())
11727         Returns[I]->setNRVOCandidate(nullptr);
11728     }
11729   }
11730 }
11731 
11732 bool Sema::canDelayFunctionBody(const Declarator &D) {
11733   // We can't delay parsing the body of a constexpr function template (yet).
11734   if (D.getDeclSpec().isConstexprSpecified())
11735     return false;
11736 
11737   // We can't delay parsing the body of a function template with a deduced
11738   // return type (yet).
11739   if (D.getDeclSpec().containsPlaceholderType()) {
11740     // If the placeholder introduces a non-deduced trailing return type,
11741     // we can still delay parsing it.
11742     if (D.getNumTypeObjects()) {
11743       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11744       if (Outer.Kind == DeclaratorChunk::Function &&
11745           Outer.Fun.hasTrailingReturnType()) {
11746         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11747         return Ty.isNull() || !Ty->isUndeducedType();
11748       }
11749     }
11750     return false;
11751   }
11752 
11753   return true;
11754 }
11755 
11756 bool Sema::canSkipFunctionBody(Decl *D) {
11757   // We cannot skip the body of a function (or function template) which is
11758   // constexpr, since we may need to evaluate its body in order to parse the
11759   // rest of the file.
11760   // We cannot skip the body of a function with an undeduced return type,
11761   // because any callers of that function need to know the type.
11762   if (const FunctionDecl *FD = D->getAsFunction())
11763     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11764       return false;
11765   return Consumer.shouldSkipFunctionBody(D);
11766 }
11767 
11768 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11769   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11770     FD->setHasSkippedBody();
11771   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11772     MD->setHasSkippedBody();
11773   return Decl;
11774 }
11775 
11776 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11777   return ActOnFinishFunctionBody(D, BodyArg, false);
11778 }
11779 
11780 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
11781                                     bool IsInstantiation) {
11782   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
11783 
11784   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11785   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
11786 
11787   if (getLangOpts().CoroutinesTS && !getCurFunction()->CoroutineStmts.empty())
11788     CheckCompletedCoroutineBody(FD, Body);
11789 
11790   if (FD) {
11791     FD->setBody(Body);
11792 
11793     if (getLangOpts().CPlusPlus14) {
11794       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
11795           FD->getReturnType()->isUndeducedType()) {
11796         // If the function has a deduced result type but contains no 'return'
11797         // statements, the result type as written must be exactly 'auto', and
11798         // the deduced result type is 'void'.
11799         if (!FD->getReturnType()->getAs<AutoType>()) {
11800           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
11801               << FD->getReturnType();
11802           FD->setInvalidDecl();
11803         } else {
11804           // Substitute 'void' for the 'auto' in the type.
11805           TypeLoc ResultType = getReturnTypeLoc(FD);
11806           Context.adjustDeducedFunctionResultType(
11807               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
11808         }
11809       }
11810     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
11811       // In C++11, we don't use 'auto' deduction rules for lambda call
11812       // operators because we don't support return type deduction.
11813       auto *LSI = getCurLambda();
11814       if (LSI->HasImplicitReturnType) {
11815         deduceClosureReturnType(*LSI);
11816 
11817         // C++11 [expr.prim.lambda]p4:
11818         //   [...] if there are no return statements in the compound-statement
11819         //   [the deduced type is] the type void
11820         QualType RetType =
11821             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
11822 
11823         // Update the return type to the deduced type.
11824         const FunctionProtoType *Proto =
11825             FD->getType()->getAs<FunctionProtoType>();
11826         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
11827                                             Proto->getExtProtoInfo()));
11828       }
11829     }
11830 
11831     // The only way to be included in UndefinedButUsed is if there is an
11832     // ODR use before the definition. Avoid the expensive map lookup if this
11833     // is the first declaration.
11834     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
11835       if (!FD->isExternallyVisible())
11836         UndefinedButUsed.erase(FD);
11837       else if (FD->isInlined() &&
11838                !LangOpts.GNUInline &&
11839                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
11840         UndefinedButUsed.erase(FD);
11841     }
11842 
11843     // If the function implicitly returns zero (like 'main') or is naked,
11844     // don't complain about missing return statements.
11845     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
11846       WP.disableCheckFallThrough();
11847 
11848     // MSVC permits the use of pure specifier (=0) on function definition,
11849     // defined at class scope, warn about this non-standard construct.
11850     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
11851       Diag(FD->getLocation(), diag::ext_pure_function_definition);
11852 
11853     if (!FD->isInvalidDecl()) {
11854       // Don't diagnose unused parameters of defaulted or deleted functions.
11855       if (!FD->isDeleted() && !FD->isDefaulted())
11856         DiagnoseUnusedParameters(FD->parameters());
11857       DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
11858                                              FD->getReturnType(), FD);
11859 
11860       // If this is a structor, we need a vtable.
11861       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
11862         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
11863       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
11864         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
11865 
11866       // Try to apply the named return value optimization. We have to check
11867       // if we can do this here because lambdas keep return statements around
11868       // to deduce an implicit return type.
11869       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
11870           !FD->isDependentContext())
11871         computeNRVO(Body, getCurFunction());
11872     }
11873 
11874     // GNU warning -Wmissing-prototypes:
11875     //   Warn if a global function is defined without a previous
11876     //   prototype declaration. This warning is issued even if the
11877     //   definition itself provides a prototype. The aim is to detect
11878     //   global functions that fail to be declared in header files.
11879     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
11880     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
11881       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
11882 
11883       if (PossibleZeroParamPrototype) {
11884         // We found a declaration that is not a prototype,
11885         // but that could be a zero-parameter prototype
11886         if (TypeSourceInfo *TI =
11887                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
11888           TypeLoc TL = TI->getTypeLoc();
11889           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
11890             Diag(PossibleZeroParamPrototype->getLocation(),
11891                  diag::note_declaration_not_a_prototype)
11892                 << PossibleZeroParamPrototype
11893                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
11894         }
11895       }
11896 
11897       // GNU warning -Wstrict-prototypes
11898       //   Warn if K&R function is defined without a previous declaration.
11899       //   This warning is issued only if the definition itself does not provide
11900       //   a prototype. Only K&R definitions do not provide a prototype.
11901       //   An empty list in a function declarator that is part of a definition
11902       //   of that function specifies that the function has no parameters
11903       //   (C99 6.7.5.3p14)
11904       if (!FD->hasWrittenPrototype() && FD->getNumParams() > 0 &&
11905           !LangOpts.CPlusPlus) {
11906         TypeSourceInfo *TI = FD->getTypeSourceInfo();
11907         TypeLoc TL = TI->getTypeLoc();
11908         FunctionTypeLoc FTL = TL.castAs<FunctionTypeLoc>();
11909         Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 1;
11910       }
11911     }
11912 
11913     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11914       const CXXMethodDecl *KeyFunction;
11915       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
11916           MD->isVirtual() &&
11917           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
11918           MD == KeyFunction->getCanonicalDecl()) {
11919         // Update the key-function state if necessary for this ABI.
11920         if (FD->isInlined() &&
11921             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11922           Context.setNonKeyFunction(MD);
11923 
11924           // If the newly-chosen key function is already defined, then we
11925           // need to mark the vtable as used retroactively.
11926           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
11927           const FunctionDecl *Definition;
11928           if (KeyFunction && KeyFunction->isDefined(Definition))
11929             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
11930         } else {
11931           // We just defined they key function; mark the vtable as used.
11932           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
11933         }
11934       }
11935     }
11936 
11937     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
11938            "Function parsing confused");
11939   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
11940     assert(MD == getCurMethodDecl() && "Method parsing confused");
11941     MD->setBody(Body);
11942     if (!MD->isInvalidDecl()) {
11943       DiagnoseUnusedParameters(MD->parameters());
11944       DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
11945                                              MD->getReturnType(), MD);
11946 
11947       if (Body)
11948         computeNRVO(Body, getCurFunction());
11949     }
11950     if (getCurFunction()->ObjCShouldCallSuper) {
11951       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
11952         << MD->getSelector().getAsString();
11953       getCurFunction()->ObjCShouldCallSuper = false;
11954     }
11955     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
11956       const ObjCMethodDecl *InitMethod = nullptr;
11957       bool isDesignated =
11958           MD->isDesignatedInitializerForTheInterface(&InitMethod);
11959       assert(isDesignated && InitMethod);
11960       (void)isDesignated;
11961 
11962       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
11963         auto IFace = MD->getClassInterface();
11964         if (!IFace)
11965           return false;
11966         auto SuperD = IFace->getSuperClass();
11967         if (!SuperD)
11968           return false;
11969         return SuperD->getIdentifier() ==
11970             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
11971       };
11972       // Don't issue this warning for unavailable inits or direct subclasses
11973       // of NSObject.
11974       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
11975         Diag(MD->getLocation(),
11976              diag::warn_objc_designated_init_missing_super_call);
11977         Diag(InitMethod->getLocation(),
11978              diag::note_objc_designated_init_marked_here);
11979       }
11980       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
11981     }
11982     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
11983       // Don't issue this warning for unavaialable inits.
11984       if (!MD->isUnavailable())
11985         Diag(MD->getLocation(),
11986              diag::warn_objc_secondary_init_missing_init_call);
11987       getCurFunction()->ObjCWarnForNoInitDelegation = false;
11988     }
11989   } else {
11990     return nullptr;
11991   }
11992 
11993   if (Body && getCurFunction()->HasPotentialAvailabilityViolations)
11994     DiagnoseUnguardedAvailabilityViolations(dcl);
11995 
11996   assert(!getCurFunction()->ObjCShouldCallSuper &&
11997          "This should only be set for ObjC methods, which should have been "
11998          "handled in the block above.");
11999 
12000   // Verify and clean out per-function state.
12001   if (Body && (!FD || !FD->isDefaulted())) {
12002     // C++ constructors that have function-try-blocks can't have return
12003     // statements in the handlers of that block. (C++ [except.handle]p14)
12004     // Verify this.
12005     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
12006       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
12007 
12008     // Verify that gotos and switch cases don't jump into scopes illegally.
12009     if (getCurFunction()->NeedsScopeChecking() &&
12010         !PP.isCodeCompletionEnabled())
12011       DiagnoseInvalidJumps(Body);
12012 
12013     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
12014       if (!Destructor->getParent()->isDependentType())
12015         CheckDestructor(Destructor);
12016 
12017       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
12018                                              Destructor->getParent());
12019     }
12020 
12021     // If any errors have occurred, clear out any temporaries that may have
12022     // been leftover. This ensures that these temporaries won't be picked up for
12023     // deletion in some later function.
12024     if (getDiagnostics().hasErrorOccurred() ||
12025         getDiagnostics().getSuppressAllDiagnostics()) {
12026       DiscardCleanupsInEvaluationContext();
12027     }
12028     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
12029         !isa<FunctionTemplateDecl>(dcl)) {
12030       // Since the body is valid, issue any analysis-based warnings that are
12031       // enabled.
12032       ActivePolicy = &WP;
12033     }
12034 
12035     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
12036         (!CheckConstexprFunctionDecl(FD) ||
12037          !CheckConstexprFunctionBody(FD, Body)))
12038       FD->setInvalidDecl();
12039 
12040     if (FD && FD->hasAttr<NakedAttr>()) {
12041       for (const Stmt *S : Body->children()) {
12042         // Allow local register variables without initializer as they don't
12043         // require prologue.
12044         bool RegisterVariables = false;
12045         if (auto *DS = dyn_cast<DeclStmt>(S)) {
12046           for (const auto *Decl : DS->decls()) {
12047             if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
12048               RegisterVariables =
12049                   Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
12050               if (!RegisterVariables)
12051                 break;
12052             }
12053           }
12054         }
12055         if (RegisterVariables)
12056           continue;
12057         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
12058           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
12059           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
12060           FD->setInvalidDecl();
12061           break;
12062         }
12063       }
12064     }
12065 
12066     assert(ExprCleanupObjects.size() ==
12067                ExprEvalContexts.back().NumCleanupObjects &&
12068            "Leftover temporaries in function");
12069     assert(!Cleanup.exprNeedsCleanups() && "Unaccounted cleanups in function");
12070     assert(MaybeODRUseExprs.empty() &&
12071            "Leftover expressions for odr-use checking");
12072   }
12073 
12074   if (!IsInstantiation)
12075     PopDeclContext();
12076 
12077   PopFunctionScopeInfo(ActivePolicy, dcl);
12078   // If any errors have occurred, clear out any temporaries that may have
12079   // been leftover. This ensures that these temporaries won't be picked up for
12080   // deletion in some later function.
12081   if (getDiagnostics().hasErrorOccurred()) {
12082     DiscardCleanupsInEvaluationContext();
12083   }
12084 
12085   return dcl;
12086 }
12087 
12088 /// When we finish delayed parsing of an attribute, we must attach it to the
12089 /// relevant Decl.
12090 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
12091                                        ParsedAttributes &Attrs) {
12092   // Always attach attributes to the underlying decl.
12093   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
12094     D = TD->getTemplatedDecl();
12095   ProcessDeclAttributeList(S, D, Attrs.getList());
12096 
12097   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
12098     if (Method->isStatic())
12099       checkThisInStaticMemberFunctionAttributes(Method);
12100 }
12101 
12102 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
12103 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
12104 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
12105                                           IdentifierInfo &II, Scope *S) {
12106   // Before we produce a declaration for an implicitly defined
12107   // function, see whether there was a locally-scoped declaration of
12108   // this name as a function or variable. If so, use that
12109   // (non-visible) declaration, and complain about it.
12110   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
12111     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
12112     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
12113     return ExternCPrev;
12114   }
12115 
12116   // Extension in C99.  Legal in C90, but warn about it.
12117   unsigned diag_id;
12118   if (II.getName().startswith("__builtin_"))
12119     diag_id = diag::warn_builtin_unknown;
12120   else if (getLangOpts().C99)
12121     diag_id = diag::ext_implicit_function_decl;
12122   else
12123     diag_id = diag::warn_implicit_function_decl;
12124   Diag(Loc, diag_id) << &II;
12125 
12126   // Because typo correction is expensive, only do it if the implicit
12127   // function declaration is going to be treated as an error.
12128   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
12129     TypoCorrection Corrected;
12130     if (S &&
12131         (Corrected = CorrectTypo(
12132              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
12133              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
12134       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
12135                    /*ErrorRecovery*/false);
12136   }
12137 
12138   // Set a Declarator for the implicit definition: int foo();
12139   const char *Dummy;
12140   AttributeFactory attrFactory;
12141   DeclSpec DS(attrFactory);
12142   unsigned DiagID;
12143   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
12144                                   Context.getPrintingPolicy());
12145   (void)Error; // Silence warning.
12146   assert(!Error && "Error setting up implicit decl!");
12147   SourceLocation NoLoc;
12148   Declarator D(DS, Declarator::BlockContext);
12149   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
12150                                              /*IsAmbiguous=*/false,
12151                                              /*LParenLoc=*/NoLoc,
12152                                              /*Params=*/nullptr,
12153                                              /*NumParams=*/0,
12154                                              /*EllipsisLoc=*/NoLoc,
12155                                              /*RParenLoc=*/NoLoc,
12156                                              /*TypeQuals=*/0,
12157                                              /*RefQualifierIsLvalueRef=*/true,
12158                                              /*RefQualifierLoc=*/NoLoc,
12159                                              /*ConstQualifierLoc=*/NoLoc,
12160                                              /*VolatileQualifierLoc=*/NoLoc,
12161                                              /*RestrictQualifierLoc=*/NoLoc,
12162                                              /*MutableLoc=*/NoLoc,
12163                                              EST_None,
12164                                              /*ESpecRange=*/SourceRange(),
12165                                              /*Exceptions=*/nullptr,
12166                                              /*ExceptionRanges=*/nullptr,
12167                                              /*NumExceptions=*/0,
12168                                              /*NoexceptExpr=*/nullptr,
12169                                              /*ExceptionSpecTokens=*/nullptr,
12170                                              /*DeclsInPrototype=*/None,
12171                                              Loc, Loc, D),
12172                 DS.getAttributes(),
12173                 SourceLocation());
12174   D.SetIdentifier(&II, Loc);
12175 
12176   // Insert this function into translation-unit scope.
12177 
12178   DeclContext *PrevDC = CurContext;
12179   CurContext = Context.getTranslationUnitDecl();
12180 
12181   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
12182   FD->setImplicit();
12183 
12184   CurContext = PrevDC;
12185 
12186   AddKnownFunctionAttributes(FD);
12187 
12188   return FD;
12189 }
12190 
12191 /// \brief Adds any function attributes that we know a priori based on
12192 /// the declaration of this function.
12193 ///
12194 /// These attributes can apply both to implicitly-declared builtins
12195 /// (like __builtin___printf_chk) or to library-declared functions
12196 /// like NSLog or printf.
12197 ///
12198 /// We need to check for duplicate attributes both here and where user-written
12199 /// attributes are applied to declarations.
12200 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
12201   if (FD->isInvalidDecl())
12202     return;
12203 
12204   // If this is a built-in function, map its builtin attributes to
12205   // actual attributes.
12206   if (unsigned BuiltinID = FD->getBuiltinID()) {
12207     // Handle printf-formatting attributes.
12208     unsigned FormatIdx;
12209     bool HasVAListArg;
12210     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
12211       if (!FD->hasAttr<FormatAttr>()) {
12212         const char *fmt = "printf";
12213         unsigned int NumParams = FD->getNumParams();
12214         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
12215             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
12216           fmt = "NSString";
12217         FD->addAttr(FormatAttr::CreateImplicit(Context,
12218                                                &Context.Idents.get(fmt),
12219                                                FormatIdx+1,
12220                                                HasVAListArg ? 0 : FormatIdx+2,
12221                                                FD->getLocation()));
12222       }
12223     }
12224     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
12225                                              HasVAListArg)) {
12226      if (!FD->hasAttr<FormatAttr>())
12227        FD->addAttr(FormatAttr::CreateImplicit(Context,
12228                                               &Context.Idents.get("scanf"),
12229                                               FormatIdx+1,
12230                                               HasVAListArg ? 0 : FormatIdx+2,
12231                                               FD->getLocation()));
12232     }
12233 
12234     // Mark const if we don't care about errno and that is the only
12235     // thing preventing the function from being const. This allows
12236     // IRgen to use LLVM intrinsics for such functions.
12237     if (!getLangOpts().MathErrno &&
12238         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
12239       if (!FD->hasAttr<ConstAttr>())
12240         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12241     }
12242 
12243     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
12244         !FD->hasAttr<ReturnsTwiceAttr>())
12245       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
12246                                          FD->getLocation()));
12247     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
12248       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12249     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
12250       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
12251     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
12252       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
12253     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
12254         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
12255       // Add the appropriate attribute, depending on the CUDA compilation mode
12256       // and which target the builtin belongs to. For example, during host
12257       // compilation, aux builtins are __device__, while the rest are __host__.
12258       if (getLangOpts().CUDAIsDevice !=
12259           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
12260         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
12261       else
12262         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
12263     }
12264   }
12265 
12266   // If C++ exceptions are enabled but we are told extern "C" functions cannot
12267   // throw, add an implicit nothrow attribute to any extern "C" function we come
12268   // across.
12269   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
12270       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
12271     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
12272     if (!FPT || FPT->getExceptionSpecType() == EST_None)
12273       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
12274   }
12275 
12276   IdentifierInfo *Name = FD->getIdentifier();
12277   if (!Name)
12278     return;
12279   if ((!getLangOpts().CPlusPlus &&
12280        FD->getDeclContext()->isTranslationUnit()) ||
12281       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
12282        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
12283        LinkageSpecDecl::lang_c)) {
12284     // Okay: this could be a libc/libm/Objective-C function we know
12285     // about.
12286   } else
12287     return;
12288 
12289   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
12290     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
12291     // target-specific builtins, perhaps?
12292     if (!FD->hasAttr<FormatAttr>())
12293       FD->addAttr(FormatAttr::CreateImplicit(Context,
12294                                              &Context.Idents.get("printf"), 2,
12295                                              Name->isStr("vasprintf") ? 0 : 3,
12296                                              FD->getLocation()));
12297   }
12298 
12299   if (Name->isStr("__CFStringMakeConstantString")) {
12300     // We already have a __builtin___CFStringMakeConstantString,
12301     // but builds that use -fno-constant-cfstrings don't go through that.
12302     if (!FD->hasAttr<FormatArgAttr>())
12303       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
12304                                                 FD->getLocation()));
12305   }
12306 }
12307 
12308 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
12309                                     TypeSourceInfo *TInfo) {
12310   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
12311   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
12312 
12313   if (!TInfo) {
12314     assert(D.isInvalidType() && "no declarator info for valid type");
12315     TInfo = Context.getTrivialTypeSourceInfo(T);
12316   }
12317 
12318   // Scope manipulation handled by caller.
12319   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
12320                                            D.getLocStart(),
12321                                            D.getIdentifierLoc(),
12322                                            D.getIdentifier(),
12323                                            TInfo);
12324 
12325   // Bail out immediately if we have an invalid declaration.
12326   if (D.isInvalidType()) {
12327     NewTD->setInvalidDecl();
12328     return NewTD;
12329   }
12330 
12331   if (D.getDeclSpec().isModulePrivateSpecified()) {
12332     if (CurContext->isFunctionOrMethod())
12333       Diag(NewTD->getLocation(), diag::err_module_private_local)
12334         << 2 << NewTD->getDeclName()
12335         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
12336         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
12337     else
12338       NewTD->setModulePrivate();
12339   }
12340 
12341   // C++ [dcl.typedef]p8:
12342   //   If the typedef declaration defines an unnamed class (or
12343   //   enum), the first typedef-name declared by the declaration
12344   //   to be that class type (or enum type) is used to denote the
12345   //   class type (or enum type) for linkage purposes only.
12346   // We need to check whether the type was declared in the declaration.
12347   switch (D.getDeclSpec().getTypeSpecType()) {
12348   case TST_enum:
12349   case TST_struct:
12350   case TST_interface:
12351   case TST_union:
12352   case TST_class: {
12353     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
12354     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
12355     break;
12356   }
12357 
12358   default:
12359     break;
12360   }
12361 
12362   return NewTD;
12363 }
12364 
12365 /// \brief Check that this is a valid underlying type for an enum declaration.
12366 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
12367   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
12368   QualType T = TI->getType();
12369 
12370   if (T->isDependentType())
12371     return false;
12372 
12373   if (const BuiltinType *BT = T->getAs<BuiltinType>())
12374     if (BT->isInteger())
12375       return false;
12376 
12377   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
12378   return true;
12379 }
12380 
12381 /// Check whether this is a valid redeclaration of a previous enumeration.
12382 /// \return true if the redeclaration was invalid.
12383 bool Sema::CheckEnumRedeclaration(
12384     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
12385     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
12386   bool IsFixed = !EnumUnderlyingTy.isNull();
12387 
12388   if (IsScoped != Prev->isScoped()) {
12389     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
12390       << Prev->isScoped();
12391     Diag(Prev->getLocation(), diag::note_previous_declaration);
12392     return true;
12393   }
12394 
12395   if (IsFixed && Prev->isFixed()) {
12396     if (!EnumUnderlyingTy->isDependentType() &&
12397         !Prev->getIntegerType()->isDependentType() &&
12398         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
12399                                         Prev->getIntegerType())) {
12400       // TODO: Highlight the underlying type of the redeclaration.
12401       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
12402         << EnumUnderlyingTy << Prev->getIntegerType();
12403       Diag(Prev->getLocation(), diag::note_previous_declaration)
12404           << Prev->getIntegerTypeRange();
12405       return true;
12406     }
12407   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
12408     ;
12409   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
12410     ;
12411   } else if (IsFixed != Prev->isFixed()) {
12412     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
12413       << Prev->isFixed();
12414     Diag(Prev->getLocation(), diag::note_previous_declaration);
12415     return true;
12416   }
12417 
12418   return false;
12419 }
12420 
12421 /// \brief Get diagnostic %select index for tag kind for
12422 /// redeclaration diagnostic message.
12423 /// WARNING: Indexes apply to particular diagnostics only!
12424 ///
12425 /// \returns diagnostic %select index.
12426 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12427   switch (Tag) {
12428   case TTK_Struct: return 0;
12429   case TTK_Interface: return 1;
12430   case TTK_Class:  return 2;
12431   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12432   }
12433 }
12434 
12435 /// \brief Determine if tag kind is a class-key compatible with
12436 /// class for redeclaration (class, struct, or __interface).
12437 ///
12438 /// \returns true iff the tag kind is compatible.
12439 static bool isClassCompatTagKind(TagTypeKind Tag)
12440 {
12441   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12442 }
12443 
12444 Sema::NonTagKind Sema::getNonTagTypeDeclKind(const Decl *PrevDecl,
12445                                              TagTypeKind TTK) {
12446   if (isa<TypedefDecl>(PrevDecl))
12447     return NTK_Typedef;
12448   else if (isa<TypeAliasDecl>(PrevDecl))
12449     return NTK_TypeAlias;
12450   else if (isa<ClassTemplateDecl>(PrevDecl))
12451     return NTK_Template;
12452   else if (isa<TypeAliasTemplateDecl>(PrevDecl))
12453     return NTK_TypeAliasTemplate;
12454   else if (isa<TemplateTemplateParmDecl>(PrevDecl))
12455     return NTK_TemplateTemplateArgument;
12456   switch (TTK) {
12457   case TTK_Struct:
12458   case TTK_Interface:
12459   case TTK_Class:
12460     return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
12461   case TTK_Union:
12462     return NTK_NonUnion;
12463   case TTK_Enum:
12464     return NTK_NonEnum;
12465   }
12466   llvm_unreachable("invalid TTK");
12467 }
12468 
12469 /// \brief Determine whether a tag with a given kind is acceptable
12470 /// as a redeclaration of the given tag declaration.
12471 ///
12472 /// \returns true if the new tag kind is acceptable, false otherwise.
12473 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12474                                         TagTypeKind NewTag, bool isDefinition,
12475                                         SourceLocation NewTagLoc,
12476                                         const IdentifierInfo *Name) {
12477   // C++ [dcl.type.elab]p3:
12478   //   The class-key or enum keyword present in the
12479   //   elaborated-type-specifier shall agree in kind with the
12480   //   declaration to which the name in the elaborated-type-specifier
12481   //   refers. This rule also applies to the form of
12482   //   elaborated-type-specifier that declares a class-name or
12483   //   friend class since it can be construed as referring to the
12484   //   definition of the class. Thus, in any
12485   //   elaborated-type-specifier, the enum keyword shall be used to
12486   //   refer to an enumeration (7.2), the union class-key shall be
12487   //   used to refer to a union (clause 9), and either the class or
12488   //   struct class-key shall be used to refer to a class (clause 9)
12489   //   declared using the class or struct class-key.
12490   TagTypeKind OldTag = Previous->getTagKind();
12491   if (!isDefinition || !isClassCompatTagKind(NewTag))
12492     if (OldTag == NewTag)
12493       return true;
12494 
12495   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
12496     // Warn about the struct/class tag mismatch.
12497     bool isTemplate = false;
12498     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
12499       isTemplate = Record->getDescribedClassTemplate();
12500 
12501     if (!ActiveTemplateInstantiations.empty()) {
12502       // In a template instantiation, do not offer fix-its for tag mismatches
12503       // since they usually mess up the template instead of fixing the problem.
12504       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12505         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12506         << getRedeclDiagFromTagKind(OldTag);
12507       return true;
12508     }
12509 
12510     if (isDefinition) {
12511       // On definitions, check previous tags and issue a fix-it for each
12512       // one that doesn't match the current tag.
12513       if (Previous->getDefinition()) {
12514         // Don't suggest fix-its for redefinitions.
12515         return true;
12516       }
12517 
12518       bool previousMismatch = false;
12519       for (auto I : Previous->redecls()) {
12520         if (I->getTagKind() != NewTag) {
12521           if (!previousMismatch) {
12522             previousMismatch = true;
12523             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
12524               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12525               << getRedeclDiagFromTagKind(I->getTagKind());
12526           }
12527           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
12528             << getRedeclDiagFromTagKind(NewTag)
12529             << FixItHint::CreateReplacement(I->getInnerLocStart(),
12530                  TypeWithKeyword::getTagTypeKindName(NewTag));
12531         }
12532       }
12533       return true;
12534     }
12535 
12536     // Check for a previous definition.  If current tag and definition
12537     // are same type, do nothing.  If no definition, but disagree with
12538     // with previous tag type, give a warning, but no fix-it.
12539     const TagDecl *Redecl = Previous->getDefinition() ?
12540                             Previous->getDefinition() : Previous;
12541     if (Redecl->getTagKind() == NewTag) {
12542       return true;
12543     }
12544 
12545     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12546       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12547       << getRedeclDiagFromTagKind(OldTag);
12548     Diag(Redecl->getLocation(), diag::note_previous_use);
12549 
12550     // If there is a previous definition, suggest a fix-it.
12551     if (Previous->getDefinition()) {
12552         Diag(NewTagLoc, diag::note_struct_class_suggestion)
12553           << getRedeclDiagFromTagKind(Redecl->getTagKind())
12554           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
12555                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
12556     }
12557 
12558     return true;
12559   }
12560   return false;
12561 }
12562 
12563 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
12564 /// from an outer enclosing namespace or file scope inside a friend declaration.
12565 /// This should provide the commented out code in the following snippet:
12566 ///   namespace N {
12567 ///     struct X;
12568 ///     namespace M {
12569 ///       struct Y { friend struct /*N::*/ X; };
12570 ///     }
12571 ///   }
12572 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
12573                                          SourceLocation NameLoc) {
12574   // While the decl is in a namespace, do repeated lookup of that name and see
12575   // if we get the same namespace back.  If we do not, continue until
12576   // translation unit scope, at which point we have a fully qualified NNS.
12577   SmallVector<IdentifierInfo *, 4> Namespaces;
12578   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12579   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
12580     // This tag should be declared in a namespace, which can only be enclosed by
12581     // other namespaces.  Bail if there's an anonymous namespace in the chain.
12582     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
12583     if (!Namespace || Namespace->isAnonymousNamespace())
12584       return FixItHint();
12585     IdentifierInfo *II = Namespace->getIdentifier();
12586     Namespaces.push_back(II);
12587     NamedDecl *Lookup = SemaRef.LookupSingleName(
12588         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
12589     if (Lookup == Namespace)
12590       break;
12591   }
12592 
12593   // Once we have all the namespaces, reverse them to go outermost first, and
12594   // build an NNS.
12595   SmallString<64> Insertion;
12596   llvm::raw_svector_ostream OS(Insertion);
12597   if (DC->isTranslationUnit())
12598     OS << "::";
12599   std::reverse(Namespaces.begin(), Namespaces.end());
12600   for (auto *II : Namespaces)
12601     OS << II->getName() << "::";
12602   return FixItHint::CreateInsertion(NameLoc, Insertion);
12603 }
12604 
12605 /// \brief Determine whether a tag originally declared in context \p OldDC can
12606 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
12607 /// found a declaration in \p OldDC as a previous decl, perhaps through a
12608 /// using-declaration).
12609 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
12610                                          DeclContext *NewDC) {
12611   OldDC = OldDC->getRedeclContext();
12612   NewDC = NewDC->getRedeclContext();
12613 
12614   if (OldDC->Equals(NewDC))
12615     return true;
12616 
12617   // In MSVC mode, we allow a redeclaration if the contexts are related (either
12618   // encloses the other).
12619   if (S.getLangOpts().MSVCCompat &&
12620       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
12621     return true;
12622 
12623   return false;
12624 }
12625 
12626 /// Find the DeclContext in which a tag is implicitly declared if we see an
12627 /// elaborated type specifier in the specified context, and lookup finds
12628 /// nothing.
12629 static DeclContext *getTagInjectionContext(DeclContext *DC) {
12630   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
12631     DC = DC->getParent();
12632   return DC;
12633 }
12634 
12635 /// Find the Scope in which a tag is implicitly declared if we see an
12636 /// elaborated type specifier in the specified context, and lookup finds
12637 /// nothing.
12638 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
12639   while (S->isClassScope() ||
12640          (LangOpts.CPlusPlus &&
12641           S->isFunctionPrototypeScope()) ||
12642          ((S->getFlags() & Scope::DeclScope) == 0) ||
12643          (S->getEntity() && S->getEntity()->isTransparentContext()))
12644     S = S->getParent();
12645   return S;
12646 }
12647 
12648 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
12649 /// former case, Name will be non-null.  In the later case, Name will be null.
12650 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
12651 /// reference/declaration/definition of a tag.
12652 ///
12653 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
12654 /// trailing-type-specifier) other than one in an alias-declaration.
12655 ///
12656 /// \param SkipBody If non-null, will be set to indicate if the caller should
12657 /// skip the definition of this tag and treat it as if it were a declaration.
12658 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12659                      SourceLocation KWLoc, CXXScopeSpec &SS,
12660                      IdentifierInfo *Name, SourceLocation NameLoc,
12661                      AttributeList *Attr, AccessSpecifier AS,
12662                      SourceLocation ModulePrivateLoc,
12663                      MultiTemplateParamsArg TemplateParameterLists,
12664                      bool &OwnedDecl, bool &IsDependent,
12665                      SourceLocation ScopedEnumKWLoc,
12666                      bool ScopedEnumUsesClassTag,
12667                      TypeResult UnderlyingType,
12668                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
12669   // If this is not a definition, it must have a name.
12670   IdentifierInfo *OrigName = Name;
12671   assert((Name != nullptr || TUK == TUK_Definition) &&
12672          "Nameless record must be a definition!");
12673   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
12674 
12675   OwnedDecl = false;
12676   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12677   bool ScopedEnum = ScopedEnumKWLoc.isValid();
12678 
12679   // FIXME: Check explicit specializations more carefully.
12680   bool isExplicitSpecialization = false;
12681   bool Invalid = false;
12682 
12683   // We only need to do this matching if we have template parameters
12684   // or a scope specifier, which also conveniently avoids this work
12685   // for non-C++ cases.
12686   if (TemplateParameterLists.size() > 0 ||
12687       (SS.isNotEmpty() && TUK != TUK_Reference)) {
12688     if (TemplateParameterList *TemplateParams =
12689             MatchTemplateParametersToScopeSpecifier(
12690                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
12691                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
12692       if (Kind == TTK_Enum) {
12693         Diag(KWLoc, diag::err_enum_template);
12694         return nullptr;
12695       }
12696 
12697       if (TemplateParams->size() > 0) {
12698         // This is a declaration or definition of a class template (which may
12699         // be a member of another template).
12700 
12701         if (Invalid)
12702           return nullptr;
12703 
12704         OwnedDecl = false;
12705         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
12706                                                SS, Name, NameLoc, Attr,
12707                                                TemplateParams, AS,
12708                                                ModulePrivateLoc,
12709                                                /*FriendLoc*/SourceLocation(),
12710                                                TemplateParameterLists.size()-1,
12711                                                TemplateParameterLists.data(),
12712                                                SkipBody);
12713         return Result.get();
12714       } else {
12715         // The "template<>" header is extraneous.
12716         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12717           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12718         isExplicitSpecialization = true;
12719       }
12720     }
12721   }
12722 
12723   // Figure out the underlying type if this a enum declaration. We need to do
12724   // this early, because it's needed to detect if this is an incompatible
12725   // redeclaration.
12726   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
12727   bool EnumUnderlyingIsImplicit = false;
12728 
12729   if (Kind == TTK_Enum) {
12730     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
12731       // No underlying type explicitly specified, or we failed to parse the
12732       // type, default to int.
12733       EnumUnderlying = Context.IntTy.getTypePtr();
12734     else if (UnderlyingType.get()) {
12735       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
12736       // integral type; any cv-qualification is ignored.
12737       TypeSourceInfo *TI = nullptr;
12738       GetTypeFromParser(UnderlyingType.get(), &TI);
12739       EnumUnderlying = TI;
12740 
12741       if (CheckEnumUnderlyingType(TI))
12742         // Recover by falling back to int.
12743         EnumUnderlying = Context.IntTy.getTypePtr();
12744 
12745       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
12746                                           UPPC_FixedUnderlyingType))
12747         EnumUnderlying = Context.IntTy.getTypePtr();
12748 
12749     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12750       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
12751         // Microsoft enums are always of int type.
12752         EnumUnderlying = Context.IntTy.getTypePtr();
12753         EnumUnderlyingIsImplicit = true;
12754       }
12755     }
12756   }
12757 
12758   DeclContext *SearchDC = CurContext;
12759   DeclContext *DC = CurContext;
12760   bool isStdBadAlloc = false;
12761   bool isStdAlignValT = false;
12762 
12763   RedeclarationKind Redecl = ForRedeclaration;
12764   if (TUK == TUK_Friend || TUK == TUK_Reference)
12765     Redecl = NotForRedeclaration;
12766 
12767   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
12768   if (Name && SS.isNotEmpty()) {
12769     // We have a nested-name tag ('struct foo::bar').
12770 
12771     // Check for invalid 'foo::'.
12772     if (SS.isInvalid()) {
12773       Name = nullptr;
12774       goto CreateNewDecl;
12775     }
12776 
12777     // If this is a friend or a reference to a class in a dependent
12778     // context, don't try to make a decl for it.
12779     if (TUK == TUK_Friend || TUK == TUK_Reference) {
12780       DC = computeDeclContext(SS, false);
12781       if (!DC) {
12782         IsDependent = true;
12783         return nullptr;
12784       }
12785     } else {
12786       DC = computeDeclContext(SS, true);
12787       if (!DC) {
12788         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
12789           << SS.getRange();
12790         return nullptr;
12791       }
12792     }
12793 
12794     if (RequireCompleteDeclContext(SS, DC))
12795       return nullptr;
12796 
12797     SearchDC = DC;
12798     // Look-up name inside 'foo::'.
12799     LookupQualifiedName(Previous, DC);
12800 
12801     if (Previous.isAmbiguous())
12802       return nullptr;
12803 
12804     if (Previous.empty()) {
12805       // Name lookup did not find anything. However, if the
12806       // nested-name-specifier refers to the current instantiation,
12807       // and that current instantiation has any dependent base
12808       // classes, we might find something at instantiation time: treat
12809       // this as a dependent elaborated-type-specifier.
12810       // But this only makes any sense for reference-like lookups.
12811       if (Previous.wasNotFoundInCurrentInstantiation() &&
12812           (TUK == TUK_Reference || TUK == TUK_Friend)) {
12813         IsDependent = true;
12814         return nullptr;
12815       }
12816 
12817       // A tag 'foo::bar' must already exist.
12818       Diag(NameLoc, diag::err_not_tag_in_scope)
12819         << Kind << Name << DC << SS.getRange();
12820       Name = nullptr;
12821       Invalid = true;
12822       goto CreateNewDecl;
12823     }
12824   } else if (Name) {
12825     // C++14 [class.mem]p14:
12826     //   If T is the name of a class, then each of the following shall have a
12827     //   name different from T:
12828     //    -- every member of class T that is itself a type
12829     if (TUK != TUK_Reference && TUK != TUK_Friend &&
12830         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
12831       return nullptr;
12832 
12833     // If this is a named struct, check to see if there was a previous forward
12834     // declaration or definition.
12835     // FIXME: We're looking into outer scopes here, even when we
12836     // shouldn't be. Doing so can result in ambiguities that we
12837     // shouldn't be diagnosing.
12838     LookupName(Previous, S);
12839 
12840     // When declaring or defining a tag, ignore ambiguities introduced
12841     // by types using'ed into this scope.
12842     if (Previous.isAmbiguous() &&
12843         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
12844       LookupResult::Filter F = Previous.makeFilter();
12845       while (F.hasNext()) {
12846         NamedDecl *ND = F.next();
12847         if (!ND->getDeclContext()->getRedeclContext()->Equals(
12848                 SearchDC->getRedeclContext()))
12849           F.erase();
12850       }
12851       F.done();
12852     }
12853 
12854     // C++11 [namespace.memdef]p3:
12855     //   If the name in a friend declaration is neither qualified nor
12856     //   a template-id and the declaration is a function or an
12857     //   elaborated-type-specifier, the lookup to determine whether
12858     //   the entity has been previously declared shall not consider
12859     //   any scopes outside the innermost enclosing namespace.
12860     //
12861     // MSVC doesn't implement the above rule for types, so a friend tag
12862     // declaration may be a redeclaration of a type declared in an enclosing
12863     // scope.  They do implement this rule for friend functions.
12864     //
12865     // Does it matter that this should be by scope instead of by
12866     // semantic context?
12867     if (!Previous.empty() && TUK == TUK_Friend) {
12868       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
12869       LookupResult::Filter F = Previous.makeFilter();
12870       bool FriendSawTagOutsideEnclosingNamespace = false;
12871       while (F.hasNext()) {
12872         NamedDecl *ND = F.next();
12873         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12874         if (DC->isFileContext() &&
12875             !EnclosingNS->Encloses(ND->getDeclContext())) {
12876           if (getLangOpts().MSVCCompat)
12877             FriendSawTagOutsideEnclosingNamespace = true;
12878           else
12879             F.erase();
12880         }
12881       }
12882       F.done();
12883 
12884       // Diagnose this MSVC extension in the easy case where lookup would have
12885       // unambiguously found something outside the enclosing namespace.
12886       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
12887         NamedDecl *ND = Previous.getFoundDecl();
12888         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
12889             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
12890       }
12891     }
12892 
12893     // Note:  there used to be some attempt at recovery here.
12894     if (Previous.isAmbiguous())
12895       return nullptr;
12896 
12897     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
12898       // FIXME: This makes sure that we ignore the contexts associated
12899       // with C structs, unions, and enums when looking for a matching
12900       // tag declaration or definition. See the similar lookup tweak
12901       // in Sema::LookupName; is there a better way to deal with this?
12902       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
12903         SearchDC = SearchDC->getParent();
12904     }
12905   }
12906 
12907   if (Previous.isSingleResult() &&
12908       Previous.getFoundDecl()->isTemplateParameter()) {
12909     // Maybe we will complain about the shadowed template parameter.
12910     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
12911     // Just pretend that we didn't see the previous declaration.
12912     Previous.clear();
12913   }
12914 
12915   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
12916       DC->Equals(getStdNamespace())) {
12917     if (Name->isStr("bad_alloc")) {
12918       // This is a declaration of or a reference to "std::bad_alloc".
12919       isStdBadAlloc = true;
12920 
12921       // If std::bad_alloc has been implicitly declared (but made invisible to
12922       // name lookup), fill in this implicit declaration as the previous
12923       // declaration, so that the declarations get chained appropriately.
12924       if (Previous.empty() && StdBadAlloc)
12925         Previous.addDecl(getStdBadAlloc());
12926     } else if (Name->isStr("align_val_t")) {
12927       isStdAlignValT = true;
12928       if (Previous.empty() && StdAlignValT)
12929         Previous.addDecl(getStdAlignValT());
12930     }
12931   }
12932 
12933   // If we didn't find a previous declaration, and this is a reference
12934   // (or friend reference), move to the correct scope.  In C++, we
12935   // also need to do a redeclaration lookup there, just in case
12936   // there's a shadow friend decl.
12937   if (Name && Previous.empty() &&
12938       (TUK == TUK_Reference || TUK == TUK_Friend)) {
12939     if (Invalid) goto CreateNewDecl;
12940     assert(SS.isEmpty());
12941 
12942     if (TUK == TUK_Reference) {
12943       // C++ [basic.scope.pdecl]p5:
12944       //   -- for an elaborated-type-specifier of the form
12945       //
12946       //          class-key identifier
12947       //
12948       //      if the elaborated-type-specifier is used in the
12949       //      decl-specifier-seq or parameter-declaration-clause of a
12950       //      function defined in namespace scope, the identifier is
12951       //      declared as a class-name in the namespace that contains
12952       //      the declaration; otherwise, except as a friend
12953       //      declaration, the identifier is declared in the smallest
12954       //      non-class, non-function-prototype scope that contains the
12955       //      declaration.
12956       //
12957       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
12958       // C structs and unions.
12959       //
12960       // It is an error in C++ to declare (rather than define) an enum
12961       // type, including via an elaborated type specifier.  We'll
12962       // diagnose that later; for now, declare the enum in the same
12963       // scope as we would have picked for any other tag type.
12964       //
12965       // GNU C also supports this behavior as part of its incomplete
12966       // enum types extension, while GNU C++ does not.
12967       //
12968       // Find the context where we'll be declaring the tag.
12969       // FIXME: We would like to maintain the current DeclContext as the
12970       // lexical context,
12971       SearchDC = getTagInjectionContext(SearchDC);
12972 
12973       // Find the scope where we'll be declaring the tag.
12974       S = getTagInjectionScope(S, getLangOpts());
12975     } else {
12976       assert(TUK == TUK_Friend);
12977       // C++ [namespace.memdef]p3:
12978       //   If a friend declaration in a non-local class first declares a
12979       //   class or function, the friend class or function is a member of
12980       //   the innermost enclosing namespace.
12981       SearchDC = SearchDC->getEnclosingNamespaceContext();
12982     }
12983 
12984     // In C++, we need to do a redeclaration lookup to properly
12985     // diagnose some problems.
12986     // FIXME: redeclaration lookup is also used (with and without C++) to find a
12987     // hidden declaration so that we don't get ambiguity errors when using a
12988     // type declared by an elaborated-type-specifier.  In C that is not correct
12989     // and we should instead merge compatible types found by lookup.
12990     if (getLangOpts().CPlusPlus) {
12991       Previous.setRedeclarationKind(ForRedeclaration);
12992       LookupQualifiedName(Previous, SearchDC);
12993     } else {
12994       Previous.setRedeclarationKind(ForRedeclaration);
12995       LookupName(Previous, S);
12996     }
12997   }
12998 
12999   // If we have a known previous declaration to use, then use it.
13000   if (Previous.empty() && SkipBody && SkipBody->Previous)
13001     Previous.addDecl(SkipBody->Previous);
13002 
13003   if (!Previous.empty()) {
13004     NamedDecl *PrevDecl = Previous.getFoundDecl();
13005     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
13006 
13007     // It's okay to have a tag decl in the same scope as a typedef
13008     // which hides a tag decl in the same scope.  Finding this
13009     // insanity with a redeclaration lookup can only actually happen
13010     // in C++.
13011     //
13012     // This is also okay for elaborated-type-specifiers, which is
13013     // technically forbidden by the current standard but which is
13014     // okay according to the likely resolution of an open issue;
13015     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
13016     if (getLangOpts().CPlusPlus) {
13017       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13018         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
13019           TagDecl *Tag = TT->getDecl();
13020           if (Tag->getDeclName() == Name &&
13021               Tag->getDeclContext()->getRedeclContext()
13022                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
13023             PrevDecl = Tag;
13024             Previous.clear();
13025             Previous.addDecl(Tag);
13026             Previous.resolveKind();
13027           }
13028         }
13029       }
13030     }
13031 
13032     // If this is a redeclaration of a using shadow declaration, it must
13033     // declare a tag in the same context. In MSVC mode, we allow a
13034     // redefinition if either context is within the other.
13035     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
13036       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
13037       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
13038           isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
13039           !(OldTag && isAcceptableTagRedeclContext(
13040                           *this, OldTag->getDeclContext(), SearchDC))) {
13041         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
13042         Diag(Shadow->getTargetDecl()->getLocation(),
13043              diag::note_using_decl_target);
13044         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
13045             << 0;
13046         // Recover by ignoring the old declaration.
13047         Previous.clear();
13048         goto CreateNewDecl;
13049       }
13050     }
13051 
13052     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
13053       // If this is a use of a previous tag, or if the tag is already declared
13054       // in the same scope (so that the definition/declaration completes or
13055       // rementions the tag), reuse the decl.
13056       if (TUK == TUK_Reference || TUK == TUK_Friend ||
13057           isDeclInScope(DirectPrevDecl, SearchDC, S,
13058                         SS.isNotEmpty() || isExplicitSpecialization)) {
13059         // Make sure that this wasn't declared as an enum and now used as a
13060         // struct or something similar.
13061         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
13062                                           TUK == TUK_Definition, KWLoc,
13063                                           Name)) {
13064           bool SafeToContinue
13065             = (PrevTagDecl->getTagKind() != TTK_Enum &&
13066                Kind != TTK_Enum);
13067           if (SafeToContinue)
13068             Diag(KWLoc, diag::err_use_with_wrong_tag)
13069               << Name
13070               << FixItHint::CreateReplacement(SourceRange(KWLoc),
13071                                               PrevTagDecl->getKindName());
13072           else
13073             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
13074           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
13075 
13076           if (SafeToContinue)
13077             Kind = PrevTagDecl->getTagKind();
13078           else {
13079             // Recover by making this an anonymous redefinition.
13080             Name = nullptr;
13081             Previous.clear();
13082             Invalid = true;
13083           }
13084         }
13085 
13086         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
13087           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
13088 
13089           // If this is an elaborated-type-specifier for a scoped enumeration,
13090           // the 'class' keyword is not necessary and not permitted.
13091           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13092             if (ScopedEnum)
13093               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
13094                 << PrevEnum->isScoped()
13095                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
13096             return PrevTagDecl;
13097           }
13098 
13099           QualType EnumUnderlyingTy;
13100           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13101             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
13102           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
13103             EnumUnderlyingTy = QualType(T, 0);
13104 
13105           // All conflicts with previous declarations are recovered by
13106           // returning the previous declaration, unless this is a definition,
13107           // in which case we want the caller to bail out.
13108           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
13109                                      ScopedEnum, EnumUnderlyingTy,
13110                                      EnumUnderlyingIsImplicit, PrevEnum))
13111             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
13112         }
13113 
13114         // C++11 [class.mem]p1:
13115         //   A member shall not be declared twice in the member-specification,
13116         //   except that a nested class or member class template can be declared
13117         //   and then later defined.
13118         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
13119             S->isDeclScope(PrevDecl)) {
13120           Diag(NameLoc, diag::ext_member_redeclared);
13121           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
13122         }
13123 
13124         if (!Invalid) {
13125           // If this is a use, just return the declaration we found, unless
13126           // we have attributes.
13127           if (TUK == TUK_Reference || TUK == TUK_Friend) {
13128             if (Attr) {
13129               // FIXME: Diagnose these attributes. For now, we create a new
13130               // declaration to hold them.
13131             } else if (TUK == TUK_Reference &&
13132                        (PrevTagDecl->getFriendObjectKind() ==
13133                             Decl::FOK_Undeclared ||
13134                         PP.getModuleContainingLocation(
13135                             PrevDecl->getLocation()) !=
13136                             PP.getModuleContainingLocation(KWLoc)) &&
13137                        SS.isEmpty()) {
13138               // This declaration is a reference to an existing entity, but
13139               // has different visibility from that entity: it either makes
13140               // a friend visible or it makes a type visible in a new module.
13141               // In either case, create a new declaration. We only do this if
13142               // the declaration would have meant the same thing if no prior
13143               // declaration were found, that is, if it was found in the same
13144               // scope where we would have injected a declaration.
13145               if (!getTagInjectionContext(CurContext)->getRedeclContext()
13146                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
13147                 return PrevTagDecl;
13148               // This is in the injected scope, create a new declaration in
13149               // that scope.
13150               S = getTagInjectionScope(S, getLangOpts());
13151             } else {
13152               return PrevTagDecl;
13153             }
13154           }
13155 
13156           // Diagnose attempts to redefine a tag.
13157           if (TUK == TUK_Definition) {
13158             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
13159               // If we're defining a specialization and the previous definition
13160               // is from an implicit instantiation, don't emit an error
13161               // here; we'll catch this in the general case below.
13162               bool IsExplicitSpecializationAfterInstantiation = false;
13163               if (isExplicitSpecialization) {
13164                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
13165                   IsExplicitSpecializationAfterInstantiation =
13166                     RD->getTemplateSpecializationKind() !=
13167                     TSK_ExplicitSpecialization;
13168                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
13169                   IsExplicitSpecializationAfterInstantiation =
13170                     ED->getTemplateSpecializationKind() !=
13171                     TSK_ExplicitSpecialization;
13172               }
13173 
13174               NamedDecl *Hidden = nullptr;
13175               if (SkipBody && getLangOpts().CPlusPlus &&
13176                   !hasVisibleDefinition(Def, &Hidden)) {
13177                 // There is a definition of this tag, but it is not visible. We
13178                 // explicitly make use of C++'s one definition rule here, and
13179                 // assume that this definition is identical to the hidden one
13180                 // we already have. Make the existing definition visible and
13181                 // use it in place of this one.
13182                 SkipBody->ShouldSkip = true;
13183                 makeMergedDefinitionVisible(Hidden, KWLoc);
13184                 return Def;
13185               } else if (!IsExplicitSpecializationAfterInstantiation) {
13186                 // A redeclaration in function prototype scope in C isn't
13187                 // visible elsewhere, so merely issue a warning.
13188                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
13189                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
13190                 else
13191                   Diag(NameLoc, diag::err_redefinition) << Name;
13192                 Diag(Def->getLocation(), diag::note_previous_definition);
13193                 // If this is a redefinition, recover by making this
13194                 // struct be anonymous, which will make any later
13195                 // references get the previous definition.
13196                 Name = nullptr;
13197                 Previous.clear();
13198                 Invalid = true;
13199               }
13200             } else {
13201               // If the type is currently being defined, complain
13202               // about a nested redefinition.
13203               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
13204               if (TD->isBeingDefined()) {
13205                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
13206                 Diag(PrevTagDecl->getLocation(),
13207                      diag::note_previous_definition);
13208                 Name = nullptr;
13209                 Previous.clear();
13210                 Invalid = true;
13211               }
13212             }
13213 
13214             // Okay, this is definition of a previously declared or referenced
13215             // tag. We're going to create a new Decl for it.
13216           }
13217 
13218           // Okay, we're going to make a redeclaration.  If this is some kind
13219           // of reference, make sure we build the redeclaration in the same DC
13220           // as the original, and ignore the current access specifier.
13221           if (TUK == TUK_Friend || TUK == TUK_Reference) {
13222             SearchDC = PrevTagDecl->getDeclContext();
13223             AS = AS_none;
13224           }
13225         }
13226         // If we get here we have (another) forward declaration or we
13227         // have a definition.  Just create a new decl.
13228 
13229       } else {
13230         // If we get here, this is a definition of a new tag type in a nested
13231         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
13232         // new decl/type.  We set PrevDecl to NULL so that the entities
13233         // have distinct types.
13234         Previous.clear();
13235       }
13236       // If we get here, we're going to create a new Decl. If PrevDecl
13237       // is non-NULL, it's a definition of the tag declared by
13238       // PrevDecl. If it's NULL, we have a new definition.
13239 
13240     // Otherwise, PrevDecl is not a tag, but was found with tag
13241     // lookup.  This is only actually possible in C++, where a few
13242     // things like templates still live in the tag namespace.
13243     } else {
13244       // Use a better diagnostic if an elaborated-type-specifier
13245       // found the wrong kind of type on the first
13246       // (non-redeclaration) lookup.
13247       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
13248           !Previous.isForRedeclaration()) {
13249         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13250         Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
13251                                                        << Kind;
13252         Diag(PrevDecl->getLocation(), diag::note_declared_at);
13253         Invalid = true;
13254 
13255       // Otherwise, only diagnose if the declaration is in scope.
13256       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
13257                                 SS.isNotEmpty() || isExplicitSpecialization)) {
13258         // do nothing
13259 
13260       // Diagnose implicit declarations introduced by elaborated types.
13261       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
13262         NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
13263         Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
13264         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13265         Invalid = true;
13266 
13267       // Otherwise it's a declaration.  Call out a particularly common
13268       // case here.
13269       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
13270         unsigned Kind = 0;
13271         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
13272         Diag(NameLoc, diag::err_tag_definition_of_typedef)
13273           << Name << Kind << TND->getUnderlyingType();
13274         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
13275         Invalid = true;
13276 
13277       // Otherwise, diagnose.
13278       } else {
13279         // The tag name clashes with something else in the target scope,
13280         // issue an error and recover by making this tag be anonymous.
13281         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
13282         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13283         Name = nullptr;
13284         Invalid = true;
13285       }
13286 
13287       // The existing declaration isn't relevant to us; we're in a
13288       // new scope, so clear out the previous declaration.
13289       Previous.clear();
13290     }
13291   }
13292 
13293 CreateNewDecl:
13294 
13295   TagDecl *PrevDecl = nullptr;
13296   if (Previous.isSingleResult())
13297     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
13298 
13299   // If there is an identifier, use the location of the identifier as the
13300   // location of the decl, otherwise use the location of the struct/union
13301   // keyword.
13302   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
13303 
13304   // Otherwise, create a new declaration. If there is a previous
13305   // declaration of the same entity, the two will be linked via
13306   // PrevDecl.
13307   TagDecl *New;
13308 
13309   bool IsForwardReference = false;
13310   if (Kind == TTK_Enum) {
13311     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13312     // enum X { A, B, C } D;    D should chain to X.
13313     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
13314                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
13315                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
13316 
13317     if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
13318       StdAlignValT = cast<EnumDecl>(New);
13319 
13320     // If this is an undefined enum, warn.
13321     if (TUK != TUK_Definition && !Invalid) {
13322       TagDecl *Def;
13323       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
13324           cast<EnumDecl>(New)->isFixed()) {
13325         // C++0x: 7.2p2: opaque-enum-declaration.
13326         // Conflicts are diagnosed above. Do nothing.
13327       }
13328       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
13329         Diag(Loc, diag::ext_forward_ref_enum_def)
13330           << New;
13331         Diag(Def->getLocation(), diag::note_previous_definition);
13332       } else {
13333         unsigned DiagID = diag::ext_forward_ref_enum;
13334         if (getLangOpts().MSVCCompat)
13335           DiagID = diag::ext_ms_forward_ref_enum;
13336         else if (getLangOpts().CPlusPlus)
13337           DiagID = diag::err_forward_ref_enum;
13338         Diag(Loc, DiagID);
13339 
13340         // If this is a forward-declared reference to an enumeration, make a
13341         // note of it; we won't actually be introducing the declaration into
13342         // the declaration context.
13343         if (TUK == TUK_Reference)
13344           IsForwardReference = true;
13345       }
13346     }
13347 
13348     if (EnumUnderlying) {
13349       EnumDecl *ED = cast<EnumDecl>(New);
13350       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
13351         ED->setIntegerTypeSourceInfo(TI);
13352       else
13353         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
13354       ED->setPromotionType(ED->getIntegerType());
13355     }
13356   } else {
13357     // struct/union/class
13358 
13359     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
13360     // struct X { int A; } D;    D should chain to X.
13361     if (getLangOpts().CPlusPlus) {
13362       // FIXME: Look for a way to use RecordDecl for simple structs.
13363       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13364                                   cast_or_null<CXXRecordDecl>(PrevDecl));
13365 
13366       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
13367         StdBadAlloc = cast<CXXRecordDecl>(New);
13368     } else
13369       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
13370                                cast_or_null<RecordDecl>(PrevDecl));
13371   }
13372 
13373   // C++11 [dcl.type]p3:
13374   //   A type-specifier-seq shall not define a class or enumeration [...].
13375   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
13376     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
13377       << Context.getTagDeclType(New);
13378     Invalid = true;
13379   }
13380 
13381   // Maybe add qualifier info.
13382   if (SS.isNotEmpty()) {
13383     if (SS.isSet()) {
13384       // If this is either a declaration or a definition, check the
13385       // nested-name-specifier against the current context. We don't do this
13386       // for explicit specializations, because they have similar checking
13387       // (with more specific diagnostics) in the call to
13388       // CheckMemberSpecialization, below.
13389       if (!isExplicitSpecialization &&
13390           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
13391           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
13392         Invalid = true;
13393 
13394       New->setQualifierInfo(SS.getWithLocInContext(Context));
13395       if (TemplateParameterLists.size() > 0) {
13396         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
13397       }
13398     }
13399     else
13400       Invalid = true;
13401   }
13402 
13403   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
13404     // Add alignment attributes if necessary; these attributes are checked when
13405     // the ASTContext lays out the structure.
13406     //
13407     // It is important for implementing the correct semantics that this
13408     // happen here (in act on tag decl). The #pragma pack stack is
13409     // maintained as a result of parser callbacks which can occur at
13410     // many points during the parsing of a struct declaration (because
13411     // the #pragma tokens are effectively skipped over during the
13412     // parsing of the struct).
13413     if (TUK == TUK_Definition) {
13414       AddAlignmentAttributesForRecord(RD);
13415       AddMsStructLayoutForRecord(RD);
13416     }
13417   }
13418 
13419   if (ModulePrivateLoc.isValid()) {
13420     if (isExplicitSpecialization)
13421       Diag(New->getLocation(), diag::err_module_private_specialization)
13422         << 2
13423         << FixItHint::CreateRemoval(ModulePrivateLoc);
13424     // __module_private__ does not apply to local classes. However, we only
13425     // diagnose this as an error when the declaration specifiers are
13426     // freestanding. Here, we just ignore the __module_private__.
13427     else if (!SearchDC->isFunctionOrMethod())
13428       New->setModulePrivate();
13429   }
13430 
13431   // If this is a specialization of a member class (of a class template),
13432   // check the specialization.
13433   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
13434     Invalid = true;
13435 
13436   // If we're declaring or defining a tag in function prototype scope in C,
13437   // note that this type can only be used within the function and add it to
13438   // the list of decls to inject into the function definition scope.
13439   if ((Name || Kind == TTK_Enum) &&
13440       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
13441     if (getLangOpts().CPlusPlus) {
13442       // C++ [dcl.fct]p6:
13443       //   Types shall not be defined in return or parameter types.
13444       if (TUK == TUK_Definition && !IsTypeSpecifier) {
13445         Diag(Loc, diag::err_type_defined_in_param_type)
13446             << Name;
13447         Invalid = true;
13448       }
13449     } else if (!PrevDecl) {
13450       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
13451     }
13452   }
13453 
13454   if (Invalid)
13455     New->setInvalidDecl();
13456 
13457   if (Attr)
13458     ProcessDeclAttributeList(S, New, Attr);
13459 
13460   // Set the lexical context. If the tag has a C++ scope specifier, the
13461   // lexical context will be different from the semantic context.
13462   New->setLexicalDeclContext(CurContext);
13463 
13464   // Mark this as a friend decl if applicable.
13465   // In Microsoft mode, a friend declaration also acts as a forward
13466   // declaration so we always pass true to setObjectOfFriendDecl to make
13467   // the tag name visible.
13468   if (TUK == TUK_Friend)
13469     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
13470 
13471   // Set the access specifier.
13472   if (!Invalid && SearchDC->isRecord())
13473     SetMemberAccessSpecifier(New, PrevDecl, AS);
13474 
13475   if (TUK == TUK_Definition)
13476     New->startDefinition();
13477 
13478   // If this has an identifier, add it to the scope stack.
13479   if (TUK == TUK_Friend) {
13480     // We might be replacing an existing declaration in the lookup tables;
13481     // if so, borrow its access specifier.
13482     if (PrevDecl)
13483       New->setAccess(PrevDecl->getAccess());
13484 
13485     DeclContext *DC = New->getDeclContext()->getRedeclContext();
13486     DC->makeDeclVisibleInContext(New);
13487     if (Name) // can be null along some error paths
13488       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13489         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
13490   } else if (Name) {
13491     S = getNonFieldDeclScope(S);
13492     PushOnScopeChains(New, S, !IsForwardReference);
13493     if (IsForwardReference)
13494       SearchDC->makeDeclVisibleInContext(New);
13495   } else {
13496     CurContext->addDecl(New);
13497   }
13498 
13499   // If this is the C FILE type, notify the AST context.
13500   if (IdentifierInfo *II = New->getIdentifier())
13501     if (!New->isInvalidDecl() &&
13502         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
13503         II->isStr("FILE"))
13504       Context.setFILEDecl(New);
13505 
13506   if (PrevDecl)
13507     mergeDeclAttributes(New, PrevDecl);
13508 
13509   // If there's a #pragma GCC visibility in scope, set the visibility of this
13510   // record.
13511   AddPushedVisibilityAttribute(New);
13512 
13513   OwnedDecl = true;
13514   // In C++, don't return an invalid declaration. We can't recover well from
13515   // the cases where we make the type anonymous.
13516   if (Invalid && getLangOpts().CPlusPlus) {
13517     if (New->isBeingDefined())
13518       if (auto RD = dyn_cast<RecordDecl>(New))
13519         RD->completeDefinition();
13520     return nullptr;
13521   } else {
13522     return New;
13523   }
13524 }
13525 
13526 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
13527   AdjustDeclIfTemplate(TagD);
13528   TagDecl *Tag = cast<TagDecl>(TagD);
13529 
13530   // Enter the tag context.
13531   PushDeclContext(S, Tag);
13532 
13533   ActOnDocumentableDecl(TagD);
13534 
13535   // If there's a #pragma GCC visibility in scope, set the visibility of this
13536   // record.
13537   AddPushedVisibilityAttribute(Tag);
13538 }
13539 
13540 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
13541   assert(isa<ObjCContainerDecl>(IDecl) &&
13542          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
13543   DeclContext *OCD = cast<DeclContext>(IDecl);
13544   assert(getContainingDC(OCD) == CurContext &&
13545       "The next DeclContext should be lexically contained in the current one.");
13546   CurContext = OCD;
13547   return IDecl;
13548 }
13549 
13550 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
13551                                            SourceLocation FinalLoc,
13552                                            bool IsFinalSpelledSealed,
13553                                            SourceLocation LBraceLoc) {
13554   AdjustDeclIfTemplate(TagD);
13555   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
13556 
13557   FieldCollector->StartClass();
13558 
13559   if (!Record->getIdentifier())
13560     return;
13561 
13562   if (FinalLoc.isValid())
13563     Record->addAttr(new (Context)
13564                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
13565 
13566   // C++ [class]p2:
13567   //   [...] The class-name is also inserted into the scope of the
13568   //   class itself; this is known as the injected-class-name. For
13569   //   purposes of access checking, the injected-class-name is treated
13570   //   as if it were a public member name.
13571   CXXRecordDecl *InjectedClassName
13572     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
13573                             Record->getLocStart(), Record->getLocation(),
13574                             Record->getIdentifier(),
13575                             /*PrevDecl=*/nullptr,
13576                             /*DelayTypeCreation=*/true);
13577   Context.getTypeDeclType(InjectedClassName, Record);
13578   InjectedClassName->setImplicit();
13579   InjectedClassName->setAccess(AS_public);
13580   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
13581       InjectedClassName->setDescribedClassTemplate(Template);
13582   PushOnScopeChains(InjectedClassName, S);
13583   assert(InjectedClassName->isInjectedClassName() &&
13584          "Broken injected-class-name");
13585 }
13586 
13587 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
13588                                     SourceRange BraceRange) {
13589   AdjustDeclIfTemplate(TagD);
13590   TagDecl *Tag = cast<TagDecl>(TagD);
13591   Tag->setBraceRange(BraceRange);
13592 
13593   // Make sure we "complete" the definition even it is invalid.
13594   if (Tag->isBeingDefined()) {
13595     assert(Tag->isInvalidDecl() && "We should already have completed it");
13596     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13597       RD->completeDefinition();
13598   }
13599 
13600   if (isa<CXXRecordDecl>(Tag))
13601     FieldCollector->FinishClass();
13602 
13603   // Exit this scope of this tag's definition.
13604   PopDeclContext();
13605 
13606   if (getCurLexicalContext()->isObjCContainer() &&
13607       Tag->getDeclContext()->isFileContext())
13608     Tag->setTopLevelDeclInObjCContainer();
13609 
13610   // Notify the consumer that we've defined a tag.
13611   if (!Tag->isInvalidDecl())
13612     Consumer.HandleTagDeclDefinition(Tag);
13613 }
13614 
13615 void Sema::ActOnObjCContainerFinishDefinition() {
13616   // Exit this scope of this interface definition.
13617   PopDeclContext();
13618 }
13619 
13620 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
13621   assert(DC == CurContext && "Mismatch of container contexts");
13622   OriginalLexicalContext = DC;
13623   ActOnObjCContainerFinishDefinition();
13624 }
13625 
13626 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
13627   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
13628   OriginalLexicalContext = nullptr;
13629 }
13630 
13631 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
13632   AdjustDeclIfTemplate(TagD);
13633   TagDecl *Tag = cast<TagDecl>(TagD);
13634   Tag->setInvalidDecl();
13635 
13636   // Make sure we "complete" the definition even it is invalid.
13637   if (Tag->isBeingDefined()) {
13638     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13639       RD->completeDefinition();
13640   }
13641 
13642   // We're undoing ActOnTagStartDefinition here, not
13643   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
13644   // the FieldCollector.
13645 
13646   PopDeclContext();
13647 }
13648 
13649 // Note that FieldName may be null for anonymous bitfields.
13650 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
13651                                 IdentifierInfo *FieldName,
13652                                 QualType FieldTy, bool IsMsStruct,
13653                                 Expr *BitWidth, bool *ZeroWidth) {
13654   // Default to true; that shouldn't confuse checks for emptiness
13655   if (ZeroWidth)
13656     *ZeroWidth = true;
13657 
13658   // C99 6.7.2.1p4 - verify the field type.
13659   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
13660   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
13661     // Handle incomplete types with specific error.
13662     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
13663       return ExprError();
13664     if (FieldName)
13665       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
13666         << FieldName << FieldTy << BitWidth->getSourceRange();
13667     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
13668       << FieldTy << BitWidth->getSourceRange();
13669   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
13670                                              UPPC_BitFieldWidth))
13671     return ExprError();
13672 
13673   // If the bit-width is type- or value-dependent, don't try to check
13674   // it now.
13675   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
13676     return BitWidth;
13677 
13678   llvm::APSInt Value;
13679   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
13680   if (ICE.isInvalid())
13681     return ICE;
13682   BitWidth = ICE.get();
13683 
13684   if (Value != 0 && ZeroWidth)
13685     *ZeroWidth = false;
13686 
13687   // Zero-width bitfield is ok for anonymous field.
13688   if (Value == 0 && FieldName)
13689     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
13690 
13691   if (Value.isSigned() && Value.isNegative()) {
13692     if (FieldName)
13693       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
13694                << FieldName << Value.toString(10);
13695     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
13696       << Value.toString(10);
13697   }
13698 
13699   if (!FieldTy->isDependentType()) {
13700     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
13701     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
13702     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
13703 
13704     // Over-wide bitfields are an error in C or when using the MSVC bitfield
13705     // ABI.
13706     bool CStdConstraintViolation =
13707         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
13708     bool MSBitfieldViolation =
13709         Value.ugt(TypeStorageSize) &&
13710         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
13711     if (CStdConstraintViolation || MSBitfieldViolation) {
13712       unsigned DiagWidth =
13713           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
13714       if (FieldName)
13715         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
13716                << FieldName << (unsigned)Value.getZExtValue()
13717                << !CStdConstraintViolation << DiagWidth;
13718 
13719       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
13720              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
13721              << DiagWidth;
13722     }
13723 
13724     // Warn on types where the user might conceivably expect to get all
13725     // specified bits as value bits: that's all integral types other than
13726     // 'bool'.
13727     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
13728       if (FieldName)
13729         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
13730             << FieldName << (unsigned)Value.getZExtValue()
13731             << (unsigned)TypeWidth;
13732       else
13733         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
13734             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
13735     }
13736   }
13737 
13738   return BitWidth;
13739 }
13740 
13741 /// ActOnField - Each field of a C struct/union is passed into this in order
13742 /// to create a FieldDecl object for it.
13743 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
13744                        Declarator &D, Expr *BitfieldWidth) {
13745   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
13746                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
13747                                /*InitStyle=*/ICIS_NoInit, AS_public);
13748   return Res;
13749 }
13750 
13751 /// HandleField - Analyze a field of a C struct or a C++ data member.
13752 ///
13753 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
13754                              SourceLocation DeclStart,
13755                              Declarator &D, Expr *BitWidth,
13756                              InClassInitStyle InitStyle,
13757                              AccessSpecifier AS) {
13758   if (D.isDecompositionDeclarator()) {
13759     const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
13760     Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
13761       << Decomp.getSourceRange();
13762     return nullptr;
13763   }
13764 
13765   IdentifierInfo *II = D.getIdentifier();
13766   SourceLocation Loc = DeclStart;
13767   if (II) Loc = D.getIdentifierLoc();
13768 
13769   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13770   QualType T = TInfo->getType();
13771   if (getLangOpts().CPlusPlus) {
13772     CheckExtraCXXDefaultArguments(D);
13773 
13774     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13775                                         UPPC_DataMemberType)) {
13776       D.setInvalidType();
13777       T = Context.IntTy;
13778       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13779     }
13780   }
13781 
13782   // TR 18037 does not allow fields to be declared with address spaces.
13783   if (T.getQualifiers().hasAddressSpace()) {
13784     Diag(Loc, diag::err_field_with_address_space);
13785     D.setInvalidType();
13786   }
13787 
13788   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
13789   // used as structure or union field: image, sampler, event or block types.
13790   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
13791                           T->isSamplerT() || T->isBlockPointerType())) {
13792     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
13793     D.setInvalidType();
13794   }
13795 
13796   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13797 
13798   if (D.getDeclSpec().isInlineSpecified())
13799     Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
13800         << getLangOpts().CPlusPlus1z;
13801   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13802     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13803          diag::err_invalid_thread)
13804       << DeclSpec::getSpecifierName(TSCS);
13805 
13806   // Check to see if this name was declared as a member previously
13807   NamedDecl *PrevDecl = nullptr;
13808   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13809   LookupName(Previous, S);
13810   switch (Previous.getResultKind()) {
13811     case LookupResult::Found:
13812     case LookupResult::FoundUnresolvedValue:
13813       PrevDecl = Previous.getAsSingle<NamedDecl>();
13814       break;
13815 
13816     case LookupResult::FoundOverloaded:
13817       PrevDecl = Previous.getRepresentativeDecl();
13818       break;
13819 
13820     case LookupResult::NotFound:
13821     case LookupResult::NotFoundInCurrentInstantiation:
13822     case LookupResult::Ambiguous:
13823       break;
13824   }
13825   Previous.suppressDiagnostics();
13826 
13827   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13828     // Maybe we will complain about the shadowed template parameter.
13829     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13830     // Just pretend that we didn't see the previous declaration.
13831     PrevDecl = nullptr;
13832   }
13833 
13834   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13835     PrevDecl = nullptr;
13836 
13837   bool Mutable
13838     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
13839   SourceLocation TSSL = D.getLocStart();
13840   FieldDecl *NewFD
13841     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
13842                      TSSL, AS, PrevDecl, &D);
13843 
13844   if (NewFD->isInvalidDecl())
13845     Record->setInvalidDecl();
13846 
13847   if (D.getDeclSpec().isModulePrivateSpecified())
13848     NewFD->setModulePrivate();
13849 
13850   if (NewFD->isInvalidDecl() && PrevDecl) {
13851     // Don't introduce NewFD into scope; there's already something
13852     // with the same name in the same scope.
13853   } else if (II) {
13854     PushOnScopeChains(NewFD, S);
13855   } else
13856     Record->addDecl(NewFD);
13857 
13858   return NewFD;
13859 }
13860 
13861 /// \brief Build a new FieldDecl and check its well-formedness.
13862 ///
13863 /// This routine builds a new FieldDecl given the fields name, type,
13864 /// record, etc. \p PrevDecl should refer to any previous declaration
13865 /// with the same name and in the same scope as the field to be
13866 /// created.
13867 ///
13868 /// \returns a new FieldDecl.
13869 ///
13870 /// \todo The Declarator argument is a hack. It will be removed once
13871 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
13872                                 TypeSourceInfo *TInfo,
13873                                 RecordDecl *Record, SourceLocation Loc,
13874                                 bool Mutable, Expr *BitWidth,
13875                                 InClassInitStyle InitStyle,
13876                                 SourceLocation TSSL,
13877                                 AccessSpecifier AS, NamedDecl *PrevDecl,
13878                                 Declarator *D) {
13879   IdentifierInfo *II = Name.getAsIdentifierInfo();
13880   bool InvalidDecl = false;
13881   if (D) InvalidDecl = D->isInvalidType();
13882 
13883   // If we receive a broken type, recover by assuming 'int' and
13884   // marking this declaration as invalid.
13885   if (T.isNull()) {
13886     InvalidDecl = true;
13887     T = Context.IntTy;
13888   }
13889 
13890   QualType EltTy = Context.getBaseElementType(T);
13891   if (!EltTy->isDependentType()) {
13892     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
13893       // Fields of incomplete type force their record to be invalid.
13894       Record->setInvalidDecl();
13895       InvalidDecl = true;
13896     } else {
13897       NamedDecl *Def;
13898       EltTy->isIncompleteType(&Def);
13899       if (Def && Def->isInvalidDecl()) {
13900         Record->setInvalidDecl();
13901         InvalidDecl = true;
13902       }
13903     }
13904   }
13905 
13906   // OpenCL v1.2 s6.9.c: bitfields are not supported.
13907   if (BitWidth && getLangOpts().OpenCL) {
13908     Diag(Loc, diag::err_opencl_bitfields);
13909     InvalidDecl = true;
13910   }
13911 
13912   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13913   // than a variably modified type.
13914   if (!InvalidDecl && T->isVariablyModifiedType()) {
13915     bool SizeIsNegative;
13916     llvm::APSInt Oversized;
13917 
13918     TypeSourceInfo *FixedTInfo =
13919       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
13920                                                     SizeIsNegative,
13921                                                     Oversized);
13922     if (FixedTInfo) {
13923       Diag(Loc, diag::warn_illegal_constant_array_size);
13924       TInfo = FixedTInfo;
13925       T = FixedTInfo->getType();
13926     } else {
13927       if (SizeIsNegative)
13928         Diag(Loc, diag::err_typecheck_negative_array_size);
13929       else if (Oversized.getBoolValue())
13930         Diag(Loc, diag::err_array_too_large)
13931           << Oversized.toString(10);
13932       else
13933         Diag(Loc, diag::err_typecheck_field_variable_size);
13934       InvalidDecl = true;
13935     }
13936   }
13937 
13938   // Fields can not have abstract class types
13939   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
13940                                              diag::err_abstract_type_in_decl,
13941                                              AbstractFieldType))
13942     InvalidDecl = true;
13943 
13944   bool ZeroWidth = false;
13945   if (InvalidDecl)
13946     BitWidth = nullptr;
13947   // If this is declared as a bit-field, check the bit-field.
13948   if (BitWidth) {
13949     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
13950                               &ZeroWidth).get();
13951     if (!BitWidth) {
13952       InvalidDecl = true;
13953       BitWidth = nullptr;
13954       ZeroWidth = false;
13955     }
13956   }
13957 
13958   // Check that 'mutable' is consistent with the type of the declaration.
13959   if (!InvalidDecl && Mutable) {
13960     unsigned DiagID = 0;
13961     if (T->isReferenceType())
13962       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
13963                                         : diag::err_mutable_reference;
13964     else if (T.isConstQualified())
13965       DiagID = diag::err_mutable_const;
13966 
13967     if (DiagID) {
13968       SourceLocation ErrLoc = Loc;
13969       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
13970         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
13971       Diag(ErrLoc, DiagID);
13972       if (DiagID != diag::ext_mutable_reference) {
13973         Mutable = false;
13974         InvalidDecl = true;
13975       }
13976     }
13977   }
13978 
13979   // C++11 [class.union]p8 (DR1460):
13980   //   At most one variant member of a union may have a
13981   //   brace-or-equal-initializer.
13982   if (InitStyle != ICIS_NoInit)
13983     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
13984 
13985   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
13986                                        BitWidth, Mutable, InitStyle);
13987   if (InvalidDecl)
13988     NewFD->setInvalidDecl();
13989 
13990   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
13991     Diag(Loc, diag::err_duplicate_member) << II;
13992     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13993     NewFD->setInvalidDecl();
13994   }
13995 
13996   if (!InvalidDecl && getLangOpts().CPlusPlus) {
13997     if (Record->isUnion()) {
13998       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13999         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
14000         if (RDecl->getDefinition()) {
14001           // C++ [class.union]p1: An object of a class with a non-trivial
14002           // constructor, a non-trivial copy constructor, a non-trivial
14003           // destructor, or a non-trivial copy assignment operator
14004           // cannot be a member of a union, nor can an array of such
14005           // objects.
14006           if (CheckNontrivialField(NewFD))
14007             NewFD->setInvalidDecl();
14008         }
14009       }
14010 
14011       // C++ [class.union]p1: If a union contains a member of reference type,
14012       // the program is ill-formed, except when compiling with MSVC extensions
14013       // enabled.
14014       if (EltTy->isReferenceType()) {
14015         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
14016                                     diag::ext_union_member_of_reference_type :
14017                                     diag::err_union_member_of_reference_type)
14018           << NewFD->getDeclName() << EltTy;
14019         if (!getLangOpts().MicrosoftExt)
14020           NewFD->setInvalidDecl();
14021       }
14022     }
14023   }
14024 
14025   // FIXME: We need to pass in the attributes given an AST
14026   // representation, not a parser representation.
14027   if (D) {
14028     // FIXME: The current scope is almost... but not entirely... correct here.
14029     ProcessDeclAttributes(getCurScope(), NewFD, *D);
14030 
14031     if (NewFD->hasAttrs())
14032       CheckAlignasUnderalignment(NewFD);
14033   }
14034 
14035   // In auto-retain/release, infer strong retension for fields of
14036   // retainable type.
14037   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
14038     NewFD->setInvalidDecl();
14039 
14040   if (T.isObjCGCWeak())
14041     Diag(Loc, diag::warn_attribute_weak_on_field);
14042 
14043   NewFD->setAccess(AS);
14044   return NewFD;
14045 }
14046 
14047 bool Sema::CheckNontrivialField(FieldDecl *FD) {
14048   assert(FD);
14049   assert(getLangOpts().CPlusPlus && "valid check only for C++");
14050 
14051   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
14052     return false;
14053 
14054   QualType EltTy = Context.getBaseElementType(FD->getType());
14055   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
14056     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
14057     if (RDecl->getDefinition()) {
14058       // We check for copy constructors before constructors
14059       // because otherwise we'll never get complaints about
14060       // copy constructors.
14061 
14062       CXXSpecialMember member = CXXInvalid;
14063       // We're required to check for any non-trivial constructors. Since the
14064       // implicit default constructor is suppressed if there are any
14065       // user-declared constructors, we just need to check that there is a
14066       // trivial default constructor and a trivial copy constructor. (We don't
14067       // worry about move constructors here, since this is a C++98 check.)
14068       if (RDecl->hasNonTrivialCopyConstructor())
14069         member = CXXCopyConstructor;
14070       else if (!RDecl->hasTrivialDefaultConstructor())
14071         member = CXXDefaultConstructor;
14072       else if (RDecl->hasNonTrivialCopyAssignment())
14073         member = CXXCopyAssignment;
14074       else if (RDecl->hasNonTrivialDestructor())
14075         member = CXXDestructor;
14076 
14077       if (member != CXXInvalid) {
14078         if (!getLangOpts().CPlusPlus11 &&
14079             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
14080           // Objective-C++ ARC: it is an error to have a non-trivial field of
14081           // a union. However, system headers in Objective-C programs
14082           // occasionally have Objective-C lifetime objects within unions,
14083           // and rather than cause the program to fail, we make those
14084           // members unavailable.
14085           SourceLocation Loc = FD->getLocation();
14086           if (getSourceManager().isInSystemHeader(Loc)) {
14087             if (!FD->hasAttr<UnavailableAttr>())
14088               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14089                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
14090             return false;
14091           }
14092         }
14093 
14094         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
14095                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
14096                diag::err_illegal_union_or_anon_struct_member)
14097           << FD->getParent()->isUnion() << FD->getDeclName() << member;
14098         DiagnoseNontrivial(RDecl, member);
14099         return !getLangOpts().CPlusPlus11;
14100       }
14101     }
14102   }
14103 
14104   return false;
14105 }
14106 
14107 /// TranslateIvarVisibility - Translate visibility from a token ID to an
14108 ///  AST enum value.
14109 static ObjCIvarDecl::AccessControl
14110 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
14111   switch (ivarVisibility) {
14112   default: llvm_unreachable("Unknown visitibility kind");
14113   case tok::objc_private: return ObjCIvarDecl::Private;
14114   case tok::objc_public: return ObjCIvarDecl::Public;
14115   case tok::objc_protected: return ObjCIvarDecl::Protected;
14116   case tok::objc_package: return ObjCIvarDecl::Package;
14117   }
14118 }
14119 
14120 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
14121 /// in order to create an IvarDecl object for it.
14122 Decl *Sema::ActOnIvar(Scope *S,
14123                                 SourceLocation DeclStart,
14124                                 Declarator &D, Expr *BitfieldWidth,
14125                                 tok::ObjCKeywordKind Visibility) {
14126 
14127   IdentifierInfo *II = D.getIdentifier();
14128   Expr *BitWidth = (Expr*)BitfieldWidth;
14129   SourceLocation Loc = DeclStart;
14130   if (II) Loc = D.getIdentifierLoc();
14131 
14132   // FIXME: Unnamed fields can be handled in various different ways, for
14133   // example, unnamed unions inject all members into the struct namespace!
14134 
14135   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14136   QualType T = TInfo->getType();
14137 
14138   if (BitWidth) {
14139     // 6.7.2.1p3, 6.7.2.1p4
14140     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
14141     if (!BitWidth)
14142       D.setInvalidType();
14143   } else {
14144     // Not a bitfield.
14145 
14146     // validate II.
14147 
14148   }
14149   if (T->isReferenceType()) {
14150     Diag(Loc, diag::err_ivar_reference_type);
14151     D.setInvalidType();
14152   }
14153   // C99 6.7.2.1p8: A member of a structure or union may have any type other
14154   // than a variably modified type.
14155   else if (T->isVariablyModifiedType()) {
14156     Diag(Loc, diag::err_typecheck_ivar_variable_size);
14157     D.setInvalidType();
14158   }
14159 
14160   // Get the visibility (access control) for this ivar.
14161   ObjCIvarDecl::AccessControl ac =
14162     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
14163                                         : ObjCIvarDecl::None;
14164   // Must set ivar's DeclContext to its enclosing interface.
14165   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
14166   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
14167     return nullptr;
14168   ObjCContainerDecl *EnclosingContext;
14169   if (ObjCImplementationDecl *IMPDecl =
14170       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14171     if (LangOpts.ObjCRuntime.isFragile()) {
14172     // Case of ivar declared in an implementation. Context is that of its class.
14173       EnclosingContext = IMPDecl->getClassInterface();
14174       assert(EnclosingContext && "Implementation has no class interface!");
14175     }
14176     else
14177       EnclosingContext = EnclosingDecl;
14178   } else {
14179     if (ObjCCategoryDecl *CDecl =
14180         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14181       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
14182         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
14183         return nullptr;
14184       }
14185     }
14186     EnclosingContext = EnclosingDecl;
14187   }
14188 
14189   // Construct the decl.
14190   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
14191                                              DeclStart, Loc, II, T,
14192                                              TInfo, ac, (Expr *)BitfieldWidth);
14193 
14194   if (II) {
14195     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
14196                                            ForRedeclaration);
14197     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
14198         && !isa<TagDecl>(PrevDecl)) {
14199       Diag(Loc, diag::err_duplicate_member) << II;
14200       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14201       NewID->setInvalidDecl();
14202     }
14203   }
14204 
14205   // Process attributes attached to the ivar.
14206   ProcessDeclAttributes(S, NewID, D);
14207 
14208   if (D.isInvalidType())
14209     NewID->setInvalidDecl();
14210 
14211   // In ARC, infer 'retaining' for ivars of retainable type.
14212   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
14213     NewID->setInvalidDecl();
14214 
14215   if (D.getDeclSpec().isModulePrivateSpecified())
14216     NewID->setModulePrivate();
14217 
14218   if (II) {
14219     // FIXME: When interfaces are DeclContexts, we'll need to add
14220     // these to the interface.
14221     S->AddDecl(NewID);
14222     IdResolver.AddDecl(NewID);
14223   }
14224 
14225   if (LangOpts.ObjCRuntime.isNonFragile() &&
14226       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
14227     Diag(Loc, diag::warn_ivars_in_interface);
14228 
14229   return NewID;
14230 }
14231 
14232 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
14233 /// class and class extensions. For every class \@interface and class
14234 /// extension \@interface, if the last ivar is a bitfield of any type,
14235 /// then add an implicit `char :0` ivar to the end of that interface.
14236 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
14237                              SmallVectorImpl<Decl *> &AllIvarDecls) {
14238   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
14239     return;
14240 
14241   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
14242   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
14243 
14244   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
14245     return;
14246   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
14247   if (!ID) {
14248     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
14249       if (!CD->IsClassExtension())
14250         return;
14251     }
14252     // No need to add this to end of @implementation.
14253     else
14254       return;
14255   }
14256   // All conditions are met. Add a new bitfield to the tail end of ivars.
14257   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
14258   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
14259 
14260   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
14261                               DeclLoc, DeclLoc, nullptr,
14262                               Context.CharTy,
14263                               Context.getTrivialTypeSourceInfo(Context.CharTy,
14264                                                                DeclLoc),
14265                               ObjCIvarDecl::Private, BW,
14266                               true);
14267   AllIvarDecls.push_back(Ivar);
14268 }
14269 
14270 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
14271                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
14272                        SourceLocation RBrac, AttributeList *Attr) {
14273   assert(EnclosingDecl && "missing record or interface decl");
14274 
14275   // If this is an Objective-C @implementation or category and we have
14276   // new fields here we should reset the layout of the interface since
14277   // it will now change.
14278   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
14279     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
14280     switch (DC->getKind()) {
14281     default: break;
14282     case Decl::ObjCCategory:
14283       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
14284       break;
14285     case Decl::ObjCImplementation:
14286       Context.
14287         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
14288       break;
14289     }
14290   }
14291 
14292   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
14293 
14294   // Start counting up the number of named members; make sure to include
14295   // members of anonymous structs and unions in the total.
14296   unsigned NumNamedMembers = 0;
14297   if (Record) {
14298     for (const auto *I : Record->decls()) {
14299       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
14300         if (IFD->getDeclName())
14301           ++NumNamedMembers;
14302     }
14303   }
14304 
14305   // Verify that all the fields are okay.
14306   SmallVector<FieldDecl*, 32> RecFields;
14307 
14308   bool ARCErrReported = false;
14309   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
14310        i != end; ++i) {
14311     FieldDecl *FD = cast<FieldDecl>(*i);
14312 
14313     // Get the type for the field.
14314     const Type *FDTy = FD->getType().getTypePtr();
14315 
14316     if (!FD->isAnonymousStructOrUnion()) {
14317       // Remember all fields written by the user.
14318       RecFields.push_back(FD);
14319     }
14320 
14321     // If the field is already invalid for some reason, don't emit more
14322     // diagnostics about it.
14323     if (FD->isInvalidDecl()) {
14324       EnclosingDecl->setInvalidDecl();
14325       continue;
14326     }
14327 
14328     // C99 6.7.2.1p2:
14329     //   A structure or union shall not contain a member with
14330     //   incomplete or function type (hence, a structure shall not
14331     //   contain an instance of itself, but may contain a pointer to
14332     //   an instance of itself), except that the last member of a
14333     //   structure with more than one named member may have incomplete
14334     //   array type; such a structure (and any union containing,
14335     //   possibly recursively, a member that is such a structure)
14336     //   shall not be a member of a structure or an element of an
14337     //   array.
14338     if (FDTy->isFunctionType()) {
14339       // Field declared as a function.
14340       Diag(FD->getLocation(), diag::err_field_declared_as_function)
14341         << FD->getDeclName();
14342       FD->setInvalidDecl();
14343       EnclosingDecl->setInvalidDecl();
14344       continue;
14345     } else if (FDTy->isIncompleteArrayType() && Record &&
14346                ((i + 1 == Fields.end() && !Record->isUnion()) ||
14347                 ((getLangOpts().MicrosoftExt ||
14348                   getLangOpts().CPlusPlus) &&
14349                  (i + 1 == Fields.end() || Record->isUnion())))) {
14350       // Flexible array member.
14351       // Microsoft and g++ is more permissive regarding flexible array.
14352       // It will accept flexible array in union and also
14353       // as the sole element of a struct/class.
14354       unsigned DiagID = 0;
14355       if (Record->isUnion())
14356         DiagID = getLangOpts().MicrosoftExt
14357                      ? diag::ext_flexible_array_union_ms
14358                      : getLangOpts().CPlusPlus
14359                            ? diag::ext_flexible_array_union_gnu
14360                            : diag::err_flexible_array_union;
14361       else if (NumNamedMembers < 1)
14362         DiagID = getLangOpts().MicrosoftExt
14363                      ? diag::ext_flexible_array_empty_aggregate_ms
14364                      : getLangOpts().CPlusPlus
14365                            ? diag::ext_flexible_array_empty_aggregate_gnu
14366                            : diag::err_flexible_array_empty_aggregate;
14367 
14368       if (DiagID)
14369         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
14370                                         << Record->getTagKind();
14371       // While the layout of types that contain virtual bases is not specified
14372       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
14373       // virtual bases after the derived members.  This would make a flexible
14374       // array member declared at the end of an object not adjacent to the end
14375       // of the type.
14376       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
14377         if (RD->getNumVBases() != 0)
14378           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
14379             << FD->getDeclName() << Record->getTagKind();
14380       if (!getLangOpts().C99)
14381         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
14382           << FD->getDeclName() << Record->getTagKind();
14383 
14384       // If the element type has a non-trivial destructor, we would not
14385       // implicitly destroy the elements, so disallow it for now.
14386       //
14387       // FIXME: GCC allows this. We should probably either implicitly delete
14388       // the destructor of the containing class, or just allow this.
14389       QualType BaseElem = Context.getBaseElementType(FD->getType());
14390       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
14391         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
14392           << FD->getDeclName() << FD->getType();
14393         FD->setInvalidDecl();
14394         EnclosingDecl->setInvalidDecl();
14395         continue;
14396       }
14397       // Okay, we have a legal flexible array member at the end of the struct.
14398       Record->setHasFlexibleArrayMember(true);
14399     } else if (!FDTy->isDependentType() &&
14400                RequireCompleteType(FD->getLocation(), FD->getType(),
14401                                    diag::err_field_incomplete)) {
14402       // Incomplete type
14403       FD->setInvalidDecl();
14404       EnclosingDecl->setInvalidDecl();
14405       continue;
14406     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
14407       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
14408         // A type which contains a flexible array member is considered to be a
14409         // flexible array member.
14410         Record->setHasFlexibleArrayMember(true);
14411         if (!Record->isUnion()) {
14412           // If this is a struct/class and this is not the last element, reject
14413           // it.  Note that GCC supports variable sized arrays in the middle of
14414           // structures.
14415           if (i + 1 != Fields.end())
14416             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
14417               << FD->getDeclName() << FD->getType();
14418           else {
14419             // We support flexible arrays at the end of structs in
14420             // other structs as an extension.
14421             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
14422               << FD->getDeclName();
14423           }
14424         }
14425       }
14426       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
14427           RequireNonAbstractType(FD->getLocation(), FD->getType(),
14428                                  diag::err_abstract_type_in_decl,
14429                                  AbstractIvarType)) {
14430         // Ivars can not have abstract class types
14431         FD->setInvalidDecl();
14432       }
14433       if (Record && FDTTy->getDecl()->hasObjectMember())
14434         Record->setHasObjectMember(true);
14435       if (Record && FDTTy->getDecl()->hasVolatileMember())
14436         Record->setHasVolatileMember(true);
14437     } else if (FDTy->isObjCObjectType()) {
14438       /// A field cannot be an Objective-c object
14439       Diag(FD->getLocation(), diag::err_statically_allocated_object)
14440         << FixItHint::CreateInsertion(FD->getLocation(), "*");
14441       QualType T = Context.getObjCObjectPointerType(FD->getType());
14442       FD->setType(T);
14443     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
14444                (!getLangOpts().CPlusPlus || Record->isUnion())) {
14445       // It's an error in ARC if a field has lifetime.
14446       // We don't want to report this in a system header, though,
14447       // so we just make the field unavailable.
14448       // FIXME: that's really not sufficient; we need to make the type
14449       // itself invalid to, say, initialize or copy.
14450       QualType T = FD->getType();
14451       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
14452       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
14453         SourceLocation loc = FD->getLocation();
14454         if (getSourceManager().isInSystemHeader(loc)) {
14455           if (!FD->hasAttr<UnavailableAttr>()) {
14456             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
14457                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
14458           }
14459         } else {
14460           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
14461             << T->isBlockPointerType() << Record->getTagKind();
14462         }
14463         ARCErrReported = true;
14464       }
14465     } else if (getLangOpts().ObjC1 &&
14466                getLangOpts().getGC() != LangOptions::NonGC &&
14467                Record && !Record->hasObjectMember()) {
14468       if (FD->getType()->isObjCObjectPointerType() ||
14469           FD->getType().isObjCGCStrong())
14470         Record->setHasObjectMember(true);
14471       else if (Context.getAsArrayType(FD->getType())) {
14472         QualType BaseType = Context.getBaseElementType(FD->getType());
14473         if (BaseType->isRecordType() &&
14474             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
14475           Record->setHasObjectMember(true);
14476         else if (BaseType->isObjCObjectPointerType() ||
14477                  BaseType.isObjCGCStrong())
14478                Record->setHasObjectMember(true);
14479       }
14480     }
14481     if (Record && FD->getType().isVolatileQualified())
14482       Record->setHasVolatileMember(true);
14483     // Keep track of the number of named members.
14484     if (FD->getIdentifier())
14485       ++NumNamedMembers;
14486   }
14487 
14488   // Okay, we successfully defined 'Record'.
14489   if (Record) {
14490     bool Completed = false;
14491     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14492       if (!CXXRecord->isInvalidDecl()) {
14493         // Set access bits correctly on the directly-declared conversions.
14494         for (CXXRecordDecl::conversion_iterator
14495                I = CXXRecord->conversion_begin(),
14496                E = CXXRecord->conversion_end(); I != E; ++I)
14497           I.setAccess((*I)->getAccess());
14498       }
14499 
14500       if (!CXXRecord->isDependentType()) {
14501         if (CXXRecord->hasUserDeclaredDestructor()) {
14502           // Adjust user-defined destructor exception spec.
14503           if (getLangOpts().CPlusPlus11)
14504             AdjustDestructorExceptionSpec(CXXRecord,
14505                                           CXXRecord->getDestructor());
14506         }
14507 
14508         if (!CXXRecord->isInvalidDecl()) {
14509           // Add any implicitly-declared members to this class.
14510           AddImplicitlyDeclaredMembersToClass(CXXRecord);
14511 
14512           // If we have virtual base classes, we may end up finding multiple
14513           // final overriders for a given virtual function. Check for this
14514           // problem now.
14515           if (CXXRecord->getNumVBases()) {
14516             CXXFinalOverriderMap FinalOverriders;
14517             CXXRecord->getFinalOverriders(FinalOverriders);
14518 
14519             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
14520                                              MEnd = FinalOverriders.end();
14521                  M != MEnd; ++M) {
14522               for (OverridingMethods::iterator SO = M->second.begin(),
14523                                             SOEnd = M->second.end();
14524                    SO != SOEnd; ++SO) {
14525                 assert(SO->second.size() > 0 &&
14526                        "Virtual function without overridding functions?");
14527                 if (SO->second.size() == 1)
14528                   continue;
14529 
14530                 // C++ [class.virtual]p2:
14531                 //   In a derived class, if a virtual member function of a base
14532                 //   class subobject has more than one final overrider the
14533                 //   program is ill-formed.
14534                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
14535                   << (const NamedDecl *)M->first << Record;
14536                 Diag(M->first->getLocation(),
14537                      diag::note_overridden_virtual_function);
14538                 for (OverridingMethods::overriding_iterator
14539                           OM = SO->second.begin(),
14540                        OMEnd = SO->second.end();
14541                      OM != OMEnd; ++OM)
14542                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
14543                     << (const NamedDecl *)M->first << OM->Method->getParent();
14544 
14545                 Record->setInvalidDecl();
14546               }
14547             }
14548             CXXRecord->completeDefinition(&FinalOverriders);
14549             Completed = true;
14550           }
14551         }
14552       }
14553     }
14554 
14555     if (!Completed)
14556       Record->completeDefinition();
14557 
14558     // We may have deferred checking for a deleted destructor. Check now.
14559     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14560       auto *Dtor = CXXRecord->getDestructor();
14561       if (Dtor && Dtor->isImplicit() &&
14562           ShouldDeleteSpecialMember(Dtor, CXXDestructor))
14563         SetDeclDeleted(Dtor, CXXRecord->getLocation());
14564     }
14565 
14566     if (Record->hasAttrs()) {
14567       CheckAlignasUnderalignment(Record);
14568 
14569       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
14570         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
14571                                            IA->getRange(), IA->getBestCase(),
14572                                            IA->getSemanticSpelling());
14573     }
14574 
14575     // Check if the structure/union declaration is a type that can have zero
14576     // size in C. For C this is a language extension, for C++ it may cause
14577     // compatibility problems.
14578     bool CheckForZeroSize;
14579     if (!getLangOpts().CPlusPlus) {
14580       CheckForZeroSize = true;
14581     } else {
14582       // For C++ filter out types that cannot be referenced in C code.
14583       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
14584       CheckForZeroSize =
14585           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
14586           !CXXRecord->isDependentType() &&
14587           CXXRecord->isCLike();
14588     }
14589     if (CheckForZeroSize) {
14590       bool ZeroSize = true;
14591       bool IsEmpty = true;
14592       unsigned NonBitFields = 0;
14593       for (RecordDecl::field_iterator I = Record->field_begin(),
14594                                       E = Record->field_end();
14595            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
14596         IsEmpty = false;
14597         if (I->isUnnamedBitfield()) {
14598           if (I->getBitWidthValue(Context) > 0)
14599             ZeroSize = false;
14600         } else {
14601           ++NonBitFields;
14602           QualType FieldType = I->getType();
14603           if (FieldType->isIncompleteType() ||
14604               !Context.getTypeSizeInChars(FieldType).isZero())
14605             ZeroSize = false;
14606         }
14607       }
14608 
14609       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
14610       // allowed in C++, but warn if its declaration is inside
14611       // extern "C" block.
14612       if (ZeroSize) {
14613         Diag(RecLoc, getLangOpts().CPlusPlus ?
14614                          diag::warn_zero_size_struct_union_in_extern_c :
14615                          diag::warn_zero_size_struct_union_compat)
14616           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
14617       }
14618 
14619       // Structs without named members are extension in C (C99 6.7.2.1p7),
14620       // but are accepted by GCC.
14621       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
14622         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
14623                                diag::ext_no_named_members_in_struct_union)
14624           << Record->isUnion();
14625       }
14626     }
14627   } else {
14628     ObjCIvarDecl **ClsFields =
14629       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
14630     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
14631       ID->setEndOfDefinitionLoc(RBrac);
14632       // Add ivar's to class's DeclContext.
14633       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14634         ClsFields[i]->setLexicalDeclContext(ID);
14635         ID->addDecl(ClsFields[i]);
14636       }
14637       // Must enforce the rule that ivars in the base classes may not be
14638       // duplicates.
14639       if (ID->getSuperClass())
14640         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
14641     } else if (ObjCImplementationDecl *IMPDecl =
14642                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14643       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
14644       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
14645         // Ivar declared in @implementation never belongs to the implementation.
14646         // Only it is in implementation's lexical context.
14647         ClsFields[I]->setLexicalDeclContext(IMPDecl);
14648       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
14649       IMPDecl->setIvarLBraceLoc(LBrac);
14650       IMPDecl->setIvarRBraceLoc(RBrac);
14651     } else if (ObjCCategoryDecl *CDecl =
14652                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14653       // case of ivars in class extension; all other cases have been
14654       // reported as errors elsewhere.
14655       // FIXME. Class extension does not have a LocEnd field.
14656       // CDecl->setLocEnd(RBrac);
14657       // Add ivar's to class extension's DeclContext.
14658       // Diagnose redeclaration of private ivars.
14659       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
14660       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14661         if (IDecl) {
14662           if (const ObjCIvarDecl *ClsIvar =
14663               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
14664             Diag(ClsFields[i]->getLocation(),
14665                  diag::err_duplicate_ivar_declaration);
14666             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
14667             continue;
14668           }
14669           for (const auto *Ext : IDecl->known_extensions()) {
14670             if (const ObjCIvarDecl *ClsExtIvar
14671                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
14672               Diag(ClsFields[i]->getLocation(),
14673                    diag::err_duplicate_ivar_declaration);
14674               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
14675               continue;
14676             }
14677           }
14678         }
14679         ClsFields[i]->setLexicalDeclContext(CDecl);
14680         CDecl->addDecl(ClsFields[i]);
14681       }
14682       CDecl->setIvarLBraceLoc(LBrac);
14683       CDecl->setIvarRBraceLoc(RBrac);
14684     }
14685   }
14686 
14687   if (Attr)
14688     ProcessDeclAttributeList(S, Record, Attr);
14689 }
14690 
14691 /// \brief Determine whether the given integral value is representable within
14692 /// the given type T.
14693 static bool isRepresentableIntegerValue(ASTContext &Context,
14694                                         llvm::APSInt &Value,
14695                                         QualType T) {
14696   assert(T->isIntegralType(Context) && "Integral type required!");
14697   unsigned BitWidth = Context.getIntWidth(T);
14698 
14699   if (Value.isUnsigned() || Value.isNonNegative()) {
14700     if (T->isSignedIntegerOrEnumerationType())
14701       --BitWidth;
14702     return Value.getActiveBits() <= BitWidth;
14703   }
14704   return Value.getMinSignedBits() <= BitWidth;
14705 }
14706 
14707 // \brief Given an integral type, return the next larger integral type
14708 // (or a NULL type of no such type exists).
14709 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
14710   // FIXME: Int128/UInt128 support, which also needs to be introduced into
14711   // enum checking below.
14712   assert(T->isIntegralType(Context) && "Integral type required!");
14713   const unsigned NumTypes = 4;
14714   QualType SignedIntegralTypes[NumTypes] = {
14715     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
14716   };
14717   QualType UnsignedIntegralTypes[NumTypes] = {
14718     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
14719     Context.UnsignedLongLongTy
14720   };
14721 
14722   unsigned BitWidth = Context.getTypeSize(T);
14723   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
14724                                                         : UnsignedIntegralTypes;
14725   for (unsigned I = 0; I != NumTypes; ++I)
14726     if (Context.getTypeSize(Types[I]) > BitWidth)
14727       return Types[I];
14728 
14729   return QualType();
14730 }
14731 
14732 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
14733                                           EnumConstantDecl *LastEnumConst,
14734                                           SourceLocation IdLoc,
14735                                           IdentifierInfo *Id,
14736                                           Expr *Val) {
14737   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14738   llvm::APSInt EnumVal(IntWidth);
14739   QualType EltTy;
14740 
14741   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
14742     Val = nullptr;
14743 
14744   if (Val)
14745     Val = DefaultLvalueConversion(Val).get();
14746 
14747   if (Val) {
14748     if (Enum->isDependentType() || Val->isTypeDependent())
14749       EltTy = Context.DependentTy;
14750     else {
14751       SourceLocation ExpLoc;
14752       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
14753           !getLangOpts().MSVCCompat) {
14754         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
14755         // constant-expression in the enumerator-definition shall be a converted
14756         // constant expression of the underlying type.
14757         EltTy = Enum->getIntegerType();
14758         ExprResult Converted =
14759           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
14760                                            CCEK_Enumerator);
14761         if (Converted.isInvalid())
14762           Val = nullptr;
14763         else
14764           Val = Converted.get();
14765       } else if (!Val->isValueDependent() &&
14766                  !(Val = VerifyIntegerConstantExpression(Val,
14767                                                          &EnumVal).get())) {
14768         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
14769       } else {
14770         if (Enum->isFixed()) {
14771           EltTy = Enum->getIntegerType();
14772 
14773           // In Obj-C and Microsoft mode, require the enumeration value to be
14774           // representable in the underlying type of the enumeration. In C++11,
14775           // we perform a non-narrowing conversion as part of converted constant
14776           // expression checking.
14777           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14778             if (getLangOpts().MSVCCompat) {
14779               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
14780               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
14781             } else
14782               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
14783           } else
14784             Val = ImpCastExprToType(Val, EltTy,
14785                                     EltTy->isBooleanType() ?
14786                                     CK_IntegralToBoolean : CK_IntegralCast)
14787                     .get();
14788         } else if (getLangOpts().CPlusPlus) {
14789           // C++11 [dcl.enum]p5:
14790           //   If the underlying type is not fixed, the type of each enumerator
14791           //   is the type of its initializing value:
14792           //     - If an initializer is specified for an enumerator, the
14793           //       initializing value has the same type as the expression.
14794           EltTy = Val->getType();
14795         } else {
14796           // C99 6.7.2.2p2:
14797           //   The expression that defines the value of an enumeration constant
14798           //   shall be an integer constant expression that has a value
14799           //   representable as an int.
14800 
14801           // Complain if the value is not representable in an int.
14802           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
14803             Diag(IdLoc, diag::ext_enum_value_not_int)
14804               << EnumVal.toString(10) << Val->getSourceRange()
14805               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
14806           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
14807             // Force the type of the expression to 'int'.
14808             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
14809           }
14810           EltTy = Val->getType();
14811         }
14812       }
14813     }
14814   }
14815 
14816   if (!Val) {
14817     if (Enum->isDependentType())
14818       EltTy = Context.DependentTy;
14819     else if (!LastEnumConst) {
14820       // C++0x [dcl.enum]p5:
14821       //   If the underlying type is not fixed, the type of each enumerator
14822       //   is the type of its initializing value:
14823       //     - If no initializer is specified for the first enumerator, the
14824       //       initializing value has an unspecified integral type.
14825       //
14826       // GCC uses 'int' for its unspecified integral type, as does
14827       // C99 6.7.2.2p3.
14828       if (Enum->isFixed()) {
14829         EltTy = Enum->getIntegerType();
14830       }
14831       else {
14832         EltTy = Context.IntTy;
14833       }
14834     } else {
14835       // Assign the last value + 1.
14836       EnumVal = LastEnumConst->getInitVal();
14837       ++EnumVal;
14838       EltTy = LastEnumConst->getType();
14839 
14840       // Check for overflow on increment.
14841       if (EnumVal < LastEnumConst->getInitVal()) {
14842         // C++0x [dcl.enum]p5:
14843         //   If the underlying type is not fixed, the type of each enumerator
14844         //   is the type of its initializing value:
14845         //
14846         //     - Otherwise the type of the initializing value is the same as
14847         //       the type of the initializing value of the preceding enumerator
14848         //       unless the incremented value is not representable in that type,
14849         //       in which case the type is an unspecified integral type
14850         //       sufficient to contain the incremented value. If no such type
14851         //       exists, the program is ill-formed.
14852         QualType T = getNextLargerIntegralType(Context, EltTy);
14853         if (T.isNull() || Enum->isFixed()) {
14854           // There is no integral type larger enough to represent this
14855           // value. Complain, then allow the value to wrap around.
14856           EnumVal = LastEnumConst->getInitVal();
14857           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
14858           ++EnumVal;
14859           if (Enum->isFixed())
14860             // When the underlying type is fixed, this is ill-formed.
14861             Diag(IdLoc, diag::err_enumerator_wrapped)
14862               << EnumVal.toString(10)
14863               << EltTy;
14864           else
14865             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
14866               << EnumVal.toString(10);
14867         } else {
14868           EltTy = T;
14869         }
14870 
14871         // Retrieve the last enumerator's value, extent that type to the
14872         // type that is supposed to be large enough to represent the incremented
14873         // value, then increment.
14874         EnumVal = LastEnumConst->getInitVal();
14875         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14876         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
14877         ++EnumVal;
14878 
14879         // If we're not in C++, diagnose the overflow of enumerator values,
14880         // which in C99 means that the enumerator value is not representable in
14881         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
14882         // permits enumerator values that are representable in some larger
14883         // integral type.
14884         if (!getLangOpts().CPlusPlus && !T.isNull())
14885           Diag(IdLoc, diag::warn_enum_value_overflow);
14886       } else if (!getLangOpts().CPlusPlus &&
14887                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14888         // Enforce C99 6.7.2.2p2 even when we compute the next value.
14889         Diag(IdLoc, diag::ext_enum_value_not_int)
14890           << EnumVal.toString(10) << 1;
14891       }
14892     }
14893   }
14894 
14895   if (!EltTy->isDependentType()) {
14896     // Make the enumerator value match the signedness and size of the
14897     // enumerator's type.
14898     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
14899     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14900   }
14901 
14902   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
14903                                   Val, EnumVal);
14904 }
14905 
14906 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
14907                                                 SourceLocation IILoc) {
14908   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
14909       !getLangOpts().CPlusPlus)
14910     return SkipBodyInfo();
14911 
14912   // We have an anonymous enum definition. Look up the first enumerator to
14913   // determine if we should merge the definition with an existing one and
14914   // skip the body.
14915   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
14916                                          ForRedeclaration);
14917   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
14918   if (!PrevECD)
14919     return SkipBodyInfo();
14920 
14921   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
14922   NamedDecl *Hidden;
14923   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
14924     SkipBodyInfo Skip;
14925     Skip.Previous = Hidden;
14926     return Skip;
14927   }
14928 
14929   return SkipBodyInfo();
14930 }
14931 
14932 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
14933                               SourceLocation IdLoc, IdentifierInfo *Id,
14934                               AttributeList *Attr,
14935                               SourceLocation EqualLoc, Expr *Val) {
14936   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
14937   EnumConstantDecl *LastEnumConst =
14938     cast_or_null<EnumConstantDecl>(lastEnumConst);
14939 
14940   // The scope passed in may not be a decl scope.  Zip up the scope tree until
14941   // we find one that is.
14942   S = getNonFieldDeclScope(S);
14943 
14944   // Verify that there isn't already something declared with this name in this
14945   // scope.
14946   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
14947                                          ForRedeclaration);
14948   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14949     // Maybe we will complain about the shadowed template parameter.
14950     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
14951     // Just pretend that we didn't see the previous declaration.
14952     PrevDecl = nullptr;
14953   }
14954 
14955   // C++ [class.mem]p15:
14956   // If T is the name of a class, then each of the following shall have a name
14957   // different from T:
14958   // - every enumerator of every member of class T that is an unscoped
14959   // enumerated type
14960   if (!TheEnumDecl->isScoped())
14961     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
14962                             DeclarationNameInfo(Id, IdLoc));
14963 
14964   EnumConstantDecl *New =
14965     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
14966   if (!New)
14967     return nullptr;
14968 
14969   if (PrevDecl) {
14970     // When in C++, we may get a TagDecl with the same name; in this case the
14971     // enum constant will 'hide' the tag.
14972     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
14973            "Received TagDecl when not in C++!");
14974     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
14975         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
14976       if (isa<EnumConstantDecl>(PrevDecl))
14977         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
14978       else
14979         Diag(IdLoc, diag::err_redefinition) << Id;
14980       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14981       return nullptr;
14982     }
14983   }
14984 
14985   // Process attributes.
14986   if (Attr) ProcessDeclAttributeList(S, New, Attr);
14987 
14988   // Register this decl in the current scope stack.
14989   New->setAccess(TheEnumDecl->getAccess());
14990   PushOnScopeChains(New, S);
14991 
14992   ActOnDocumentableDecl(New);
14993 
14994   return New;
14995 }
14996 
14997 // Returns true when the enum initial expression does not trigger the
14998 // duplicate enum warning.  A few common cases are exempted as follows:
14999 // Element2 = Element1
15000 // Element2 = Element1 + 1
15001 // Element2 = Element1 - 1
15002 // Where Element2 and Element1 are from the same enum.
15003 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
15004   Expr *InitExpr = ECD->getInitExpr();
15005   if (!InitExpr)
15006     return true;
15007   InitExpr = InitExpr->IgnoreImpCasts();
15008 
15009   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
15010     if (!BO->isAdditiveOp())
15011       return true;
15012     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
15013     if (!IL)
15014       return true;
15015     if (IL->getValue() != 1)
15016       return true;
15017 
15018     InitExpr = BO->getLHS();
15019   }
15020 
15021   // This checks if the elements are from the same enum.
15022   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
15023   if (!DRE)
15024     return true;
15025 
15026   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
15027   if (!EnumConstant)
15028     return true;
15029 
15030   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
15031       Enum)
15032     return true;
15033 
15034   return false;
15035 }
15036 
15037 namespace {
15038 struct DupKey {
15039   int64_t val;
15040   bool isTombstoneOrEmptyKey;
15041   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
15042     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
15043 };
15044 
15045 static DupKey GetDupKey(const llvm::APSInt& Val) {
15046   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
15047                 false);
15048 }
15049 
15050 struct DenseMapInfoDupKey {
15051   static DupKey getEmptyKey() { return DupKey(0, true); }
15052   static DupKey getTombstoneKey() { return DupKey(1, true); }
15053   static unsigned getHashValue(const DupKey Key) {
15054     return (unsigned)(Key.val * 37);
15055   }
15056   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
15057     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
15058            LHS.val == RHS.val;
15059   }
15060 };
15061 } // end anonymous namespace
15062 
15063 // Emits a warning when an element is implicitly set a value that
15064 // a previous element has already been set to.
15065 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
15066                                         EnumDecl *Enum,
15067                                         QualType EnumType) {
15068   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
15069     return;
15070   // Avoid anonymous enums
15071   if (!Enum->getIdentifier())
15072     return;
15073 
15074   // Only check for small enums.
15075   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
15076     return;
15077 
15078   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
15079   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
15080 
15081   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
15082   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
15083           ValueToVectorMap;
15084 
15085   DuplicatesVector DupVector;
15086   ValueToVectorMap EnumMap;
15087 
15088   // Populate the EnumMap with all values represented by enum constants without
15089   // an initialier.
15090   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15091     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
15092 
15093     // Null EnumConstantDecl means a previous diagnostic has been emitted for
15094     // this constant.  Skip this enum since it may be ill-formed.
15095     if (!ECD) {
15096       return;
15097     }
15098 
15099     if (ECD->getInitExpr())
15100       continue;
15101 
15102     DupKey Key = GetDupKey(ECD->getInitVal());
15103     DeclOrVector &Entry = EnumMap[Key];
15104 
15105     // First time encountering this value.
15106     if (Entry.isNull())
15107       Entry = ECD;
15108   }
15109 
15110   // Create vectors for any values that has duplicates.
15111   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15112     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
15113     if (!ValidDuplicateEnum(ECD, Enum))
15114       continue;
15115 
15116     DupKey Key = GetDupKey(ECD->getInitVal());
15117 
15118     DeclOrVector& Entry = EnumMap[Key];
15119     if (Entry.isNull())
15120       continue;
15121 
15122     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
15123       // Ensure constants are different.
15124       if (D == ECD)
15125         continue;
15126 
15127       // Create new vector and push values onto it.
15128       ECDVector *Vec = new ECDVector();
15129       Vec->push_back(D);
15130       Vec->push_back(ECD);
15131 
15132       // Update entry to point to the duplicates vector.
15133       Entry = Vec;
15134 
15135       // Store the vector somewhere we can consult later for quick emission of
15136       // diagnostics.
15137       DupVector.push_back(Vec);
15138       continue;
15139     }
15140 
15141     ECDVector *Vec = Entry.get<ECDVector*>();
15142     // Make sure constants are not added more than once.
15143     if (*Vec->begin() == ECD)
15144       continue;
15145 
15146     Vec->push_back(ECD);
15147   }
15148 
15149   // Emit diagnostics.
15150   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
15151                                   DupVectorEnd = DupVector.end();
15152        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
15153     ECDVector *Vec = *DupVectorIter;
15154     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
15155 
15156     // Emit warning for one enum constant.
15157     ECDVector::iterator I = Vec->begin();
15158     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
15159       << (*I)->getName() << (*I)->getInitVal().toString(10)
15160       << (*I)->getSourceRange();
15161     ++I;
15162 
15163     // Emit one note for each of the remaining enum constants with
15164     // the same value.
15165     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
15166       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
15167         << (*I)->getName() << (*I)->getInitVal().toString(10)
15168         << (*I)->getSourceRange();
15169     delete Vec;
15170   }
15171 }
15172 
15173 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
15174                              bool AllowMask) const {
15175   assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
15176   assert(ED->isCompleteDefinition() && "expected enum definition");
15177 
15178   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
15179   llvm::APInt &FlagBits = R.first->second;
15180 
15181   if (R.second) {
15182     for (auto *E : ED->enumerators()) {
15183       const auto &EVal = E->getInitVal();
15184       // Only single-bit enumerators introduce new flag values.
15185       if (EVal.isPowerOf2())
15186         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
15187     }
15188   }
15189 
15190   // A value is in a flag enum if either its bits are a subset of the enum's
15191   // flag bits (the first condition) or we are allowing masks and the same is
15192   // true of its complement (the second condition). When masks are allowed, we
15193   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
15194   //
15195   // While it's true that any value could be used as a mask, the assumption is
15196   // that a mask will have all of the insignificant bits set. Anything else is
15197   // likely a logic error.
15198   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
15199   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
15200 }
15201 
15202 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange,
15203                          Decl *EnumDeclX,
15204                          ArrayRef<Decl *> Elements,
15205                          Scope *S, AttributeList *Attr) {
15206   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
15207   QualType EnumType = Context.getTypeDeclType(Enum);
15208 
15209   if (Attr)
15210     ProcessDeclAttributeList(S, Enum, Attr);
15211 
15212   if (Enum->isDependentType()) {
15213     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15214       EnumConstantDecl *ECD =
15215         cast_or_null<EnumConstantDecl>(Elements[i]);
15216       if (!ECD) continue;
15217 
15218       ECD->setType(EnumType);
15219     }
15220 
15221     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
15222     return;
15223   }
15224 
15225   // TODO: If the result value doesn't fit in an int, it must be a long or long
15226   // long value.  ISO C does not support this, but GCC does as an extension,
15227   // emit a warning.
15228   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
15229   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
15230   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
15231 
15232   // Verify that all the values are okay, compute the size of the values, and
15233   // reverse the list.
15234   unsigned NumNegativeBits = 0;
15235   unsigned NumPositiveBits = 0;
15236 
15237   // Keep track of whether all elements have type int.
15238   bool AllElementsInt = true;
15239 
15240   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
15241     EnumConstantDecl *ECD =
15242       cast_or_null<EnumConstantDecl>(Elements[i]);
15243     if (!ECD) continue;  // Already issued a diagnostic.
15244 
15245     const llvm::APSInt &InitVal = ECD->getInitVal();
15246 
15247     // Keep track of the size of positive and negative values.
15248     if (InitVal.isUnsigned() || InitVal.isNonNegative())
15249       NumPositiveBits = std::max(NumPositiveBits,
15250                                  (unsigned)InitVal.getActiveBits());
15251     else
15252       NumNegativeBits = std::max(NumNegativeBits,
15253                                  (unsigned)InitVal.getMinSignedBits());
15254 
15255     // Keep track of whether every enum element has type int (very commmon).
15256     if (AllElementsInt)
15257       AllElementsInt = ECD->getType() == Context.IntTy;
15258   }
15259 
15260   // Figure out the type that should be used for this enum.
15261   QualType BestType;
15262   unsigned BestWidth;
15263 
15264   // C++0x N3000 [conv.prom]p3:
15265   //   An rvalue of an unscoped enumeration type whose underlying
15266   //   type is not fixed can be converted to an rvalue of the first
15267   //   of the following types that can represent all the values of
15268   //   the enumeration: int, unsigned int, long int, unsigned long
15269   //   int, long long int, or unsigned long long int.
15270   // C99 6.4.4.3p2:
15271   //   An identifier declared as an enumeration constant has type int.
15272   // The C99 rule is modified by a gcc extension
15273   QualType BestPromotionType;
15274 
15275   bool Packed = Enum->hasAttr<PackedAttr>();
15276   // -fshort-enums is the equivalent to specifying the packed attribute on all
15277   // enum definitions.
15278   if (LangOpts.ShortEnums)
15279     Packed = true;
15280 
15281   if (Enum->isFixed()) {
15282     BestType = Enum->getIntegerType();
15283     if (BestType->isPromotableIntegerType())
15284       BestPromotionType = Context.getPromotedIntegerType(BestType);
15285     else
15286       BestPromotionType = BestType;
15287 
15288     BestWidth = Context.getIntWidth(BestType);
15289   }
15290   else if (NumNegativeBits) {
15291     // If there is a negative value, figure out the smallest integer type (of
15292     // int/long/longlong) that fits.
15293     // If it's packed, check also if it fits a char or a short.
15294     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
15295       BestType = Context.SignedCharTy;
15296       BestWidth = CharWidth;
15297     } else if (Packed && NumNegativeBits <= ShortWidth &&
15298                NumPositiveBits < ShortWidth) {
15299       BestType = Context.ShortTy;
15300       BestWidth = ShortWidth;
15301     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
15302       BestType = Context.IntTy;
15303       BestWidth = IntWidth;
15304     } else {
15305       BestWidth = Context.getTargetInfo().getLongWidth();
15306 
15307       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
15308         BestType = Context.LongTy;
15309       } else {
15310         BestWidth = Context.getTargetInfo().getLongLongWidth();
15311 
15312         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
15313           Diag(Enum->getLocation(), diag::ext_enum_too_large);
15314         BestType = Context.LongLongTy;
15315       }
15316     }
15317     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
15318   } else {
15319     // If there is no negative value, figure out the smallest type that fits
15320     // all of the enumerator values.
15321     // If it's packed, check also if it fits a char or a short.
15322     if (Packed && NumPositiveBits <= CharWidth) {
15323       BestType = Context.UnsignedCharTy;
15324       BestPromotionType = Context.IntTy;
15325       BestWidth = CharWidth;
15326     } else if (Packed && NumPositiveBits <= ShortWidth) {
15327       BestType = Context.UnsignedShortTy;
15328       BestPromotionType = Context.IntTy;
15329       BestWidth = ShortWidth;
15330     } else if (NumPositiveBits <= IntWidth) {
15331       BestType = Context.UnsignedIntTy;
15332       BestWidth = IntWidth;
15333       BestPromotionType
15334         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15335                            ? Context.UnsignedIntTy : Context.IntTy;
15336     } else if (NumPositiveBits <=
15337                (BestWidth = Context.getTargetInfo().getLongWidth())) {
15338       BestType = Context.UnsignedLongTy;
15339       BestPromotionType
15340         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15341                            ? Context.UnsignedLongTy : Context.LongTy;
15342     } else {
15343       BestWidth = Context.getTargetInfo().getLongLongWidth();
15344       assert(NumPositiveBits <= BestWidth &&
15345              "How could an initializer get larger than ULL?");
15346       BestType = Context.UnsignedLongLongTy;
15347       BestPromotionType
15348         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
15349                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
15350     }
15351   }
15352 
15353   // Loop over all of the enumerator constants, changing their types to match
15354   // the type of the enum if needed.
15355   for (auto *D : Elements) {
15356     auto *ECD = cast_or_null<EnumConstantDecl>(D);
15357     if (!ECD) continue;  // Already issued a diagnostic.
15358 
15359     // Standard C says the enumerators have int type, but we allow, as an
15360     // extension, the enumerators to be larger than int size.  If each
15361     // enumerator value fits in an int, type it as an int, otherwise type it the
15362     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
15363     // that X has type 'int', not 'unsigned'.
15364 
15365     // Determine whether the value fits into an int.
15366     llvm::APSInt InitVal = ECD->getInitVal();
15367 
15368     // If it fits into an integer type, force it.  Otherwise force it to match
15369     // the enum decl type.
15370     QualType NewTy;
15371     unsigned NewWidth;
15372     bool NewSign;
15373     if (!getLangOpts().CPlusPlus &&
15374         !Enum->isFixed() &&
15375         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
15376       NewTy = Context.IntTy;
15377       NewWidth = IntWidth;
15378       NewSign = true;
15379     } else if (ECD->getType() == BestType) {
15380       // Already the right type!
15381       if (getLangOpts().CPlusPlus)
15382         // C++ [dcl.enum]p4: Following the closing brace of an
15383         // enum-specifier, each enumerator has the type of its
15384         // enumeration.
15385         ECD->setType(EnumType);
15386       continue;
15387     } else {
15388       NewTy = BestType;
15389       NewWidth = BestWidth;
15390       NewSign = BestType->isSignedIntegerOrEnumerationType();
15391     }
15392 
15393     // Adjust the APSInt value.
15394     InitVal = InitVal.extOrTrunc(NewWidth);
15395     InitVal.setIsSigned(NewSign);
15396     ECD->setInitVal(InitVal);
15397 
15398     // Adjust the Expr initializer and type.
15399     if (ECD->getInitExpr() &&
15400         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
15401       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
15402                                                 CK_IntegralCast,
15403                                                 ECD->getInitExpr(),
15404                                                 /*base paths*/ nullptr,
15405                                                 VK_RValue));
15406     if (getLangOpts().CPlusPlus)
15407       // C++ [dcl.enum]p4: Following the closing brace of an
15408       // enum-specifier, each enumerator has the type of its
15409       // enumeration.
15410       ECD->setType(EnumType);
15411     else
15412       ECD->setType(NewTy);
15413   }
15414 
15415   Enum->completeDefinition(BestType, BestPromotionType,
15416                            NumPositiveBits, NumNegativeBits);
15417 
15418   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
15419 
15420   if (Enum->hasAttr<FlagEnumAttr>()) {
15421     for (Decl *D : Elements) {
15422       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
15423       if (!ECD) continue;  // Already issued a diagnostic.
15424 
15425       llvm::APSInt InitVal = ECD->getInitVal();
15426       if (InitVal != 0 && !InitVal.isPowerOf2() &&
15427           !IsValueInFlagEnum(Enum, InitVal, true))
15428         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
15429           << ECD << Enum;
15430     }
15431   }
15432 
15433   // Now that the enum type is defined, ensure it's not been underaligned.
15434   if (Enum->hasAttrs())
15435     CheckAlignasUnderalignment(Enum);
15436 }
15437 
15438 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
15439                                   SourceLocation StartLoc,
15440                                   SourceLocation EndLoc) {
15441   StringLiteral *AsmString = cast<StringLiteral>(expr);
15442 
15443   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
15444                                                    AsmString, StartLoc,
15445                                                    EndLoc);
15446   CurContext->addDecl(New);
15447   return New;
15448 }
15449 
15450 static void checkModuleImportContext(Sema &S, Module *M,
15451                                      SourceLocation ImportLoc, DeclContext *DC,
15452                                      bool FromInclude = false) {
15453   SourceLocation ExternCLoc;
15454 
15455   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
15456     switch (LSD->getLanguage()) {
15457     case LinkageSpecDecl::lang_c:
15458       if (ExternCLoc.isInvalid())
15459         ExternCLoc = LSD->getLocStart();
15460       break;
15461     case LinkageSpecDecl::lang_cxx:
15462       break;
15463     }
15464     DC = LSD->getParent();
15465   }
15466 
15467   while (isa<LinkageSpecDecl>(DC))
15468     DC = DC->getParent();
15469 
15470   if (!isa<TranslationUnitDecl>(DC)) {
15471     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
15472                           ? diag::ext_module_import_not_at_top_level_noop
15473                           : diag::err_module_import_not_at_top_level_fatal)
15474         << M->getFullModuleName() << DC;
15475     S.Diag(cast<Decl>(DC)->getLocStart(),
15476            diag::note_module_import_not_at_top_level) << DC;
15477   } else if (!M->IsExternC && ExternCLoc.isValid()) {
15478     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
15479       << M->getFullModuleName();
15480     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
15481   }
15482 }
15483 
15484 Sema::DeclGroupPtrTy Sema::ActOnModuleDecl(SourceLocation ModuleLoc,
15485                                            ModuleDeclKind MDK,
15486                                            ModuleIdPath Path) {
15487   // 'module implementation' requires that we are not compiling a module of any
15488   // kind. 'module' and 'module partition' require that we are compiling a
15489   // module inteface (not a module map).
15490   auto CMK = getLangOpts().getCompilingModule();
15491   if (MDK == ModuleDeclKind::Implementation
15492           ? CMK != LangOptions::CMK_None
15493           : CMK != LangOptions::CMK_ModuleInterface) {
15494     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
15495       << (unsigned)MDK;
15496     return nullptr;
15497   }
15498 
15499   // FIXME: Create a ModuleDecl and return it.
15500 
15501   // FIXME: Most of this work should be done by the preprocessor rather than
15502   // here, in case we look ahead across something where the current
15503   // module matters (eg a #include).
15504 
15505   // The dots in a module name in the Modules TS are a lie. Unlike Clang's
15506   // hierarchical module map modules, the dots here are just another character
15507   // that can appear in a module name. Flatten down to the actual module name.
15508   std::string ModuleName;
15509   for (auto &Piece : Path) {
15510     if (!ModuleName.empty())
15511       ModuleName += ".";
15512     ModuleName += Piece.first->getName();
15513   }
15514 
15515   // If a module name was explicitly specified on the command line, it must be
15516   // correct.
15517   if (!getLangOpts().CurrentModule.empty() &&
15518       getLangOpts().CurrentModule != ModuleName) {
15519     Diag(Path.front().second, diag::err_current_module_name_mismatch)
15520         << SourceRange(Path.front().second, Path.back().second)
15521         << getLangOpts().CurrentModule;
15522     return nullptr;
15523   }
15524   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
15525 
15526   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
15527 
15528   switch (MDK) {
15529   case ModuleDeclKind::Module: {
15530     // FIXME: Check we're not in a submodule.
15531 
15532     // We can't have imported a definition of this module or parsed a module
15533     // map defining it already.
15534     if (auto *M = Map.findModule(ModuleName)) {
15535       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
15536       if (M->DefinitionLoc.isValid())
15537         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
15538       else if (const auto *FE = M->getASTFile())
15539         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
15540             << FE->getName();
15541       return nullptr;
15542     }
15543 
15544     // Create a Module for the module that we're defining.
15545     Module *Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
15546     assert(Mod && "module creation should not fail");
15547 
15548     // Enter the semantic scope of the module.
15549     ActOnModuleBegin(ModuleLoc, Mod);
15550     return nullptr;
15551   }
15552 
15553   case ModuleDeclKind::Partition:
15554     // FIXME: Check we are in a submodule of the named module.
15555     return nullptr;
15556 
15557   case ModuleDeclKind::Implementation:
15558     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
15559         PP.getIdentifierInfo(ModuleName), Path[0].second);
15560 
15561     DeclResult Import = ActOnModuleImport(ModuleLoc, ModuleLoc, ModuleNameLoc);
15562     if (Import.isInvalid())
15563       return nullptr;
15564     return ConvertDeclToDeclGroup(Import.get());
15565   }
15566 
15567   llvm_unreachable("unexpected module decl kind");
15568 }
15569 
15570 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
15571                                    SourceLocation ImportLoc,
15572                                    ModuleIdPath Path) {
15573   Module *Mod =
15574       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
15575                                    /*IsIncludeDirective=*/false);
15576   if (!Mod)
15577     return true;
15578 
15579   VisibleModules.setVisible(Mod, ImportLoc);
15580 
15581   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
15582 
15583   // FIXME: we should support importing a submodule within a different submodule
15584   // of the same top-level module. Until we do, make it an error rather than
15585   // silently ignoring the import.
15586   // Import-from-implementation is valid in the Modules TS. FIXME: Should we
15587   // warn on a redundant import of the current module?
15588   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
15589       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS))
15590     Diag(ImportLoc, getLangOpts().isCompilingModule()
15591                         ? diag::err_module_self_import
15592                         : diag::err_module_import_in_implementation)
15593         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
15594 
15595   SmallVector<SourceLocation, 2> IdentifierLocs;
15596   Module *ModCheck = Mod;
15597   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
15598     // If we've run out of module parents, just drop the remaining identifiers.
15599     // We need the length to be consistent.
15600     if (!ModCheck)
15601       break;
15602     ModCheck = ModCheck->Parent;
15603 
15604     IdentifierLocs.push_back(Path[I].second);
15605   }
15606 
15607   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15608   ImportDecl *Import = ImportDecl::Create(Context, TU, StartLoc,
15609                                           Mod, IdentifierLocs);
15610   if (!ModuleScopes.empty())
15611     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
15612   TU->addDecl(Import);
15613   return Import;
15614 }
15615 
15616 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15617   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15618   BuildModuleInclude(DirectiveLoc, Mod);
15619 }
15620 
15621 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15622   // Determine whether we're in the #include buffer for a module. The #includes
15623   // in that buffer do not qualify as module imports; they're just an
15624   // implementation detail of us building the module.
15625   //
15626   // FIXME: Should we even get ActOnModuleInclude calls for those?
15627   bool IsInModuleIncludes =
15628       TUKind == TU_Module &&
15629       getSourceManager().isWrittenInMainFile(DirectiveLoc);
15630 
15631   bool ShouldAddImport = !IsInModuleIncludes;
15632 
15633   // If this module import was due to an inclusion directive, create an
15634   // implicit import declaration to capture it in the AST.
15635   if (ShouldAddImport) {
15636     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15637     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15638                                                      DirectiveLoc, Mod,
15639                                                      DirectiveLoc);
15640     if (!ModuleScopes.empty())
15641       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
15642     TU->addDecl(ImportD);
15643     Consumer.HandleImplicitImportDecl(ImportD);
15644   }
15645 
15646   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
15647   VisibleModules.setVisible(Mod, DirectiveLoc);
15648 }
15649 
15650 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
15651   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15652 
15653   ModuleScopes.push_back({});
15654   ModuleScopes.back().Module = Mod;
15655   if (getLangOpts().ModulesLocalVisibility)
15656     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
15657 
15658   VisibleModules.setVisible(Mod, DirectiveLoc);
15659 }
15660 
15661 void Sema::ActOnModuleEnd(SourceLocation EofLoc, Module *Mod) {
15662   if (getLangOpts().ModulesLocalVisibility) {
15663     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
15664     // Leaving a module hides namespace names, so our visible namespace cache
15665     // is now out of date.
15666     VisibleNamespaceCache.clear();
15667   }
15668 
15669   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
15670          "left the wrong module scope");
15671   ModuleScopes.pop_back();
15672 
15673   // We got to the end of processing a #include of a local module. Create an
15674   // ImportDecl as we would for an imported module.
15675   FileID File = getSourceManager().getFileID(EofLoc);
15676   assert(File != getSourceManager().getMainFileID() &&
15677          "end of submodule in main source file");
15678   SourceLocation DirectiveLoc = getSourceManager().getIncludeLoc(File);
15679   BuildModuleInclude(DirectiveLoc, Mod);
15680 }
15681 
15682 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
15683                                                       Module *Mod) {
15684   // Bail if we're not allowed to implicitly import a module here.
15685   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
15686     return;
15687 
15688   // Create the implicit import declaration.
15689   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15690   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15691                                                    Loc, Mod, Loc);
15692   TU->addDecl(ImportD);
15693   Consumer.HandleImplicitImportDecl(ImportD);
15694 
15695   // Make the module visible.
15696   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
15697   VisibleModules.setVisible(Mod, Loc);
15698 }
15699 
15700 /// We have parsed the start of an export declaration, including the '{'
15701 /// (if present).
15702 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
15703                                  SourceLocation LBraceLoc) {
15704   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
15705 
15706   // C++ Modules TS draft:
15707   //   An export-declaration [...] shall not contain more than one
15708   //   export keyword.
15709   //
15710   // The intent here is that an export-declaration cannot appear within another
15711   // export-declaration.
15712   if (D->isExported())
15713     Diag(ExportLoc, diag::err_export_within_export);
15714 
15715   CurContext->addDecl(D);
15716   PushDeclContext(S, D);
15717   return D;
15718 }
15719 
15720 /// Complete the definition of an export declaration.
15721 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
15722   auto *ED = cast<ExportDecl>(D);
15723   if (RBraceLoc.isValid())
15724     ED->setRBraceLoc(RBraceLoc);
15725 
15726   // FIXME: Diagnose export of internal-linkage declaration (including
15727   // anonymous namespace).
15728 
15729   PopDeclContext();
15730   return D;
15731 }
15732 
15733 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
15734                                       IdentifierInfo* AliasName,
15735                                       SourceLocation PragmaLoc,
15736                                       SourceLocation NameLoc,
15737                                       SourceLocation AliasNameLoc) {
15738   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
15739                                          LookupOrdinaryName);
15740   AsmLabelAttr *Attr =
15741       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
15742 
15743   // If a declaration that:
15744   // 1) declares a function or a variable
15745   // 2) has external linkage
15746   // already exists, add a label attribute to it.
15747   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15748     if (isDeclExternC(PrevDecl))
15749       PrevDecl->addAttr(Attr);
15750     else
15751       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
15752           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
15753   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
15754   } else
15755     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
15756 }
15757 
15758 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
15759                              SourceLocation PragmaLoc,
15760                              SourceLocation NameLoc) {
15761   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
15762 
15763   if (PrevDecl) {
15764     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
15765   } else {
15766     (void)WeakUndeclaredIdentifiers.insert(
15767       std::pair<IdentifierInfo*,WeakInfo>
15768         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
15769   }
15770 }
15771 
15772 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
15773                                 IdentifierInfo* AliasName,
15774                                 SourceLocation PragmaLoc,
15775                                 SourceLocation NameLoc,
15776                                 SourceLocation AliasNameLoc) {
15777   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
15778                                     LookupOrdinaryName);
15779   WeakInfo W = WeakInfo(Name, NameLoc);
15780 
15781   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15782     if (!PrevDecl->hasAttr<AliasAttr>())
15783       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
15784         DeclApplyPragmaWeak(TUScope, ND, W);
15785   } else {
15786     (void)WeakUndeclaredIdentifiers.insert(
15787       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
15788   }
15789 }
15790 
15791 Decl *Sema::getObjCDeclContext() const {
15792   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
15793 }
15794