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 "clang/Sema/SemaInternal.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTLambda.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/CharUnits.h"
21 #include "clang/AST/CommentDiagnostic.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/EvaluatedExprVisitor.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/PartialDiagnostic.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
36 #include "clang/Sema/CXXFieldCollector.h"
37 #include "clang/Sema/DeclSpec.h"
38 #include "clang/Sema/DelayedDiagnostic.h"
39 #include "clang/Sema/Initialization.h"
40 #include "clang/Sema/Lookup.h"
41 #include "clang/Sema/ParsedTemplate.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.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       auto *BasePrimaryTemplate =
167           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
168       if (!BasePrimaryTemplate)
169         continue;
170       BaseRD = BasePrimaryTemplate;
171     }
172     if (BaseRD) {
173       for (NamedDecl *ND : BaseRD->lookup(&II)) {
174         if (!isa<TypeDecl>(ND))
175           return UnqualifiedTypeNameLookupResult::FoundNonType;
176         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
177       }
178       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
179         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
180         case UnqualifiedTypeNameLookupResult::FoundNonType:
181           return UnqualifiedTypeNameLookupResult::FoundNonType;
182         case UnqualifiedTypeNameLookupResult::FoundType:
183           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
184           break;
185         case UnqualifiedTypeNameLookupResult::NotFound:
186           break;
187         }
188       }
189     }
190   }
191 
192   return FoundTypeDecl;
193 }
194 
195 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
196                                                       const IdentifierInfo &II,
197                                                       SourceLocation NameLoc) {
198   // Lookup in the parent class template context, if any.
199   const CXXRecordDecl *RD = nullptr;
200   UnqualifiedTypeNameLookupResult FoundTypeDecl =
201       UnqualifiedTypeNameLookupResult::NotFound;
202   for (DeclContext *DC = S.CurContext;
203        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
204        DC = DC->getParent()) {
205     // Look for type decls in dependent base classes that have known primary
206     // templates.
207     RD = dyn_cast<CXXRecordDecl>(DC);
208     if (RD && RD->getDescribedClassTemplate())
209       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
210   }
211   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
212     return nullptr;
213 
214   // We found some types in dependent base classes.  Recover as if the user
215   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
216   // lookup during template instantiation.
217   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
218 
219   ASTContext &Context = S.Context;
220   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
221                                           cast<Type>(Context.getRecordType(RD)));
222   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
223 
224   CXXScopeSpec SS;
225   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
226 
227   TypeLocBuilder Builder;
228   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
229   DepTL.setNameLoc(NameLoc);
230   DepTL.setElaboratedKeywordLoc(SourceLocation());
231   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
232   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
233 }
234 
235 /// \brief If the identifier refers to a type name within this scope,
236 /// return the declaration of that type.
237 ///
238 /// This routine performs ordinary name lookup of the identifier II
239 /// within the given scope, with optional C++ scope specifier SS, to
240 /// determine whether the name refers to a type. If so, returns an
241 /// opaque pointer (actually a QualType) corresponding to that
242 /// type. Otherwise, returns NULL.
243 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
244                              Scope *S, CXXScopeSpec *SS,
245                              bool isClassName, bool HasTrailingDot,
246                              ParsedType ObjectTypePtr,
247                              bool IsCtorOrDtorName,
248                              bool WantNontrivialTypeSourceInfo,
249                              IdentifierInfo **CorrectedII) {
250   // Determine where we will perform name lookup.
251   DeclContext *LookupCtx = nullptr;
252   if (ObjectTypePtr) {
253     QualType ObjectType = ObjectTypePtr.get();
254     if (ObjectType->isRecordType())
255       LookupCtx = computeDeclContext(ObjectType);
256   } else if (SS && SS->isNotEmpty()) {
257     LookupCtx = computeDeclContext(*SS, false);
258 
259     if (!LookupCtx) {
260       if (isDependentScopeSpecifier(*SS)) {
261         // C++ [temp.res]p3:
262         //   A qualified-id that refers to a type and in which the
263         //   nested-name-specifier depends on a template-parameter (14.6.2)
264         //   shall be prefixed by the keyword typename to indicate that the
265         //   qualified-id denotes a type, forming an
266         //   elaborated-type-specifier (7.1.5.3).
267         //
268         // We therefore do not perform any name lookup if the result would
269         // refer to a member of an unknown specialization.
270         if (!isClassName && !IsCtorOrDtorName)
271           return nullptr;
272 
273         // We know from the grammar that this name refers to a type,
274         // so build a dependent node to describe the type.
275         if (WantNontrivialTypeSourceInfo)
276           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
277 
278         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
279         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
280                                        II, NameLoc);
281         return ParsedType::make(T);
282       }
283 
284       return nullptr;
285     }
286 
287     if (!LookupCtx->isDependentContext() &&
288         RequireCompleteDeclContext(*SS, LookupCtx))
289       return nullptr;
290   }
291 
292   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
293   // lookup for class-names.
294   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
295                                       LookupOrdinaryName;
296   LookupResult Result(*this, &II, NameLoc, Kind);
297   if (LookupCtx) {
298     // Perform "qualified" name lookup into the declaration context we
299     // computed, which is either the type of the base of a member access
300     // expression or the declaration context associated with a prior
301     // nested-name-specifier.
302     LookupQualifiedName(Result, LookupCtx);
303 
304     if (ObjectTypePtr && Result.empty()) {
305       // C++ [basic.lookup.classref]p3:
306       //   If the unqualified-id is ~type-name, the type-name is looked up
307       //   in the context of the entire postfix-expression. If the type T of
308       //   the object expression is of a class type C, the type-name is also
309       //   looked up in the scope of class C. At least one of the lookups shall
310       //   find a name that refers to (possibly cv-qualified) T.
311       LookupName(Result, S);
312     }
313   } else {
314     // Perform unqualified name lookup.
315     LookupName(Result, S);
316 
317     // For unqualified lookup in a class template in MSVC mode, look into
318     // dependent base classes where the primary class template is known.
319     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
320       if (ParsedType TypeInBase =
321               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
322         return TypeInBase;
323     }
324   }
325 
326   NamedDecl *IIDecl = nullptr;
327   switch (Result.getResultKind()) {
328   case LookupResult::NotFound:
329   case LookupResult::NotFoundInCurrentInstantiation:
330     if (CorrectedII) {
331       TypoCorrection Correction = CorrectTypo(
332           Result.getLookupNameInfo(), Kind, S, SS,
333           llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
334           CTK_ErrorRecovery);
335       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
336       TemplateTy Template;
337       bool MemberOfUnknownSpecialization;
338       UnqualifiedId TemplateName;
339       TemplateName.setIdentifier(NewII, NameLoc);
340       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
341       CXXScopeSpec NewSS, *NewSSPtr = SS;
342       if (SS && NNS) {
343         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
344         NewSSPtr = &NewSS;
345       }
346       if (Correction && (NNS || NewII != &II) &&
347           // Ignore a correction to a template type as the to-be-corrected
348           // identifier is not a template (typo correction for template names
349           // is handled elsewhere).
350           !(getLangOpts().CPlusPlus && NewSSPtr &&
351             isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
352                            Template, MemberOfUnknownSpecialization))) {
353         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
354                                     isClassName, HasTrailingDot, ObjectTypePtr,
355                                     IsCtorOrDtorName,
356                                     WantNontrivialTypeSourceInfo);
357         if (Ty) {
358           diagnoseTypo(Correction,
359                        PDiag(diag::err_unknown_type_or_class_name_suggest)
360                          << Result.getLookupName() << isClassName);
361           if (SS && NNS)
362             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
363           *CorrectedII = NewII;
364           return Ty;
365         }
366       }
367     }
368     // If typo correction failed or was not performed, fall through
369   case LookupResult::FoundOverloaded:
370   case LookupResult::FoundUnresolvedValue:
371     Result.suppressDiagnostics();
372     return nullptr;
373 
374   case LookupResult::Ambiguous:
375     // Recover from type-hiding ambiguities by hiding the type.  We'll
376     // do the lookup again when looking for an object, and we can
377     // diagnose the error then.  If we don't do this, then the error
378     // about hiding the type will be immediately followed by an error
379     // that only makes sense if the identifier was treated like a type.
380     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
381       Result.suppressDiagnostics();
382       return nullptr;
383     }
384 
385     // Look to see if we have a type anywhere in the list of results.
386     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
387          Res != ResEnd; ++Res) {
388       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
389         if (!IIDecl ||
390             (*Res)->getLocation().getRawEncoding() <
391               IIDecl->getLocation().getRawEncoding())
392           IIDecl = *Res;
393       }
394     }
395 
396     if (!IIDecl) {
397       // None of the entities we found is a type, so there is no way
398       // to even assume that the result is a type. In this case, don't
399       // complain about the ambiguity. The parser will either try to
400       // perform this lookup again (e.g., as an object name), which
401       // will produce the ambiguity, or will complain that it expected
402       // a type name.
403       Result.suppressDiagnostics();
404       return nullptr;
405     }
406 
407     // We found a type within the ambiguous lookup; diagnose the
408     // ambiguity and then return that type. This might be the right
409     // answer, or it might not be, but it suppresses any attempt to
410     // perform the name lookup again.
411     break;
412 
413   case LookupResult::Found:
414     IIDecl = Result.getFoundDecl();
415     break;
416   }
417 
418   assert(IIDecl && "Didn't find decl");
419 
420   QualType T;
421   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
422     DiagnoseUseOfDecl(IIDecl, NameLoc);
423 
424     T = Context.getTypeDeclType(TD);
425     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
426 
427     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
428     // constructor or destructor name (in such a case, the scope specifier
429     // will be attached to the enclosing Expr or Decl node).
430     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
431       if (WantNontrivialTypeSourceInfo) {
432         // Construct a type with type-source information.
433         TypeLocBuilder Builder;
434         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
435 
436         T = getElaboratedType(ETK_None, *SS, T);
437         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
438         ElabTL.setElaboratedKeywordLoc(SourceLocation());
439         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
440         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
441       } else {
442         T = getElaboratedType(ETK_None, *SS, T);
443       }
444     }
445   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
446     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
447     if (!HasTrailingDot)
448       T = Context.getObjCInterfaceType(IDecl);
449   }
450 
451   if (T.isNull()) {
452     // If it's not plausibly a type, suppress diagnostics.
453     Result.suppressDiagnostics();
454     return nullptr;
455   }
456   return ParsedType::make(T);
457 }
458 
459 // Builds a fake NNS for the given decl context.
460 static NestedNameSpecifier *
461 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
462   for (;; DC = DC->getLookupParent()) {
463     DC = DC->getPrimaryContext();
464     auto *ND = dyn_cast<NamespaceDecl>(DC);
465     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
466       return NestedNameSpecifier::Create(Context, nullptr, ND);
467     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
468       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
469                                          RD->getTypeForDecl());
470     else if (isa<TranslationUnitDecl>(DC))
471       return NestedNameSpecifier::GlobalSpecifier(Context);
472   }
473   llvm_unreachable("something isn't in TU scope?");
474 }
475 
476 /// Find the parent class with dependent bases of the innermost enclosing method
477 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
478 /// up allowing unqualified dependent type names at class-level, which MSVC
479 /// correctly rejects.
480 static const CXXRecordDecl *
481 findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC) {
482   for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
483     DC = DC->getPrimaryContext();
484     if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
485       if (MD->getParent()->hasAnyDependentBases())
486         return MD->getParent();
487   }
488   return nullptr;
489 }
490 
491 ParsedType Sema::ActOnMSVCUnknownTypeName(const IdentifierInfo &II,
492                                           SourceLocation NameLoc,
493                                           bool IsTemplateTypeArg) {
494   assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
495 
496   NestedNameSpecifier *NNS = nullptr;
497   if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
498     // If we weren't able to parse a default template argument, delay lookup
499     // until instantiation time by making a non-dependent DependentTypeName. We
500     // pretend we saw a NestedNameSpecifier referring to the current scope, and
501     // lookup is retried.
502     // FIXME: This hurts our diagnostic quality, since we get errors like "no
503     // type named 'Foo' in 'current_namespace'" when the user didn't write any
504     // name specifiers.
505     NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
506     Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
507   } else if (const CXXRecordDecl *RD =
508                  findRecordWithDependentBasesOfEnclosingMethod(CurContext)) {
509     // Build a DependentNameType that will perform lookup into RD at
510     // instantiation time.
511     NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
512                                       RD->getTypeForDecl());
513 
514     // Diagnose that this identifier was undeclared, and retry the lookup during
515     // template instantiation.
516     Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
517                                                                       << RD;
518   } else {
519     // This is not a situation that we should recover from.
520     return ParsedType();
521   }
522 
523   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
524 
525   // Build type location information.  We synthesized the qualifier, so we have
526   // to build a fake NestedNameSpecifierLoc.
527   NestedNameSpecifierLocBuilder NNSLocBuilder;
528   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
529   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
530 
531   TypeLocBuilder Builder;
532   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
533   DepTL.setNameLoc(NameLoc);
534   DepTL.setElaboratedKeywordLoc(SourceLocation());
535   DepTL.setQualifierLoc(QualifierLoc);
536   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
537 }
538 
539 /// isTagName() - This method is called *for error recovery purposes only*
540 /// to determine if the specified name is a valid tag name ("struct foo").  If
541 /// so, this returns the TST for the tag corresponding to it (TST_enum,
542 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
543 /// cases in C where the user forgot to specify the tag.
544 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
545   // Do a tag name lookup in this scope.
546   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
547   LookupName(R, S, false);
548   R.suppressDiagnostics();
549   if (R.getResultKind() == LookupResult::Found)
550     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
551       switch (TD->getTagKind()) {
552       case TTK_Struct: return DeclSpec::TST_struct;
553       case TTK_Interface: return DeclSpec::TST_interface;
554       case TTK_Union:  return DeclSpec::TST_union;
555       case TTK_Class:  return DeclSpec::TST_class;
556       case TTK_Enum:   return DeclSpec::TST_enum;
557       }
558     }
559 
560   return DeclSpec::TST_unspecified;
561 }
562 
563 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
564 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
565 /// then downgrade the missing typename error to a warning.
566 /// This is needed for MSVC compatibility; Example:
567 /// @code
568 /// template<class T> class A {
569 /// public:
570 ///   typedef int TYPE;
571 /// };
572 /// template<class T> class B : public A<T> {
573 /// public:
574 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
575 /// };
576 /// @endcode
577 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
578   if (CurContext->isRecord()) {
579     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
580       return true;
581 
582     const Type *Ty = SS->getScopeRep()->getAsType();
583 
584     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
585     for (const auto &Base : RD->bases())
586       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
587         return true;
588     return S->isFunctionPrototypeScope();
589   }
590   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
591 }
592 
593 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
594                                    SourceLocation IILoc,
595                                    Scope *S,
596                                    CXXScopeSpec *SS,
597                                    ParsedType &SuggestedType,
598                                    bool AllowClassTemplates) {
599   // We don't have anything to suggest (yet).
600   SuggestedType = nullptr;
601 
602   // There may have been a typo in the name of the type. Look up typo
603   // results, in case we have something that we can suggest.
604   if (TypoCorrection Corrected =
605           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
606                       llvm::make_unique<TypeNameValidatorCCC>(
607                           false, false, AllowClassTemplates),
608                       CTK_ErrorRecovery)) {
609     if (Corrected.isKeyword()) {
610       // We corrected to a keyword.
611       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
612       II = Corrected.getCorrectionAsIdentifierInfo();
613     } else {
614       // We found a similarly-named type or interface; suggest that.
615       if (!SS || !SS->isSet()) {
616         diagnoseTypo(Corrected,
617                      PDiag(diag::err_unknown_typename_suggest) << II);
618       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
619         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
620         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
621                                 II->getName().equals(CorrectedStr);
622         diagnoseTypo(Corrected,
623                      PDiag(diag::err_unknown_nested_typename_suggest)
624                        << II << DC << DroppedSpecifier << SS->getRange());
625       } else {
626         llvm_unreachable("could not have corrected a typo here");
627       }
628 
629       CXXScopeSpec tmpSS;
630       if (Corrected.getCorrectionSpecifier())
631         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
632                           SourceRange(IILoc));
633       SuggestedType =
634           getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
635                       tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
636                       /*IsCtorOrDtorName=*/false,
637                       /*NonTrivialTypeSourceInfo=*/true);
638     }
639     return;
640   }
641 
642   if (getLangOpts().CPlusPlus) {
643     // See if II is a class template that the user forgot to pass arguments to.
644     UnqualifiedId Name;
645     Name.setIdentifier(II, IILoc);
646     CXXScopeSpec EmptySS;
647     TemplateTy TemplateResult;
648     bool MemberOfUnknownSpecialization;
649     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
650                        Name, nullptr, true, TemplateResult,
651                        MemberOfUnknownSpecialization) == TNK_Type_template) {
652       TemplateName TplName = TemplateResult.get();
653       Diag(IILoc, diag::err_template_missing_args) << TplName;
654       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
655         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
656           << TplDecl->getTemplateParameters()->getSourceRange();
657       }
658       return;
659     }
660   }
661 
662   // FIXME: Should we move the logic that tries to recover from a missing tag
663   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
664 
665   if (!SS || (!SS->isSet() && !SS->isInvalid()))
666     Diag(IILoc, diag::err_unknown_typename) << II;
667   else if (DeclContext *DC = computeDeclContext(*SS, false))
668     Diag(IILoc, diag::err_typename_nested_not_found)
669       << II << DC << SS->getRange();
670   else if (isDependentScopeSpecifier(*SS)) {
671     unsigned DiagID = diag::err_typename_missing;
672     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
673       DiagID = diag::ext_typename_missing;
674 
675     Diag(SS->getRange().getBegin(), DiagID)
676       << SS->getScopeRep() << II->getName()
677       << SourceRange(SS->getRange().getBegin(), IILoc)
678       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
679     SuggestedType = ActOnTypenameType(S, SourceLocation(),
680                                       *SS, *II, IILoc).get();
681   } else {
682     assert(SS && SS->isInvalid() &&
683            "Invalid scope specifier has already been diagnosed");
684   }
685 }
686 
687 /// \brief Determine whether the given result set contains either a type name
688 /// or
689 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
690   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
691                        NextToken.is(tok::less);
692 
693   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
694     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
695       return true;
696 
697     if (CheckTemplate && isa<TemplateDecl>(*I))
698       return true;
699   }
700 
701   return false;
702 }
703 
704 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
705                                     Scope *S, CXXScopeSpec &SS,
706                                     IdentifierInfo *&Name,
707                                     SourceLocation NameLoc) {
708   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
709   SemaRef.LookupParsedName(R, S, &SS);
710   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
711     StringRef FixItTagName;
712     switch (Tag->getTagKind()) {
713       case TTK_Class:
714         FixItTagName = "class ";
715         break;
716 
717       case TTK_Enum:
718         FixItTagName = "enum ";
719         break;
720 
721       case TTK_Struct:
722         FixItTagName = "struct ";
723         break;
724 
725       case TTK_Interface:
726         FixItTagName = "__interface ";
727         break;
728 
729       case TTK_Union:
730         FixItTagName = "union ";
731         break;
732     }
733 
734     StringRef TagName = FixItTagName.drop_back();
735     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
736       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
737       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
738 
739     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
740          I != IEnd; ++I)
741       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
742         << Name << TagName;
743 
744     // Replace lookup results with just the tag decl.
745     Result.clear(Sema::LookupTagName);
746     SemaRef.LookupParsedName(Result, S, &SS);
747     return true;
748   }
749 
750   return false;
751 }
752 
753 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
754 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
755                                   QualType T, SourceLocation NameLoc) {
756   ASTContext &Context = S.Context;
757 
758   TypeLocBuilder Builder;
759   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
760 
761   T = S.getElaboratedType(ETK_None, SS, T);
762   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
763   ElabTL.setElaboratedKeywordLoc(SourceLocation());
764   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
765   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
766 }
767 
768 Sema::NameClassification
769 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
770                    SourceLocation NameLoc, const Token &NextToken,
771                    bool IsAddressOfOperand,
772                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
773   DeclarationNameInfo NameInfo(Name, NameLoc);
774   ObjCMethodDecl *CurMethod = getCurMethodDecl();
775 
776   if (NextToken.is(tok::coloncolon)) {
777     BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
778                                 QualType(), false, SS, nullptr, false);
779   }
780 
781   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
782   LookupParsedName(Result, S, &SS, !CurMethod);
783 
784   // For unqualified lookup in a class template in MSVC mode, look into
785   // dependent base classes where the primary class template is known.
786   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
787     if (ParsedType TypeInBase =
788             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
789       return TypeInBase;
790   }
791 
792   // Perform lookup for Objective-C instance variables (including automatically
793   // synthesized instance variables), if we're in an Objective-C method.
794   // FIXME: This lookup really, really needs to be folded in to the normal
795   // unqualified lookup mechanism.
796   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
797     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
798     if (E.get() || E.isInvalid())
799       return E;
800   }
801 
802   bool SecondTry = false;
803   bool IsFilteredTemplateName = false;
804 
805 Corrected:
806   switch (Result.getResultKind()) {
807   case LookupResult::NotFound:
808     // If an unqualified-id is followed by a '(', then we have a function
809     // call.
810     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
811       // In C++, this is an ADL-only call.
812       // FIXME: Reference?
813       if (getLangOpts().CPlusPlus)
814         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
815 
816       // C90 6.3.2.2:
817       //   If the expression that precedes the parenthesized argument list in a
818       //   function call consists solely of an identifier, and if no
819       //   declaration is visible for this identifier, the identifier is
820       //   implicitly declared exactly as if, in the innermost block containing
821       //   the function call, the declaration
822       //
823       //     extern int identifier ();
824       //
825       //   appeared.
826       //
827       // We also allow this in C99 as an extension.
828       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
829         Result.addDecl(D);
830         Result.resolveKind();
831         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
832       }
833     }
834 
835     // In C, we first see whether there is a tag type by the same name, in
836     // which case it's likely that the user just forgot to write "enum",
837     // "struct", or "union".
838     if (!getLangOpts().CPlusPlus && !SecondTry &&
839         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
840       break;
841     }
842 
843     // Perform typo correction to determine if there is another name that is
844     // close to this name.
845     if (!SecondTry && CCC) {
846       SecondTry = true;
847       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
848                                                  Result.getLookupKind(), S,
849                                                  &SS, std::move(CCC),
850                                                  CTK_ErrorRecovery)) {
851         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
852         unsigned QualifiedDiag = diag::err_no_member_suggest;
853 
854         NamedDecl *FirstDecl = Corrected.getFoundDecl();
855         NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
856         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
857             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
858           UnqualifiedDiag = diag::err_no_template_suggest;
859           QualifiedDiag = diag::err_no_member_template_suggest;
860         } else if (UnderlyingFirstDecl &&
861                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
862                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
863                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
864           UnqualifiedDiag = diag::err_unknown_typename_suggest;
865           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
866         }
867 
868         if (SS.isEmpty()) {
869           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
870         } else {// FIXME: is this even reachable? Test it.
871           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
872           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
873                                   Name->getName().equals(CorrectedStr);
874           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
875                                     << Name << computeDeclContext(SS, false)
876                                     << DroppedSpecifier << SS.getRange());
877         }
878 
879         // Update the name, so that the caller has the new name.
880         Name = Corrected.getCorrectionAsIdentifierInfo();
881 
882         // Typo correction corrected to a keyword.
883         if (Corrected.isKeyword())
884           return Name;
885 
886         // Also update the LookupResult...
887         // FIXME: This should probably go away at some point
888         Result.clear();
889         Result.setLookupName(Corrected.getCorrection());
890         if (FirstDecl)
891           Result.addDecl(FirstDecl);
892 
893         // If we found an Objective-C instance variable, let
894         // LookupInObjCMethod build the appropriate expression to
895         // reference the ivar.
896         // FIXME: This is a gross hack.
897         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
898           Result.clear();
899           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
900           return E;
901         }
902 
903         goto Corrected;
904       }
905     }
906 
907     // We failed to correct; just fall through and let the parser deal with it.
908     Result.suppressDiagnostics();
909     return NameClassification::Unknown();
910 
911   case LookupResult::NotFoundInCurrentInstantiation: {
912     // We performed name lookup into the current instantiation, and there were
913     // dependent bases, so we treat this result the same way as any other
914     // dependent nested-name-specifier.
915 
916     // C++ [temp.res]p2:
917     //   A name used in a template declaration or definition and that is
918     //   dependent on a template-parameter is assumed not to name a type
919     //   unless the applicable name lookup finds a type name or the name is
920     //   qualified by the keyword typename.
921     //
922     // FIXME: If the next token is '<', we might want to ask the parser to
923     // perform some heroics to see if we actually have a
924     // template-argument-list, which would indicate a missing 'template'
925     // keyword here.
926     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
927                                       NameInfo, IsAddressOfOperand,
928                                       /*TemplateArgs=*/nullptr);
929   }
930 
931   case LookupResult::Found:
932   case LookupResult::FoundOverloaded:
933   case LookupResult::FoundUnresolvedValue:
934     break;
935 
936   case LookupResult::Ambiguous:
937     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
938         hasAnyAcceptableTemplateNames(Result)) {
939       // C++ [temp.local]p3:
940       //   A lookup that finds an injected-class-name (10.2) can result in an
941       //   ambiguity in certain cases (for example, if it is found in more than
942       //   one base class). If all of the injected-class-names that are found
943       //   refer to specializations of the same class template, and if the name
944       //   is followed by a template-argument-list, the reference refers to the
945       //   class template itself and not a specialization thereof, and is not
946       //   ambiguous.
947       //
948       // This filtering can make an ambiguous result into an unambiguous one,
949       // so try again after filtering out template names.
950       FilterAcceptableTemplateNames(Result);
951       if (!Result.isAmbiguous()) {
952         IsFilteredTemplateName = true;
953         break;
954       }
955     }
956 
957     // Diagnose the ambiguity and return an error.
958     return NameClassification::Error();
959   }
960 
961   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
962       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
963     // C++ [temp.names]p3:
964     //   After name lookup (3.4) finds that a name is a template-name or that
965     //   an operator-function-id or a literal- operator-id refers to a set of
966     //   overloaded functions any member of which is a function template if
967     //   this is followed by a <, the < is always taken as the delimiter of a
968     //   template-argument-list and never as the less-than operator.
969     if (!IsFilteredTemplateName)
970       FilterAcceptableTemplateNames(Result);
971 
972     if (!Result.empty()) {
973       bool IsFunctionTemplate;
974       bool IsVarTemplate;
975       TemplateName Template;
976       if (Result.end() - Result.begin() > 1) {
977         IsFunctionTemplate = true;
978         Template = Context.getOverloadedTemplateName(Result.begin(),
979                                                      Result.end());
980       } else {
981         TemplateDecl *TD
982           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
983         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
984         IsVarTemplate = isa<VarTemplateDecl>(TD);
985 
986         if (SS.isSet() && !SS.isInvalid())
987           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
988                                                     /*TemplateKeyword=*/false,
989                                                       TD);
990         else
991           Template = TemplateName(TD);
992       }
993 
994       if (IsFunctionTemplate) {
995         // Function templates always go through overload resolution, at which
996         // point we'll perform the various checks (e.g., accessibility) we need
997         // to based on which function we selected.
998         Result.suppressDiagnostics();
999 
1000         return NameClassification::FunctionTemplate(Template);
1001       }
1002 
1003       return IsVarTemplate ? NameClassification::VarTemplate(Template)
1004                            : NameClassification::TypeTemplate(Template);
1005     }
1006   }
1007 
1008   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1009   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1010     DiagnoseUseOfDecl(Type, NameLoc);
1011     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1012     QualType T = Context.getTypeDeclType(Type);
1013     if (SS.isNotEmpty())
1014       return buildNestedType(*this, SS, T, NameLoc);
1015     return ParsedType::make(T);
1016   }
1017 
1018   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1019   if (!Class) {
1020     // FIXME: It's unfortunate that we don't have a Type node for handling this.
1021     if (ObjCCompatibleAliasDecl *Alias =
1022             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1023       Class = Alias->getClassInterface();
1024   }
1025 
1026   if (Class) {
1027     DiagnoseUseOfDecl(Class, NameLoc);
1028 
1029     if (NextToken.is(tok::period)) {
1030       // Interface. <something> is parsed as a property reference expression.
1031       // Just return "unknown" as a fall-through for now.
1032       Result.suppressDiagnostics();
1033       return NameClassification::Unknown();
1034     }
1035 
1036     QualType T = Context.getObjCInterfaceType(Class);
1037     return ParsedType::make(T);
1038   }
1039 
1040   // We can have a type template here if we're classifying a template argument.
1041   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
1042     return NameClassification::TypeTemplate(
1043         TemplateName(cast<TemplateDecl>(FirstDecl)));
1044 
1045   // Check for a tag type hidden by a non-type decl in a few cases where it
1046   // seems likely a type is wanted instead of the non-type that was found.
1047   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1048   if ((NextToken.is(tok::identifier) ||
1049        (NextIsOp &&
1050         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1051       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1052     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1053     DiagnoseUseOfDecl(Type, NameLoc);
1054     QualType T = Context.getTypeDeclType(Type);
1055     if (SS.isNotEmpty())
1056       return buildNestedType(*this, SS, T, NameLoc);
1057     return ParsedType::make(T);
1058   }
1059 
1060   if (FirstDecl->isCXXClassMember())
1061     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1062                                            nullptr, S);
1063 
1064   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1065   return BuildDeclarationNameExpr(SS, Result, ADL);
1066 }
1067 
1068 // Determines the context to return to after temporarily entering a
1069 // context.  This depends in an unnecessarily complicated way on the
1070 // exact ordering of callbacks from the parser.
1071 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1072 
1073   // Functions defined inline within classes aren't parsed until we've
1074   // finished parsing the top-level class, so the top-level class is
1075   // the context we'll need to return to.
1076   // A Lambda call operator whose parent is a class must not be treated
1077   // as an inline member function.  A Lambda can be used legally
1078   // either as an in-class member initializer or a default argument.  These
1079   // are parsed once the class has been marked complete and so the containing
1080   // context would be the nested class (when the lambda is defined in one);
1081   // If the class is not complete, then the lambda is being used in an
1082   // ill-formed fashion (such as to specify the width of a bit-field, or
1083   // in an array-bound) - in which case we still want to return the
1084   // lexically containing DC (which could be a nested class).
1085   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1086     DC = DC->getLexicalParent();
1087 
1088     // A function not defined within a class will always return to its
1089     // lexical context.
1090     if (!isa<CXXRecordDecl>(DC))
1091       return DC;
1092 
1093     // A C++ inline method/friend is parsed *after* the topmost class
1094     // it was declared in is fully parsed ("complete");  the topmost
1095     // class is the context we need to return to.
1096     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1097       DC = RD;
1098 
1099     // Return the declaration context of the topmost class the inline method is
1100     // declared in.
1101     return DC;
1102   }
1103 
1104   return DC->getLexicalParent();
1105 }
1106 
1107 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1108   assert(getContainingDC(DC) == CurContext &&
1109       "The next DeclContext should be lexically contained in the current one.");
1110   CurContext = DC;
1111   S->setEntity(DC);
1112 }
1113 
1114 void Sema::PopDeclContext() {
1115   assert(CurContext && "DeclContext imbalance!");
1116 
1117   CurContext = getContainingDC(CurContext);
1118   assert(CurContext && "Popped translation unit!");
1119 }
1120 
1121 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1122                                                                     Decl *D) {
1123   // Unlike PushDeclContext, the context to which we return is not necessarily
1124   // the containing DC of TD, because the new context will be some pre-existing
1125   // TagDecl definition instead of a fresh one.
1126   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1127   CurContext = cast<TagDecl>(D)->getDefinition();
1128   assert(CurContext && "skipping definition of undefined tag");
1129   // Start lookups from the parent of the current context; we don't want to look
1130   // into the pre-existing complete definition.
1131   S->setEntity(CurContext->getLookupParent());
1132   return Result;
1133 }
1134 
1135 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1136   CurContext = static_cast<decltype(CurContext)>(Context);
1137 }
1138 
1139 /// EnterDeclaratorContext - Used when we must lookup names in the context
1140 /// of a declarator's nested name specifier.
1141 ///
1142 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1143   // C++0x [basic.lookup.unqual]p13:
1144   //   A name used in the definition of a static data member of class
1145   //   X (after the qualified-id of the static member) is looked up as
1146   //   if the name was used in a member function of X.
1147   // C++0x [basic.lookup.unqual]p14:
1148   //   If a variable member of a namespace is defined outside of the
1149   //   scope of its namespace then any name used in the definition of
1150   //   the variable member (after the declarator-id) is looked up as
1151   //   if the definition of the variable member occurred in its
1152   //   namespace.
1153   // Both of these imply that we should push a scope whose context
1154   // is the semantic context of the declaration.  We can't use
1155   // PushDeclContext here because that context is not necessarily
1156   // lexically contained in the current context.  Fortunately,
1157   // the containing scope should have the appropriate information.
1158 
1159   assert(!S->getEntity() && "scope already has entity");
1160 
1161 #ifndef NDEBUG
1162   Scope *Ancestor = S->getParent();
1163   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1164   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1165 #endif
1166 
1167   CurContext = DC;
1168   S->setEntity(DC);
1169 }
1170 
1171 void Sema::ExitDeclaratorContext(Scope *S) {
1172   assert(S->getEntity() == CurContext && "Context imbalance!");
1173 
1174   // Switch back to the lexical context.  The safety of this is
1175   // enforced by an assert in EnterDeclaratorContext.
1176   Scope *Ancestor = S->getParent();
1177   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1178   CurContext = Ancestor->getEntity();
1179 
1180   // We don't need to do anything with the scope, which is going to
1181   // disappear.
1182 }
1183 
1184 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1185   // We assume that the caller has already called
1186   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1187   FunctionDecl *FD = D->getAsFunction();
1188   if (!FD)
1189     return;
1190 
1191   // Same implementation as PushDeclContext, but enters the context
1192   // from the lexical parent, rather than the top-level class.
1193   assert(CurContext == FD->getLexicalParent() &&
1194     "The next DeclContext should be lexically contained in the current one.");
1195   CurContext = FD;
1196   S->setEntity(CurContext);
1197 
1198   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1199     ParmVarDecl *Param = FD->getParamDecl(P);
1200     // If the parameter has an identifier, then add it to the scope
1201     if (Param->getIdentifier()) {
1202       S->AddDecl(Param);
1203       IdResolver.AddDecl(Param);
1204     }
1205   }
1206 }
1207 
1208 void Sema::ActOnExitFunctionContext() {
1209   // Same implementation as PopDeclContext, but returns to the lexical parent,
1210   // rather than the top-level class.
1211   assert(CurContext && "DeclContext imbalance!");
1212   CurContext = CurContext->getLexicalParent();
1213   assert(CurContext && "Popped translation unit!");
1214 }
1215 
1216 /// \brief Determine whether we allow overloading of the function
1217 /// PrevDecl with another declaration.
1218 ///
1219 /// This routine determines whether overloading is possible, not
1220 /// whether some new function is actually an overload. It will return
1221 /// true in C++ (where we can always provide overloads) or, as an
1222 /// extension, in C when the previous function is already an
1223 /// overloaded function declaration or has the "overloadable"
1224 /// attribute.
1225 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1226                                        ASTContext &Context) {
1227   if (Context.getLangOpts().CPlusPlus)
1228     return true;
1229 
1230   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1231     return true;
1232 
1233   return (Previous.getResultKind() == LookupResult::Found
1234           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1235 }
1236 
1237 /// Add this decl to the scope shadowed decl chains.
1238 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1239   // Move up the scope chain until we find the nearest enclosing
1240   // non-transparent context. The declaration will be introduced into this
1241   // scope.
1242   while (S->getEntity() && S->getEntity()->isTransparentContext())
1243     S = S->getParent();
1244 
1245   // Add scoped declarations into their context, so that they can be
1246   // found later. Declarations without a context won't be inserted
1247   // into any context.
1248   if (AddToContext)
1249     CurContext->addDecl(D);
1250 
1251   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1252   // are function-local declarations.
1253   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1254       !D->getDeclContext()->getRedeclContext()->Equals(
1255         D->getLexicalDeclContext()->getRedeclContext()) &&
1256       !D->getLexicalDeclContext()->isFunctionOrMethod())
1257     return;
1258 
1259   // Template instantiations should also not be pushed into scope.
1260   if (isa<FunctionDecl>(D) &&
1261       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1262     return;
1263 
1264   // If this replaces anything in the current scope,
1265   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1266                                IEnd = IdResolver.end();
1267   for (; I != IEnd; ++I) {
1268     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1269       S->RemoveDecl(*I);
1270       IdResolver.RemoveDecl(*I);
1271 
1272       // Should only need to replace one decl.
1273       break;
1274     }
1275   }
1276 
1277   S->AddDecl(D);
1278 
1279   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1280     // Implicitly-generated labels may end up getting generated in an order that
1281     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1282     // the label at the appropriate place in the identifier chain.
1283     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1284       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1285       if (IDC == CurContext) {
1286         if (!S->isDeclScope(*I))
1287           continue;
1288       } else if (IDC->Encloses(CurContext))
1289         break;
1290     }
1291 
1292     IdResolver.InsertDeclAfter(I, D);
1293   } else {
1294     IdResolver.AddDecl(D);
1295   }
1296 }
1297 
1298 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1299   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1300     TUScope->AddDecl(D);
1301 }
1302 
1303 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1304                          bool AllowInlineNamespace) {
1305   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1306 }
1307 
1308 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1309   DeclContext *TargetDC = DC->getPrimaryContext();
1310   do {
1311     if (DeclContext *ScopeDC = S->getEntity())
1312       if (ScopeDC->getPrimaryContext() == TargetDC)
1313         return S;
1314   } while ((S = S->getParent()));
1315 
1316   return nullptr;
1317 }
1318 
1319 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1320                                             DeclContext*,
1321                                             ASTContext&);
1322 
1323 /// Filters out lookup results that don't fall within the given scope
1324 /// as determined by isDeclInScope.
1325 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1326                                 bool ConsiderLinkage,
1327                                 bool AllowInlineNamespace) {
1328   LookupResult::Filter F = R.makeFilter();
1329   while (F.hasNext()) {
1330     NamedDecl *D = F.next();
1331 
1332     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1333       continue;
1334 
1335     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1336       continue;
1337 
1338     F.erase();
1339   }
1340 
1341   F.done();
1342 }
1343 
1344 static bool isUsingDecl(NamedDecl *D) {
1345   return isa<UsingShadowDecl>(D) ||
1346          isa<UnresolvedUsingTypenameDecl>(D) ||
1347          isa<UnresolvedUsingValueDecl>(D);
1348 }
1349 
1350 /// Removes using shadow declarations from the lookup results.
1351 static void RemoveUsingDecls(LookupResult &R) {
1352   LookupResult::Filter F = R.makeFilter();
1353   while (F.hasNext())
1354     if (isUsingDecl(F.next()))
1355       F.erase();
1356 
1357   F.done();
1358 }
1359 
1360 /// \brief Check for this common pattern:
1361 /// @code
1362 /// class S {
1363 ///   S(const S&); // DO NOT IMPLEMENT
1364 ///   void operator=(const S&); // DO NOT IMPLEMENT
1365 /// };
1366 /// @endcode
1367 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1368   // FIXME: Should check for private access too but access is set after we get
1369   // the decl here.
1370   if (D->doesThisDeclarationHaveABody())
1371     return false;
1372 
1373   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1374     return CD->isCopyConstructor();
1375   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1376     return Method->isCopyAssignmentOperator();
1377   return false;
1378 }
1379 
1380 // We need this to handle
1381 //
1382 // typedef struct {
1383 //   void *foo() { return 0; }
1384 // } A;
1385 //
1386 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1387 // for example. If 'A', foo will have external linkage. If we have '*A',
1388 // foo will have no linkage. Since we can't know until we get to the end
1389 // of the typedef, this function finds out if D might have non-external linkage.
1390 // Callers should verify at the end of the TU if it D has external linkage or
1391 // not.
1392 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1393   const DeclContext *DC = D->getDeclContext();
1394   while (!DC->isTranslationUnit()) {
1395     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1396       if (!RD->hasNameForLinkage())
1397         return true;
1398     }
1399     DC = DC->getParent();
1400   }
1401 
1402   return !D->isExternallyVisible();
1403 }
1404 
1405 // FIXME: This needs to be refactored; some other isInMainFile users want
1406 // these semantics.
1407 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1408   if (S.TUKind != TU_Complete)
1409     return false;
1410   return S.SourceMgr.isInMainFile(Loc);
1411 }
1412 
1413 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1414   assert(D);
1415 
1416   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1417     return false;
1418 
1419   // Ignore all entities declared within templates, and out-of-line definitions
1420   // of members of class templates.
1421   if (D->getDeclContext()->isDependentContext() ||
1422       D->getLexicalDeclContext()->isDependentContext())
1423     return false;
1424 
1425   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1426     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1427       return false;
1428 
1429     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1430       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1431         return false;
1432     } else {
1433       // 'static inline' functions are defined in headers; don't warn.
1434       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1435         return false;
1436     }
1437 
1438     if (FD->doesThisDeclarationHaveABody() &&
1439         Context.DeclMustBeEmitted(FD))
1440       return false;
1441   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1442     // Constants and utility variables are defined in headers with internal
1443     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1444     // like "inline".)
1445     if (!isMainFileLoc(*this, VD->getLocation()))
1446       return false;
1447 
1448     if (Context.DeclMustBeEmitted(VD))
1449       return false;
1450 
1451     if (VD->isStaticDataMember() &&
1452         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1453       return false;
1454   } else {
1455     return false;
1456   }
1457 
1458   // Only warn for unused decls internal to the translation unit.
1459   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1460   // for inline functions defined in the main source file, for instance.
1461   return mightHaveNonExternalLinkage(D);
1462 }
1463 
1464 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1465   if (!D)
1466     return;
1467 
1468   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1469     const FunctionDecl *First = FD->getFirstDecl();
1470     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1471       return; // First should already be in the vector.
1472   }
1473 
1474   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1475     const VarDecl *First = VD->getFirstDecl();
1476     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1477       return; // First should already be in the vector.
1478   }
1479 
1480   if (ShouldWarnIfUnusedFileScopedDecl(D))
1481     UnusedFileScopedDecls.push_back(D);
1482 }
1483 
1484 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1485   if (D->isInvalidDecl())
1486     return false;
1487 
1488   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1489       D->hasAttr<ObjCPreciseLifetimeAttr>())
1490     return false;
1491 
1492   if (isa<LabelDecl>(D))
1493     return true;
1494 
1495   // Except for labels, we only care about unused decls that are local to
1496   // functions.
1497   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1498   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1499     // For dependent types, the diagnostic is deferred.
1500     WithinFunction =
1501         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1502   if (!WithinFunction)
1503     return false;
1504 
1505   if (isa<TypedefNameDecl>(D))
1506     return true;
1507 
1508   // White-list anything that isn't a local variable.
1509   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1510     return false;
1511 
1512   // Types of valid local variables should be complete, so this should succeed.
1513   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1514 
1515     // White-list anything with an __attribute__((unused)) type.
1516     QualType Ty = VD->getType();
1517 
1518     // Only look at the outermost level of typedef.
1519     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1520       if (TT->getDecl()->hasAttr<UnusedAttr>())
1521         return false;
1522     }
1523 
1524     // If we failed to complete the type for some reason, or if the type is
1525     // dependent, don't diagnose the variable.
1526     if (Ty->isIncompleteType() || Ty->isDependentType())
1527       return false;
1528 
1529     if (const TagType *TT = Ty->getAs<TagType>()) {
1530       const TagDecl *Tag = TT->getDecl();
1531       if (Tag->hasAttr<UnusedAttr>())
1532         return false;
1533 
1534       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1535         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1536           return false;
1537 
1538         if (const Expr *Init = VD->getInit()) {
1539           if (const ExprWithCleanups *Cleanups =
1540                   dyn_cast<ExprWithCleanups>(Init))
1541             Init = Cleanups->getSubExpr();
1542           const CXXConstructExpr *Construct =
1543             dyn_cast<CXXConstructExpr>(Init);
1544           if (Construct && !Construct->isElidable()) {
1545             CXXConstructorDecl *CD = Construct->getConstructor();
1546             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1547               return false;
1548           }
1549         }
1550       }
1551     }
1552 
1553     // TODO: __attribute__((unused)) templates?
1554   }
1555 
1556   return true;
1557 }
1558 
1559 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1560                                      FixItHint &Hint) {
1561   if (isa<LabelDecl>(D)) {
1562     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1563                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1564     if (AfterColon.isInvalid())
1565       return;
1566     Hint = FixItHint::CreateRemoval(CharSourceRange::
1567                                     getCharRange(D->getLocStart(), AfterColon));
1568   }
1569 }
1570 
1571 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1572   if (D->getTypeForDecl()->isDependentType())
1573     return;
1574 
1575   for (auto *TmpD : D->decls()) {
1576     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1577       DiagnoseUnusedDecl(T);
1578     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1579       DiagnoseUnusedNestedTypedefs(R);
1580   }
1581 }
1582 
1583 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1584 /// unless they are marked attr(unused).
1585 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1586   if (!ShouldDiagnoseUnusedDecl(D))
1587     return;
1588 
1589   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1590     // typedefs can be referenced later on, so the diagnostics are emitted
1591     // at end-of-translation-unit.
1592     UnusedLocalTypedefNameCandidates.insert(TD);
1593     return;
1594   }
1595 
1596   FixItHint Hint;
1597   GenerateFixForUnusedDecl(D, Context, Hint);
1598 
1599   unsigned DiagID;
1600   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1601     DiagID = diag::warn_unused_exception_param;
1602   else if (isa<LabelDecl>(D))
1603     DiagID = diag::warn_unused_label;
1604   else
1605     DiagID = diag::warn_unused_variable;
1606 
1607   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1608 }
1609 
1610 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1611   // Verify that we have no forward references left.  If so, there was a goto
1612   // or address of a label taken, but no definition of it.  Label fwd
1613   // definitions are indicated with a null substmt which is also not a resolved
1614   // MS inline assembly label name.
1615   bool Diagnose = false;
1616   if (L->isMSAsmLabel())
1617     Diagnose = !L->isResolvedMSAsmLabel();
1618   else
1619     Diagnose = L->getStmt() == nullptr;
1620   if (Diagnose)
1621     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1622 }
1623 
1624 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1625   S->mergeNRVOIntoParent();
1626 
1627   if (S->decl_empty()) return;
1628   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1629          "Scope shouldn't contain decls!");
1630 
1631   for (auto *TmpD : S->decls()) {
1632     assert(TmpD && "This decl didn't get pushed??");
1633 
1634     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1635     NamedDecl *D = cast<NamedDecl>(TmpD);
1636 
1637     if (!D->getDeclName()) continue;
1638 
1639     // Diagnose unused variables in this scope.
1640     if (!S->hasUnrecoverableErrorOccurred()) {
1641       DiagnoseUnusedDecl(D);
1642       if (const auto *RD = dyn_cast<RecordDecl>(D))
1643         DiagnoseUnusedNestedTypedefs(RD);
1644     }
1645 
1646     // If this was a forward reference to a label, verify it was defined.
1647     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1648       CheckPoppedLabel(LD, *this);
1649 
1650     // Remove this name from our lexical scope, and warn on it if we haven't
1651     // already.
1652     IdResolver.RemoveDecl(D);
1653     auto ShadowI = ShadowingDecls.find(D);
1654     if (ShadowI != ShadowingDecls.end()) {
1655       if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
1656         Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
1657             << D << FD << FD->getParent();
1658         Diag(FD->getLocation(), diag::note_previous_declaration);
1659       }
1660       ShadowingDecls.erase(ShadowI);
1661     }
1662   }
1663 }
1664 
1665 /// \brief Look for an Objective-C class in the translation unit.
1666 ///
1667 /// \param Id The name of the Objective-C class we're looking for. If
1668 /// typo-correction fixes this name, the Id will be updated
1669 /// to the fixed name.
1670 ///
1671 /// \param IdLoc The location of the name in the translation unit.
1672 ///
1673 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1674 /// if there is no class with the given name.
1675 ///
1676 /// \returns The declaration of the named Objective-C class, or NULL if the
1677 /// class could not be found.
1678 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1679                                               SourceLocation IdLoc,
1680                                               bool DoTypoCorrection) {
1681   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1682   // creation from this context.
1683   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1684 
1685   if (!IDecl && DoTypoCorrection) {
1686     // Perform typo correction at the given location, but only if we
1687     // find an Objective-C class name.
1688     if (TypoCorrection C = CorrectTypo(
1689             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1690             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1691             CTK_ErrorRecovery)) {
1692       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1693       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1694       Id = IDecl->getIdentifier();
1695     }
1696   }
1697   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1698   // This routine must always return a class definition, if any.
1699   if (Def && Def->getDefinition())
1700       Def = Def->getDefinition();
1701   return Def;
1702 }
1703 
1704 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1705 /// from S, where a non-field would be declared. This routine copes
1706 /// with the difference between C and C++ scoping rules in structs and
1707 /// unions. For example, the following code is well-formed in C but
1708 /// ill-formed in C++:
1709 /// @code
1710 /// struct S6 {
1711 ///   enum { BAR } e;
1712 /// };
1713 ///
1714 /// void test_S6() {
1715 ///   struct S6 a;
1716 ///   a.e = BAR;
1717 /// }
1718 /// @endcode
1719 /// For the declaration of BAR, this routine will return a different
1720 /// scope. The scope S will be the scope of the unnamed enumeration
1721 /// within S6. In C++, this routine will return the scope associated
1722 /// with S6, because the enumeration's scope is a transparent
1723 /// context but structures can contain non-field names. In C, this
1724 /// routine will return the translation unit scope, since the
1725 /// enumeration's scope is a transparent context and structures cannot
1726 /// contain non-field names.
1727 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1728   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1729          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1730          (S->isClassScope() && !getLangOpts().CPlusPlus))
1731     S = S->getParent();
1732   return S;
1733 }
1734 
1735 /// \brief Looks up the declaration of "struct objc_super" and
1736 /// saves it for later use in building builtin declaration of
1737 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1738 /// pre-existing declaration exists no action takes place.
1739 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1740                                         IdentifierInfo *II) {
1741   if (!II->isStr("objc_msgSendSuper"))
1742     return;
1743   ASTContext &Context = ThisSema.Context;
1744 
1745   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1746                       SourceLocation(), Sema::LookupTagName);
1747   ThisSema.LookupName(Result, S);
1748   if (Result.getResultKind() == LookupResult::Found)
1749     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1750       Context.setObjCSuperType(Context.getTagDeclType(TD));
1751 }
1752 
1753 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1754   switch (Error) {
1755   case ASTContext::GE_None:
1756     return "";
1757   case ASTContext::GE_Missing_stdio:
1758     return "stdio.h";
1759   case ASTContext::GE_Missing_setjmp:
1760     return "setjmp.h";
1761   case ASTContext::GE_Missing_ucontext:
1762     return "ucontext.h";
1763   }
1764   llvm_unreachable("unhandled error kind");
1765 }
1766 
1767 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1768 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1769 /// if we're creating this built-in in anticipation of redeclaring the
1770 /// built-in.
1771 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1772                                      Scope *S, bool ForRedeclaration,
1773                                      SourceLocation Loc) {
1774   LookupPredefedObjCSuperType(*this, S, II);
1775 
1776   ASTContext::GetBuiltinTypeError Error;
1777   QualType R = Context.GetBuiltinType(ID, Error);
1778   if (Error) {
1779     if (ForRedeclaration)
1780       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1781           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1782     return nullptr;
1783   }
1784 
1785   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
1786     Diag(Loc, diag::ext_implicit_lib_function_decl)
1787         << Context.BuiltinInfo.getName(ID) << R;
1788     if (Context.BuiltinInfo.getHeaderName(ID) &&
1789         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1790       Diag(Loc, diag::note_include_header_or_declare)
1791           << Context.BuiltinInfo.getHeaderName(ID)
1792           << Context.BuiltinInfo.getName(ID);
1793   }
1794 
1795   if (R.isNull())
1796     return nullptr;
1797 
1798   DeclContext *Parent = Context.getTranslationUnitDecl();
1799   if (getLangOpts().CPlusPlus) {
1800     LinkageSpecDecl *CLinkageDecl =
1801         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1802                                 LinkageSpecDecl::lang_c, false);
1803     CLinkageDecl->setImplicit();
1804     Parent->addDecl(CLinkageDecl);
1805     Parent = CLinkageDecl;
1806   }
1807 
1808   FunctionDecl *New = FunctionDecl::Create(Context,
1809                                            Parent,
1810                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1811                                            SC_Extern,
1812                                            false,
1813                                            R->isFunctionProtoType());
1814   New->setImplicit();
1815 
1816   // Create Decl objects for each parameter, adding them to the
1817   // FunctionDecl.
1818   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1819     SmallVector<ParmVarDecl*, 16> Params;
1820     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1821       ParmVarDecl *parm =
1822           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1823                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1824                               SC_None, nullptr);
1825       parm->setScopeInfo(0, i);
1826       Params.push_back(parm);
1827     }
1828     New->setParams(Params);
1829   }
1830 
1831   AddKnownFunctionAttributes(New);
1832   RegisterLocallyScopedExternCDecl(New, S);
1833 
1834   // TUScope is the translation-unit scope to insert this function into.
1835   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1836   // relate Scopes to DeclContexts, and probably eliminate CurContext
1837   // entirely, but we're not there yet.
1838   DeclContext *SavedContext = CurContext;
1839   CurContext = Parent;
1840   PushOnScopeChains(New, TUScope);
1841   CurContext = SavedContext;
1842   return New;
1843 }
1844 
1845 /// Typedef declarations don't have linkage, but they still denote the same
1846 /// entity if their types are the same.
1847 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1848 /// isSameEntity.
1849 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1850                                                      TypedefNameDecl *Decl,
1851                                                      LookupResult &Previous) {
1852   // This is only interesting when modules are enabled.
1853   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1854     return;
1855 
1856   // Empty sets are uninteresting.
1857   if (Previous.empty())
1858     return;
1859 
1860   LookupResult::Filter Filter = Previous.makeFilter();
1861   while (Filter.hasNext()) {
1862     NamedDecl *Old = Filter.next();
1863 
1864     // Non-hidden declarations are never ignored.
1865     if (S.isVisible(Old))
1866       continue;
1867 
1868     // Declarations of the same entity are not ignored, even if they have
1869     // different linkages.
1870     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1871       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1872                                 Decl->getUnderlyingType()))
1873         continue;
1874 
1875       // If both declarations give a tag declaration a typedef name for linkage
1876       // purposes, then they declare the same entity.
1877       if (S.getLangOpts().CPlusPlus &&
1878           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1879           Decl->getAnonDeclWithTypedefName())
1880         continue;
1881     }
1882 
1883     Filter.erase();
1884   }
1885 
1886   Filter.done();
1887 }
1888 
1889 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1890   QualType OldType;
1891   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1892     OldType = OldTypedef->getUnderlyingType();
1893   else
1894     OldType = Context.getTypeDeclType(Old);
1895   QualType NewType = New->getUnderlyingType();
1896 
1897   if (NewType->isVariablyModifiedType()) {
1898     // Must not redefine a typedef with a variably-modified type.
1899     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1900     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1901       << Kind << NewType;
1902     if (Old->getLocation().isValid())
1903       Diag(Old->getLocation(), diag::note_previous_definition);
1904     New->setInvalidDecl();
1905     return true;
1906   }
1907 
1908   if (OldType != NewType &&
1909       !OldType->isDependentType() &&
1910       !NewType->isDependentType() &&
1911       !Context.hasSameType(OldType, NewType)) {
1912     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1913     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1914       << Kind << NewType << OldType;
1915     if (Old->getLocation().isValid())
1916       Diag(Old->getLocation(), diag::note_previous_definition);
1917     New->setInvalidDecl();
1918     return true;
1919   }
1920   return false;
1921 }
1922 
1923 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1924 /// same name and scope as a previous declaration 'Old'.  Figure out
1925 /// how to resolve this situation, merging decls or emitting
1926 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1927 ///
1928 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
1929                                 LookupResult &OldDecls) {
1930   // If the new decl is known invalid already, don't bother doing any
1931   // merging checks.
1932   if (New->isInvalidDecl()) return;
1933 
1934   // Allow multiple definitions for ObjC built-in typedefs.
1935   // FIXME: Verify the underlying types are equivalent!
1936   if (getLangOpts().ObjC1) {
1937     const IdentifierInfo *TypeID = New->getIdentifier();
1938     switch (TypeID->getLength()) {
1939     default: break;
1940     case 2:
1941       {
1942         if (!TypeID->isStr("id"))
1943           break;
1944         QualType T = New->getUnderlyingType();
1945         if (!T->isPointerType())
1946           break;
1947         if (!T->isVoidPointerType()) {
1948           QualType PT = T->getAs<PointerType>()->getPointeeType();
1949           if (!PT->isStructureType())
1950             break;
1951         }
1952         Context.setObjCIdRedefinitionType(T);
1953         // Install the built-in type for 'id', ignoring the current definition.
1954         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1955         return;
1956       }
1957     case 5:
1958       if (!TypeID->isStr("Class"))
1959         break;
1960       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1961       // Install the built-in type for 'Class', ignoring the current definition.
1962       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1963       return;
1964     case 3:
1965       if (!TypeID->isStr("SEL"))
1966         break;
1967       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1968       // Install the built-in type for 'SEL', ignoring the current definition.
1969       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1970       return;
1971     }
1972     // Fall through - the typedef name was not a builtin type.
1973   }
1974 
1975   // Verify the old decl was also a type.
1976   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1977   if (!Old) {
1978     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1979       << New->getDeclName();
1980 
1981     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1982     if (OldD->getLocation().isValid())
1983       Diag(OldD->getLocation(), diag::note_previous_definition);
1984 
1985     return New->setInvalidDecl();
1986   }
1987 
1988   // If the old declaration is invalid, just give up here.
1989   if (Old->isInvalidDecl())
1990     return New->setInvalidDecl();
1991 
1992   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1993     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
1994     auto *NewTag = New->getAnonDeclWithTypedefName();
1995     NamedDecl *Hidden = nullptr;
1996     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
1997         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
1998         !hasVisibleDefinition(OldTag, &Hidden)) {
1999       // There is a definition of this tag, but it is not visible. Use it
2000       // instead of our tag.
2001       New->setTypeForDecl(OldTD->getTypeForDecl());
2002       if (OldTD->isModed())
2003         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2004                                     OldTD->getUnderlyingType());
2005       else
2006         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2007 
2008       // Make the old tag definition visible.
2009       makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
2010 
2011       // If this was an unscoped enumeration, yank all of its enumerators
2012       // out of the scope.
2013       if (isa<EnumDecl>(NewTag)) {
2014         Scope *EnumScope = getNonFieldDeclScope(S);
2015         for (auto *D : NewTag->decls()) {
2016           auto *ED = cast<EnumConstantDecl>(D);
2017           assert(EnumScope->isDeclScope(ED));
2018           EnumScope->RemoveDecl(ED);
2019           IdResolver.RemoveDecl(ED);
2020           ED->getLexicalDeclContext()->removeDecl(ED);
2021         }
2022       }
2023     }
2024   }
2025 
2026   // If the typedef types are not identical, reject them in all languages and
2027   // with any extensions enabled.
2028   if (isIncompatibleTypedef(Old, New))
2029     return;
2030 
2031   // The types match.  Link up the redeclaration chain and merge attributes if
2032   // the old declaration was a typedef.
2033   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2034     New->setPreviousDecl(Typedef);
2035     mergeDeclAttributes(New, Old);
2036   }
2037 
2038   if (getLangOpts().MicrosoftExt)
2039     return;
2040 
2041   if (getLangOpts().CPlusPlus) {
2042     // C++ [dcl.typedef]p2:
2043     //   In a given non-class scope, a typedef specifier can be used to
2044     //   redefine the name of any type declared in that scope to refer
2045     //   to the type to which it already refers.
2046     if (!isa<CXXRecordDecl>(CurContext))
2047       return;
2048 
2049     // C++0x [dcl.typedef]p4:
2050     //   In a given class scope, a typedef specifier can be used to redefine
2051     //   any class-name declared in that scope that is not also a typedef-name
2052     //   to refer to the type to which it already refers.
2053     //
2054     // This wording came in via DR424, which was a correction to the
2055     // wording in DR56, which accidentally banned code like:
2056     //
2057     //   struct S {
2058     //     typedef struct A { } A;
2059     //   };
2060     //
2061     // in the C++03 standard. We implement the C++0x semantics, which
2062     // allow the above but disallow
2063     //
2064     //   struct S {
2065     //     typedef int I;
2066     //     typedef int I;
2067     //   };
2068     //
2069     // since that was the intent of DR56.
2070     if (!isa<TypedefNameDecl>(Old))
2071       return;
2072 
2073     Diag(New->getLocation(), diag::err_redefinition)
2074       << New->getDeclName();
2075     Diag(Old->getLocation(), diag::note_previous_definition);
2076     return New->setInvalidDecl();
2077   }
2078 
2079   // Modules always permit redefinition of typedefs, as does C11.
2080   if (getLangOpts().Modules || getLangOpts().C11)
2081     return;
2082 
2083   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2084   // is normally mapped to an error, but can be controlled with
2085   // -Wtypedef-redefinition.  If either the original or the redefinition is
2086   // in a system header, don't emit this for compatibility with GCC.
2087   if (getDiagnostics().getSuppressSystemWarnings() &&
2088       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2089        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2090     return;
2091 
2092   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2093     << New->getDeclName();
2094   Diag(Old->getLocation(), diag::note_previous_definition);
2095 }
2096 
2097 /// DeclhasAttr - returns true if decl Declaration already has the target
2098 /// attribute.
2099 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2100   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2101   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2102   for (const auto *i : D->attrs())
2103     if (i->getKind() == A->getKind()) {
2104       if (Ann) {
2105         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2106           return true;
2107         continue;
2108       }
2109       // FIXME: Don't hardcode this check
2110       if (OA && isa<OwnershipAttr>(i))
2111         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2112       return true;
2113     }
2114 
2115   return false;
2116 }
2117 
2118 static bool isAttributeTargetADefinition(Decl *D) {
2119   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2120     return VD->isThisDeclarationADefinition();
2121   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2122     return TD->isCompleteDefinition() || TD->isBeingDefined();
2123   return true;
2124 }
2125 
2126 /// Merge alignment attributes from \p Old to \p New, taking into account the
2127 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2128 ///
2129 /// \return \c true if any attributes were added to \p New.
2130 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2131   // Look for alignas attributes on Old, and pick out whichever attribute
2132   // specifies the strictest alignment requirement.
2133   AlignedAttr *OldAlignasAttr = nullptr;
2134   AlignedAttr *OldStrictestAlignAttr = nullptr;
2135   unsigned OldAlign = 0;
2136   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2137     // FIXME: We have no way of representing inherited dependent alignments
2138     // in a case like:
2139     //   template<int A, int B> struct alignas(A) X;
2140     //   template<int A, int B> struct alignas(B) X {};
2141     // For now, we just ignore any alignas attributes which are not on the
2142     // definition in such a case.
2143     if (I->isAlignmentDependent())
2144       return false;
2145 
2146     if (I->isAlignas())
2147       OldAlignasAttr = I;
2148 
2149     unsigned Align = I->getAlignment(S.Context);
2150     if (Align > OldAlign) {
2151       OldAlign = Align;
2152       OldStrictestAlignAttr = I;
2153     }
2154   }
2155 
2156   // Look for alignas attributes on New.
2157   AlignedAttr *NewAlignasAttr = nullptr;
2158   unsigned NewAlign = 0;
2159   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2160     if (I->isAlignmentDependent())
2161       return false;
2162 
2163     if (I->isAlignas())
2164       NewAlignasAttr = I;
2165 
2166     unsigned Align = I->getAlignment(S.Context);
2167     if (Align > NewAlign)
2168       NewAlign = Align;
2169   }
2170 
2171   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2172     // Both declarations have 'alignas' attributes. We require them to match.
2173     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2174     // fall short. (If two declarations both have alignas, they must both match
2175     // every definition, and so must match each other if there is a definition.)
2176 
2177     // If either declaration only contains 'alignas(0)' specifiers, then it
2178     // specifies the natural alignment for the type.
2179     if (OldAlign == 0 || NewAlign == 0) {
2180       QualType Ty;
2181       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2182         Ty = VD->getType();
2183       else
2184         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2185 
2186       if (OldAlign == 0)
2187         OldAlign = S.Context.getTypeAlign(Ty);
2188       if (NewAlign == 0)
2189         NewAlign = S.Context.getTypeAlign(Ty);
2190     }
2191 
2192     if (OldAlign != NewAlign) {
2193       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2194         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2195         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2196       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2197     }
2198   }
2199 
2200   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2201     // C++11 [dcl.align]p6:
2202     //   if any declaration of an entity has an alignment-specifier,
2203     //   every defining declaration of that entity shall specify an
2204     //   equivalent alignment.
2205     // C11 6.7.5/7:
2206     //   If the definition of an object does not have an alignment
2207     //   specifier, any other declaration of that object shall also
2208     //   have no alignment specifier.
2209     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2210       << OldAlignasAttr;
2211     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2212       << OldAlignasAttr;
2213   }
2214 
2215   bool AnyAdded = false;
2216 
2217   // Ensure we have an attribute representing the strictest alignment.
2218   if (OldAlign > NewAlign) {
2219     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2220     Clone->setInherited(true);
2221     New->addAttr(Clone);
2222     AnyAdded = true;
2223   }
2224 
2225   // Ensure we have an alignas attribute if the old declaration had one.
2226   if (OldAlignasAttr && !NewAlignasAttr &&
2227       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2228     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2229     Clone->setInherited(true);
2230     New->addAttr(Clone);
2231     AnyAdded = true;
2232   }
2233 
2234   return AnyAdded;
2235 }
2236 
2237 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2238                                const InheritableAttr *Attr,
2239                                Sema::AvailabilityMergeKind AMK) {
2240   InheritableAttr *NewAttr = nullptr;
2241   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2242   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2243     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2244                                       AA->isImplicit(), AA->getIntroduced(),
2245                                       AA->getDeprecated(),
2246                                       AA->getObsoleted(), AA->getUnavailable(),
2247                                       AA->getMessage(), AA->getStrict(),
2248                                       AA->getReplacement(), AMK,
2249                                       AttrSpellingListIndex);
2250   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2251     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2252                                     AttrSpellingListIndex);
2253   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2254     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2255                                         AttrSpellingListIndex);
2256   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2257     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2258                                    AttrSpellingListIndex);
2259   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2260     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2261                                    AttrSpellingListIndex);
2262   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2263     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2264                                 FA->getFormatIdx(), FA->getFirstArg(),
2265                                 AttrSpellingListIndex);
2266   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2267     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2268                                  AttrSpellingListIndex);
2269   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2270     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2271                                        AttrSpellingListIndex,
2272                                        IA->getSemanticSpelling());
2273   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2274     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2275                                       &S.Context.Idents.get(AA->getSpelling()),
2276                                       AttrSpellingListIndex);
2277   else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2278     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2279   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2280     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2281   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2282     NewAttr = S.mergeInternalLinkageAttr(
2283         D, InternalLinkageA->getRange(),
2284         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2285         AttrSpellingListIndex);
2286   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2287     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2288                                 &S.Context.Idents.get(CommonA->getSpelling()),
2289                                 AttrSpellingListIndex);
2290   else if (isa<AlignedAttr>(Attr))
2291     // AlignedAttrs are handled separately, because we need to handle all
2292     // such attributes on a declaration at the same time.
2293     NewAttr = nullptr;
2294   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2295            (AMK == Sema::AMK_Override ||
2296             AMK == Sema::AMK_ProtocolImplementation))
2297     NewAttr = nullptr;
2298   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2299     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2300 
2301   if (NewAttr) {
2302     NewAttr->setInherited(true);
2303     D->addAttr(NewAttr);
2304     if (isa<MSInheritanceAttr>(NewAttr))
2305       S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2306     return true;
2307   }
2308 
2309   return false;
2310 }
2311 
2312 static const Decl *getDefinition(const Decl *D) {
2313   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2314     return TD->getDefinition();
2315   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2316     const VarDecl *Def = VD->getDefinition();
2317     if (Def)
2318       return Def;
2319     return VD->getActingDefinition();
2320   }
2321   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2322     const FunctionDecl* Def;
2323     if (FD->isDefined(Def))
2324       return Def;
2325   }
2326   return nullptr;
2327 }
2328 
2329 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2330   for (const auto *Attribute : D->attrs())
2331     if (Attribute->getKind() == Kind)
2332       return true;
2333   return false;
2334 }
2335 
2336 /// checkNewAttributesAfterDef - If we already have a definition, check that
2337 /// there are no new attributes in this declaration.
2338 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2339   if (!New->hasAttrs())
2340     return;
2341 
2342   const Decl *Def = getDefinition(Old);
2343   if (!Def || Def == New)
2344     return;
2345 
2346   AttrVec &NewAttributes = New->getAttrs();
2347   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2348     const Attr *NewAttribute = NewAttributes[I];
2349 
2350     if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2351       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2352         Sema::SkipBodyInfo SkipBody;
2353         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2354 
2355         // If we're skipping this definition, drop the "alias" attribute.
2356         if (SkipBody.ShouldSkip) {
2357           NewAttributes.erase(NewAttributes.begin() + I);
2358           --E;
2359           continue;
2360         }
2361       } else {
2362         VarDecl *VD = cast<VarDecl>(New);
2363         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2364                                 VarDecl::TentativeDefinition
2365                             ? diag::err_alias_after_tentative
2366                             : diag::err_redefinition;
2367         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2368         S.Diag(Def->getLocation(), diag::note_previous_definition);
2369         VD->setInvalidDecl();
2370       }
2371       ++I;
2372       continue;
2373     }
2374 
2375     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2376       // Tentative definitions are only interesting for the alias check above.
2377       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2378         ++I;
2379         continue;
2380       }
2381     }
2382 
2383     if (hasAttribute(Def, NewAttribute->getKind())) {
2384       ++I;
2385       continue; // regular attr merging will take care of validating this.
2386     }
2387 
2388     if (isa<C11NoReturnAttr>(NewAttribute)) {
2389       // C's _Noreturn is allowed to be added to a function after it is defined.
2390       ++I;
2391       continue;
2392     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2393       if (AA->isAlignas()) {
2394         // C++11 [dcl.align]p6:
2395         //   if any declaration of an entity has an alignment-specifier,
2396         //   every defining declaration of that entity shall specify an
2397         //   equivalent alignment.
2398         // C11 6.7.5/7:
2399         //   If the definition of an object does not have an alignment
2400         //   specifier, any other declaration of that object shall also
2401         //   have no alignment specifier.
2402         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2403           << AA;
2404         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2405           << AA;
2406         NewAttributes.erase(NewAttributes.begin() + I);
2407         --E;
2408         continue;
2409       }
2410     }
2411 
2412     S.Diag(NewAttribute->getLocation(),
2413            diag::warn_attribute_precede_definition);
2414     S.Diag(Def->getLocation(), diag::note_previous_definition);
2415     NewAttributes.erase(NewAttributes.begin() + I);
2416     --E;
2417   }
2418 }
2419 
2420 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2421 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2422                                AvailabilityMergeKind AMK) {
2423   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2424     UsedAttr *NewAttr = OldAttr->clone(Context);
2425     NewAttr->setInherited(true);
2426     New->addAttr(NewAttr);
2427   }
2428 
2429   if (!Old->hasAttrs() && !New->hasAttrs())
2430     return;
2431 
2432   // Attributes declared post-definition are currently ignored.
2433   checkNewAttributesAfterDef(*this, New, Old);
2434 
2435   if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
2436     if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
2437       if (OldA->getLabel() != NewA->getLabel()) {
2438         // This redeclaration changes __asm__ label.
2439         Diag(New->getLocation(), diag::err_different_asm_label);
2440         Diag(OldA->getLocation(), diag::note_previous_declaration);
2441       }
2442     } else if (Old->isUsed()) {
2443       // This redeclaration adds an __asm__ label to a declaration that has
2444       // already been ODR-used.
2445       Diag(New->getLocation(), diag::err_late_asm_label_name)
2446         << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
2447     }
2448   }
2449 
2450   // Re-declaration cannot add abi_tag's.
2451   if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
2452     if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
2453       for (const auto &NewTag : NewAbiTagAttr->tags()) {
2454         if (std::find(OldAbiTagAttr->tags_begin(), OldAbiTagAttr->tags_end(),
2455                       NewTag) == OldAbiTagAttr->tags_end()) {
2456           Diag(NewAbiTagAttr->getLocation(),
2457                diag::err_new_abi_tag_on_redeclaration)
2458               << NewTag;
2459           Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
2460         }
2461       }
2462     } else {
2463       Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
2464       Diag(Old->getLocation(), diag::note_previous_declaration);
2465     }
2466   }
2467 
2468   if (!Old->hasAttrs())
2469     return;
2470 
2471   bool foundAny = New->hasAttrs();
2472 
2473   // Ensure that any moving of objects within the allocated map is done before
2474   // we process them.
2475   if (!foundAny) New->setAttrs(AttrVec());
2476 
2477   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2478     // Ignore deprecated/unavailable/availability attributes if requested.
2479     AvailabilityMergeKind LocalAMK = AMK_None;
2480     if (isa<DeprecatedAttr>(I) ||
2481         isa<UnavailableAttr>(I) ||
2482         isa<AvailabilityAttr>(I)) {
2483       switch (AMK) {
2484       case AMK_None:
2485         continue;
2486 
2487       case AMK_Redeclaration:
2488       case AMK_Override:
2489       case AMK_ProtocolImplementation:
2490         LocalAMK = AMK;
2491         break;
2492       }
2493     }
2494 
2495     // Already handled.
2496     if (isa<UsedAttr>(I))
2497       continue;
2498 
2499     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2500       foundAny = true;
2501   }
2502 
2503   if (mergeAlignedAttrs(*this, New, Old))
2504     foundAny = true;
2505 
2506   if (!foundAny) New->dropAttrs();
2507 }
2508 
2509 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2510 /// to the new one.
2511 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2512                                      const ParmVarDecl *oldDecl,
2513                                      Sema &S) {
2514   // C++11 [dcl.attr.depend]p2:
2515   //   The first declaration of a function shall specify the
2516   //   carries_dependency attribute for its declarator-id if any declaration
2517   //   of the function specifies the carries_dependency attribute.
2518   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2519   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2520     S.Diag(CDA->getLocation(),
2521            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2522     // Find the first declaration of the parameter.
2523     // FIXME: Should we build redeclaration chains for function parameters?
2524     const FunctionDecl *FirstFD =
2525       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2526     const ParmVarDecl *FirstVD =
2527       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2528     S.Diag(FirstVD->getLocation(),
2529            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2530   }
2531 
2532   if (!oldDecl->hasAttrs())
2533     return;
2534 
2535   bool foundAny = newDecl->hasAttrs();
2536 
2537   // Ensure that any moving of objects within the allocated map is
2538   // done before we process them.
2539   if (!foundAny) newDecl->setAttrs(AttrVec());
2540 
2541   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2542     if (!DeclHasAttr(newDecl, I)) {
2543       InheritableAttr *newAttr =
2544         cast<InheritableParamAttr>(I->clone(S.Context));
2545       newAttr->setInherited(true);
2546       newDecl->addAttr(newAttr);
2547       foundAny = true;
2548     }
2549   }
2550 
2551   if (!foundAny) newDecl->dropAttrs();
2552 }
2553 
2554 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2555                                 const ParmVarDecl *OldParam,
2556                                 Sema &S) {
2557   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2558     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2559       if (*Oldnullability != *Newnullability) {
2560         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2561           << DiagNullabilityKind(
2562                *Newnullability,
2563                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2564                 != 0))
2565           << DiagNullabilityKind(
2566                *Oldnullability,
2567                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2568                 != 0));
2569         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2570       }
2571     } else {
2572       QualType NewT = NewParam->getType();
2573       NewT = S.Context.getAttributedType(
2574                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2575                          NewT, NewT);
2576       NewParam->setType(NewT);
2577     }
2578   }
2579 }
2580 
2581 namespace {
2582 
2583 /// Used in MergeFunctionDecl to keep track of function parameters in
2584 /// C.
2585 struct GNUCompatibleParamWarning {
2586   ParmVarDecl *OldParm;
2587   ParmVarDecl *NewParm;
2588   QualType PromotedType;
2589 };
2590 
2591 } // end anonymous namespace
2592 
2593 /// getSpecialMember - get the special member enum for a method.
2594 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2595   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2596     if (Ctor->isDefaultConstructor())
2597       return Sema::CXXDefaultConstructor;
2598 
2599     if (Ctor->isCopyConstructor())
2600       return Sema::CXXCopyConstructor;
2601 
2602     if (Ctor->isMoveConstructor())
2603       return Sema::CXXMoveConstructor;
2604   } else if (isa<CXXDestructorDecl>(MD)) {
2605     return Sema::CXXDestructor;
2606   } else if (MD->isCopyAssignmentOperator()) {
2607     return Sema::CXXCopyAssignment;
2608   } else if (MD->isMoveAssignmentOperator()) {
2609     return Sema::CXXMoveAssignment;
2610   }
2611 
2612   return Sema::CXXInvalid;
2613 }
2614 
2615 // Determine whether the previous declaration was a definition, implicit
2616 // declaration, or a declaration.
2617 template <typename T>
2618 static std::pair<diag::kind, SourceLocation>
2619 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2620   diag::kind PrevDiag;
2621   SourceLocation OldLocation = Old->getLocation();
2622   if (Old->isThisDeclarationADefinition())
2623     PrevDiag = diag::note_previous_definition;
2624   else if (Old->isImplicit()) {
2625     PrevDiag = diag::note_previous_implicit_declaration;
2626     if (OldLocation.isInvalid())
2627       OldLocation = New->getLocation();
2628   } else
2629     PrevDiag = diag::note_previous_declaration;
2630   return std::make_pair(PrevDiag, OldLocation);
2631 }
2632 
2633 /// canRedefineFunction - checks if a function can be redefined. Currently,
2634 /// only extern inline functions can be redefined, and even then only in
2635 /// GNU89 mode.
2636 static bool canRedefineFunction(const FunctionDecl *FD,
2637                                 const LangOptions& LangOpts) {
2638   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2639           !LangOpts.CPlusPlus &&
2640           FD->isInlineSpecified() &&
2641           FD->getStorageClass() == SC_Extern);
2642 }
2643 
2644 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2645   const AttributedType *AT = T->getAs<AttributedType>();
2646   while (AT && !AT->isCallingConv())
2647     AT = AT->getModifiedType()->getAs<AttributedType>();
2648   return AT;
2649 }
2650 
2651 template <typename T>
2652 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2653   const DeclContext *DC = Old->getDeclContext();
2654   if (DC->isRecord())
2655     return false;
2656 
2657   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2658   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2659     return true;
2660   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2661     return true;
2662   return false;
2663 }
2664 
2665 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2666 static bool isExternC(VarTemplateDecl *) { return false; }
2667 
2668 /// \brief Check whether a redeclaration of an entity introduced by a
2669 /// using-declaration is valid, given that we know it's not an overload
2670 /// (nor a hidden tag declaration).
2671 template<typename ExpectedDecl>
2672 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2673                                    ExpectedDecl *New) {
2674   // C++11 [basic.scope.declarative]p4:
2675   //   Given a set of declarations in a single declarative region, each of
2676   //   which specifies the same unqualified name,
2677   //   -- they shall all refer to the same entity, or all refer to functions
2678   //      and function templates; or
2679   //   -- exactly one declaration shall declare a class name or enumeration
2680   //      name that is not a typedef name and the other declarations shall all
2681   //      refer to the same variable or enumerator, or all refer to functions
2682   //      and function templates; in this case the class name or enumeration
2683   //      name is hidden (3.3.10).
2684 
2685   // C++11 [namespace.udecl]p14:
2686   //   If a function declaration in namespace scope or block scope has the
2687   //   same name and the same parameter-type-list as a function introduced
2688   //   by a using-declaration, and the declarations do not declare the same
2689   //   function, the program is ill-formed.
2690 
2691   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2692   if (Old &&
2693       !Old->getDeclContext()->getRedeclContext()->Equals(
2694           New->getDeclContext()->getRedeclContext()) &&
2695       !(isExternC(Old) && isExternC(New)))
2696     Old = nullptr;
2697 
2698   if (!Old) {
2699     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2700     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2701     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2702     return true;
2703   }
2704   return false;
2705 }
2706 
2707 static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A,
2708                                             const FunctionDecl *B) {
2709   assert(A->getNumParams() == B->getNumParams());
2710 
2711   auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
2712     const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
2713     const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
2714     if (AttrA == AttrB)
2715       return true;
2716     return AttrA && AttrB && AttrA->getType() == AttrB->getType();
2717   };
2718 
2719   return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
2720 }
2721 
2722 /// MergeFunctionDecl - We just parsed a function 'New' from
2723 /// declarator D which has the same name and scope as a previous
2724 /// declaration 'Old'.  Figure out how to resolve this situation,
2725 /// merging decls or emitting diagnostics as appropriate.
2726 ///
2727 /// In C++, New and Old must be declarations that are not
2728 /// overloaded. Use IsOverload to determine whether New and Old are
2729 /// overloaded, and to select the Old declaration that New should be
2730 /// merged with.
2731 ///
2732 /// Returns true if there was an error, false otherwise.
2733 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2734                              Scope *S, bool MergeTypeWithOld) {
2735   // Verify the old decl was also a function.
2736   FunctionDecl *Old = OldD->getAsFunction();
2737   if (!Old) {
2738     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2739       if (New->getFriendObjectKind()) {
2740         Diag(New->getLocation(), diag::err_using_decl_friend);
2741         Diag(Shadow->getTargetDecl()->getLocation(),
2742              diag::note_using_decl_target);
2743         Diag(Shadow->getUsingDecl()->getLocation(),
2744              diag::note_using_decl) << 0;
2745         return true;
2746       }
2747 
2748       // Check whether the two declarations might declare the same function.
2749       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2750         return true;
2751       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2752     } else {
2753       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2754         << New->getDeclName();
2755       Diag(OldD->getLocation(), diag::note_previous_definition);
2756       return true;
2757     }
2758   }
2759 
2760   // If the old declaration is invalid, just give up here.
2761   if (Old->isInvalidDecl())
2762     return true;
2763 
2764   diag::kind PrevDiag;
2765   SourceLocation OldLocation;
2766   std::tie(PrevDiag, OldLocation) =
2767       getNoteDiagForInvalidRedeclaration(Old, New);
2768 
2769   // Don't complain about this if we're in GNU89 mode and the old function
2770   // is an extern inline function.
2771   // Don't complain about specializations. They are not supposed to have
2772   // storage classes.
2773   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2774       New->getStorageClass() == SC_Static &&
2775       Old->hasExternalFormalLinkage() &&
2776       !New->getTemplateSpecializationInfo() &&
2777       !canRedefineFunction(Old, getLangOpts())) {
2778     if (getLangOpts().MicrosoftExt) {
2779       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2780       Diag(OldLocation, PrevDiag);
2781     } else {
2782       Diag(New->getLocation(), diag::err_static_non_static) << New;
2783       Diag(OldLocation, PrevDiag);
2784       return true;
2785     }
2786   }
2787 
2788   if (New->hasAttr<InternalLinkageAttr>() &&
2789       !Old->hasAttr<InternalLinkageAttr>()) {
2790     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2791         << New->getDeclName();
2792     Diag(Old->getLocation(), diag::note_previous_definition);
2793     New->dropAttr<InternalLinkageAttr>();
2794   }
2795 
2796   // If a function is first declared with a calling convention, but is later
2797   // declared or defined without one, all following decls assume the calling
2798   // convention of the first.
2799   //
2800   // It's OK if a function is first declared without a calling convention,
2801   // but is later declared or defined with the default calling convention.
2802   //
2803   // To test if either decl has an explicit calling convention, we look for
2804   // AttributedType sugar nodes on the type as written.  If they are missing or
2805   // were canonicalized away, we assume the calling convention was implicit.
2806   //
2807   // Note also that we DO NOT return at this point, because we still have
2808   // other tests to run.
2809   QualType OldQType = Context.getCanonicalType(Old->getType());
2810   QualType NewQType = Context.getCanonicalType(New->getType());
2811   const FunctionType *OldType = cast<FunctionType>(OldQType);
2812   const FunctionType *NewType = cast<FunctionType>(NewQType);
2813   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2814   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2815   bool RequiresAdjustment = false;
2816 
2817   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2818     FunctionDecl *First = Old->getFirstDecl();
2819     const FunctionType *FT =
2820         First->getType().getCanonicalType()->castAs<FunctionType>();
2821     FunctionType::ExtInfo FI = FT->getExtInfo();
2822     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2823     if (!NewCCExplicit) {
2824       // Inherit the CC from the previous declaration if it was specified
2825       // there but not here.
2826       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2827       RequiresAdjustment = true;
2828     } else {
2829       // Calling conventions aren't compatible, so complain.
2830       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2831       Diag(New->getLocation(), diag::err_cconv_change)
2832         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2833         << !FirstCCExplicit
2834         << (!FirstCCExplicit ? "" :
2835             FunctionType::getNameForCallConv(FI.getCC()));
2836 
2837       // Put the note on the first decl, since it is the one that matters.
2838       Diag(First->getLocation(), diag::note_previous_declaration);
2839       return true;
2840     }
2841   }
2842 
2843   // FIXME: diagnose the other way around?
2844   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2845     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2846     RequiresAdjustment = true;
2847   }
2848 
2849   // Merge regparm attribute.
2850   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2851       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2852     if (NewTypeInfo.getHasRegParm()) {
2853       Diag(New->getLocation(), diag::err_regparm_mismatch)
2854         << NewType->getRegParmType()
2855         << OldType->getRegParmType();
2856       Diag(OldLocation, diag::note_previous_declaration);
2857       return true;
2858     }
2859 
2860     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2861     RequiresAdjustment = true;
2862   }
2863 
2864   // Merge ns_returns_retained attribute.
2865   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2866     if (NewTypeInfo.getProducesResult()) {
2867       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2868       Diag(OldLocation, diag::note_previous_declaration);
2869       return true;
2870     }
2871 
2872     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2873     RequiresAdjustment = true;
2874   }
2875 
2876   if (RequiresAdjustment) {
2877     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2878     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2879     New->setType(QualType(AdjustedType, 0));
2880     NewQType = Context.getCanonicalType(New->getType());
2881     NewType = cast<FunctionType>(NewQType);
2882   }
2883 
2884   // If this redeclaration makes the function inline, we may need to add it to
2885   // UndefinedButUsed.
2886   if (!Old->isInlined() && New->isInlined() &&
2887       !New->hasAttr<GNUInlineAttr>() &&
2888       !getLangOpts().GNUInline &&
2889       Old->isUsed(false) &&
2890       !Old->isDefined() && !New->isThisDeclarationADefinition())
2891     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2892                                            SourceLocation()));
2893 
2894   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2895   // about it.
2896   if (New->hasAttr<GNUInlineAttr>() &&
2897       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2898     UndefinedButUsed.erase(Old->getCanonicalDecl());
2899   }
2900 
2901   // If pass_object_size params don't match up perfectly, this isn't a valid
2902   // redeclaration.
2903   if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
2904       !hasIdenticalPassObjectSizeAttrs(Old, New)) {
2905     Diag(New->getLocation(), diag::err_different_pass_object_size_params)
2906         << New->getDeclName();
2907     Diag(OldLocation, PrevDiag) << Old << Old->getType();
2908     return true;
2909   }
2910 
2911   if (getLangOpts().CPlusPlus) {
2912     // (C++98 13.1p2):
2913     //   Certain function declarations cannot be overloaded:
2914     //     -- Function declarations that differ only in the return type
2915     //        cannot be overloaded.
2916 
2917     // Go back to the type source info to compare the declared return types,
2918     // per C++1y [dcl.type.auto]p13:
2919     //   Redeclarations or specializations of a function or function template
2920     //   with a declared return type that uses a placeholder type shall also
2921     //   use that placeholder, not a deduced type.
2922     QualType OldDeclaredReturnType =
2923         (Old->getTypeSourceInfo()
2924              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2925              : OldType)->getReturnType();
2926     QualType NewDeclaredReturnType =
2927         (New->getTypeSourceInfo()
2928              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2929              : NewType)->getReturnType();
2930     QualType ResQT;
2931     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2932         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2933           New->isLocalExternDecl())) {
2934       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2935           OldDeclaredReturnType->isObjCObjectPointerType())
2936         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2937       if (ResQT.isNull()) {
2938         if (New->isCXXClassMember() && New->isOutOfLine())
2939           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2940               << New << New->getReturnTypeSourceRange();
2941         else
2942           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2943               << New->getReturnTypeSourceRange();
2944         Diag(OldLocation, PrevDiag) << Old << Old->getType()
2945                                     << Old->getReturnTypeSourceRange();
2946         return true;
2947       }
2948       else
2949         NewQType = ResQT;
2950     }
2951 
2952     QualType OldReturnType = OldType->getReturnType();
2953     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2954     if (OldReturnType != NewReturnType) {
2955       // If this function has a deduced return type and has already been
2956       // defined, copy the deduced value from the old declaration.
2957       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2958       if (OldAT && OldAT->isDeduced()) {
2959         New->setType(
2960             SubstAutoType(New->getType(),
2961                           OldAT->isDependentType() ? Context.DependentTy
2962                                                    : OldAT->getDeducedType()));
2963         NewQType = Context.getCanonicalType(
2964             SubstAutoType(NewQType,
2965                           OldAT->isDependentType() ? Context.DependentTy
2966                                                    : OldAT->getDeducedType()));
2967       }
2968     }
2969 
2970     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2971     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2972     if (OldMethod && NewMethod) {
2973       // Preserve triviality.
2974       NewMethod->setTrivial(OldMethod->isTrivial());
2975 
2976       // MSVC allows explicit template specialization at class scope:
2977       // 2 CXXMethodDecls referring to the same function will be injected.
2978       // We don't want a redeclaration error.
2979       bool IsClassScopeExplicitSpecialization =
2980                               OldMethod->isFunctionTemplateSpecialization() &&
2981                               NewMethod->isFunctionTemplateSpecialization();
2982       bool isFriend = NewMethod->getFriendObjectKind();
2983 
2984       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2985           !IsClassScopeExplicitSpecialization) {
2986         //    -- Member function declarations with the same name and the
2987         //       same parameter types cannot be overloaded if any of them
2988         //       is a static member function declaration.
2989         if (OldMethod->isStatic() != NewMethod->isStatic()) {
2990           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2991           Diag(OldLocation, PrevDiag) << Old << Old->getType();
2992           return true;
2993         }
2994 
2995         // C++ [class.mem]p1:
2996         //   [...] A member shall not be declared twice in the
2997         //   member-specification, except that a nested class or member
2998         //   class template can be declared and then later defined.
2999         if (ActiveTemplateInstantiations.empty()) {
3000           unsigned NewDiag;
3001           if (isa<CXXConstructorDecl>(OldMethod))
3002             NewDiag = diag::err_constructor_redeclared;
3003           else if (isa<CXXDestructorDecl>(NewMethod))
3004             NewDiag = diag::err_destructor_redeclared;
3005           else if (isa<CXXConversionDecl>(NewMethod))
3006             NewDiag = diag::err_conv_function_redeclared;
3007           else
3008             NewDiag = diag::err_member_redeclared;
3009 
3010           Diag(New->getLocation(), NewDiag);
3011         } else {
3012           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3013             << New << New->getType();
3014         }
3015         Diag(OldLocation, PrevDiag) << Old << Old->getType();
3016         return true;
3017 
3018       // Complain if this is an explicit declaration of a special
3019       // member that was initially declared implicitly.
3020       //
3021       // As an exception, it's okay to befriend such methods in order
3022       // to permit the implicit constructor/destructor/operator calls.
3023       } else if (OldMethod->isImplicit()) {
3024         if (isFriend) {
3025           NewMethod->setImplicit();
3026         } else {
3027           Diag(NewMethod->getLocation(),
3028                diag::err_definition_of_implicitly_declared_member)
3029             << New << getSpecialMember(OldMethod);
3030           return true;
3031         }
3032       } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3033         Diag(NewMethod->getLocation(),
3034              diag::err_definition_of_explicitly_defaulted_member)
3035           << getSpecialMember(OldMethod);
3036         return true;
3037       }
3038     }
3039 
3040     // C++11 [dcl.attr.noreturn]p1:
3041     //   The first declaration of a function shall specify the noreturn
3042     //   attribute if any declaration of that function specifies the noreturn
3043     //   attribute.
3044     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
3045     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
3046       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
3047       Diag(Old->getFirstDecl()->getLocation(),
3048            diag::note_noreturn_missing_first_decl);
3049     }
3050 
3051     // C++11 [dcl.attr.depend]p2:
3052     //   The first declaration of a function shall specify the
3053     //   carries_dependency attribute for its declarator-id if any declaration
3054     //   of the function specifies the carries_dependency attribute.
3055     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3056     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3057       Diag(CDA->getLocation(),
3058            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3059       Diag(Old->getFirstDecl()->getLocation(),
3060            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3061     }
3062 
3063     // (C++98 8.3.5p3):
3064     //   All declarations for a function shall agree exactly in both the
3065     //   return type and the parameter-type-list.
3066     // We also want to respect all the extended bits except noreturn.
3067 
3068     // noreturn should now match unless the old type info didn't have it.
3069     QualType OldQTypeForComparison = OldQType;
3070     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3071       assert(OldQType == QualType(OldType, 0));
3072       const FunctionType *OldTypeForComparison
3073         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3074       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3075       assert(OldQTypeForComparison.isCanonical());
3076     }
3077 
3078     if (haveIncompatibleLanguageLinkages(Old, New)) {
3079       // As a special case, retain the language linkage from previous
3080       // declarations of a friend function as an extension.
3081       //
3082       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3083       // and is useful because there's otherwise no way to specify language
3084       // linkage within class scope.
3085       //
3086       // Check cautiously as the friend object kind isn't yet complete.
3087       if (New->getFriendObjectKind() != Decl::FOK_None) {
3088         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3089         Diag(OldLocation, PrevDiag);
3090       } else {
3091         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3092         Diag(OldLocation, PrevDiag);
3093         return true;
3094       }
3095     }
3096 
3097     if (OldQTypeForComparison == NewQType)
3098       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3099 
3100     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
3101         New->isLocalExternDecl()) {
3102       // It's OK if we couldn't merge types for a local function declaraton
3103       // if either the old or new type is dependent. We'll merge the types
3104       // when we instantiate the function.
3105       return false;
3106     }
3107 
3108     // Fall through for conflicting redeclarations and redefinitions.
3109   }
3110 
3111   // C: Function types need to be compatible, not identical. This handles
3112   // duplicate function decls like "void f(int); void f(enum X);" properly.
3113   if (!getLangOpts().CPlusPlus &&
3114       Context.typesAreCompatible(OldQType, NewQType)) {
3115     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3116     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3117     const FunctionProtoType *OldProto = nullptr;
3118     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3119         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3120       // The old declaration provided a function prototype, but the
3121       // new declaration does not. Merge in the prototype.
3122       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3123       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3124       NewQType =
3125           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3126                                   OldProto->getExtProtoInfo());
3127       New->setType(NewQType);
3128       New->setHasInheritedPrototype();
3129 
3130       // Synthesize parameters with the same types.
3131       SmallVector<ParmVarDecl*, 16> Params;
3132       for (const auto &ParamType : OldProto->param_types()) {
3133         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3134                                                  SourceLocation(), nullptr,
3135                                                  ParamType, /*TInfo=*/nullptr,
3136                                                  SC_None, nullptr);
3137         Param->setScopeInfo(0, Params.size());
3138         Param->setImplicit();
3139         Params.push_back(Param);
3140       }
3141 
3142       New->setParams(Params);
3143     }
3144 
3145     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3146   }
3147 
3148   // GNU C permits a K&R definition to follow a prototype declaration
3149   // if the declared types of the parameters in the K&R definition
3150   // match the types in the prototype declaration, even when the
3151   // promoted types of the parameters from the K&R definition differ
3152   // from the types in the prototype. GCC then keeps the types from
3153   // the prototype.
3154   //
3155   // If a variadic prototype is followed by a non-variadic K&R definition,
3156   // the K&R definition becomes variadic.  This is sort of an edge case, but
3157   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3158   // C99 6.9.1p8.
3159   if (!getLangOpts().CPlusPlus &&
3160       Old->hasPrototype() && !New->hasPrototype() &&
3161       New->getType()->getAs<FunctionProtoType>() &&
3162       Old->getNumParams() == New->getNumParams()) {
3163     SmallVector<QualType, 16> ArgTypes;
3164     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3165     const FunctionProtoType *OldProto
3166       = Old->getType()->getAs<FunctionProtoType>();
3167     const FunctionProtoType *NewProto
3168       = New->getType()->getAs<FunctionProtoType>();
3169 
3170     // Determine whether this is the GNU C extension.
3171     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3172                                                NewProto->getReturnType());
3173     bool LooseCompatible = !MergedReturn.isNull();
3174     for (unsigned Idx = 0, End = Old->getNumParams();
3175          LooseCompatible && Idx != End; ++Idx) {
3176       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3177       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3178       if (Context.typesAreCompatible(OldParm->getType(),
3179                                      NewProto->getParamType(Idx))) {
3180         ArgTypes.push_back(NewParm->getType());
3181       } else if (Context.typesAreCompatible(OldParm->getType(),
3182                                             NewParm->getType(),
3183                                             /*CompareUnqualified=*/true)) {
3184         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3185                                            NewProto->getParamType(Idx) };
3186         Warnings.push_back(Warn);
3187         ArgTypes.push_back(NewParm->getType());
3188       } else
3189         LooseCompatible = false;
3190     }
3191 
3192     if (LooseCompatible) {
3193       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3194         Diag(Warnings[Warn].NewParm->getLocation(),
3195              diag::ext_param_promoted_not_compatible_with_prototype)
3196           << Warnings[Warn].PromotedType
3197           << Warnings[Warn].OldParm->getType();
3198         if (Warnings[Warn].OldParm->getLocation().isValid())
3199           Diag(Warnings[Warn].OldParm->getLocation(),
3200                diag::note_previous_declaration);
3201       }
3202 
3203       if (MergeTypeWithOld)
3204         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3205                                              OldProto->getExtProtoInfo()));
3206       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3207     }
3208 
3209     // Fall through to diagnose conflicting types.
3210   }
3211 
3212   // A function that has already been declared has been redeclared or
3213   // defined with a different type; show an appropriate diagnostic.
3214 
3215   // If the previous declaration was an implicitly-generated builtin
3216   // declaration, then at the very least we should use a specialized note.
3217   unsigned BuiltinID;
3218   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3219     // If it's actually a library-defined builtin function like 'malloc'
3220     // or 'printf', just warn about the incompatible redeclaration.
3221     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3222       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3223       Diag(OldLocation, diag::note_previous_builtin_declaration)
3224         << Old << Old->getType();
3225 
3226       // If this is a global redeclaration, just forget hereafter
3227       // about the "builtin-ness" of the function.
3228       //
3229       // Doing this for local extern declarations is problematic.  If
3230       // the builtin declaration remains visible, a second invalid
3231       // local declaration will produce a hard error; if it doesn't
3232       // remain visible, a single bogus local redeclaration (which is
3233       // actually only a warning) could break all the downstream code.
3234       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3235         New->getIdentifier()->revertBuiltin();
3236 
3237       return false;
3238     }
3239 
3240     PrevDiag = diag::note_previous_builtin_declaration;
3241   }
3242 
3243   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3244   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3245   return true;
3246 }
3247 
3248 /// \brief Completes the merge of two function declarations that are
3249 /// known to be compatible.
3250 ///
3251 /// This routine handles the merging of attributes and other
3252 /// properties of function declarations from the old declaration to
3253 /// the new declaration, once we know that New is in fact a
3254 /// redeclaration of Old.
3255 ///
3256 /// \returns false
3257 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3258                                         Scope *S, bool MergeTypeWithOld) {
3259   // Merge the attributes
3260   mergeDeclAttributes(New, Old);
3261 
3262   // Merge "pure" flag.
3263   if (Old->isPure())
3264     New->setPure();
3265 
3266   // Merge "used" flag.
3267   if (Old->getMostRecentDecl()->isUsed(false))
3268     New->setIsUsed();
3269 
3270   // Merge attributes from the parameters.  These can mismatch with K&R
3271   // declarations.
3272   if (New->getNumParams() == Old->getNumParams())
3273       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3274         ParmVarDecl *NewParam = New->getParamDecl(i);
3275         ParmVarDecl *OldParam = Old->getParamDecl(i);
3276         mergeParamDeclAttributes(NewParam, OldParam, *this);
3277         mergeParamDeclTypes(NewParam, OldParam, *this);
3278       }
3279 
3280   if (getLangOpts().CPlusPlus)
3281     return MergeCXXFunctionDecl(New, Old, S);
3282 
3283   // Merge the function types so the we get the composite types for the return
3284   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3285   // was visible.
3286   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3287   if (!Merged.isNull() && MergeTypeWithOld)
3288     New->setType(Merged);
3289 
3290   return false;
3291 }
3292 
3293 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3294                                 ObjCMethodDecl *oldMethod) {
3295   // Merge the attributes, including deprecated/unavailable
3296   AvailabilityMergeKind MergeKind =
3297     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3298       ? AMK_ProtocolImplementation
3299       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3300                                                        : AMK_Override;
3301 
3302   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3303 
3304   // Merge attributes from the parameters.
3305   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3306                                        oe = oldMethod->param_end();
3307   for (ObjCMethodDecl::param_iterator
3308          ni = newMethod->param_begin(), ne = newMethod->param_end();
3309        ni != ne && oi != oe; ++ni, ++oi)
3310     mergeParamDeclAttributes(*ni, *oi, *this);
3311 
3312   CheckObjCMethodOverride(newMethod, oldMethod);
3313 }
3314 
3315 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
3316   assert(!S.Context.hasSameType(New->getType(), Old->getType()));
3317 
3318   S.Diag(New->getLocation(), New->isThisDeclarationADefinition()
3319          ? diag::err_redefinition_different_type
3320          : diag::err_redeclaration_different_type)
3321     << New->getDeclName() << New->getType() << Old->getType();
3322 
3323   diag::kind PrevDiag;
3324   SourceLocation OldLocation;
3325   std::tie(PrevDiag, OldLocation)
3326     = getNoteDiagForInvalidRedeclaration(Old, New);
3327   S.Diag(OldLocation, PrevDiag);
3328   New->setInvalidDecl();
3329 }
3330 
3331 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3332 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3333 /// emitting diagnostics as appropriate.
3334 ///
3335 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3336 /// to here in AddInitializerToDecl. We can't check them before the initializer
3337 /// is attached.
3338 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3339                              bool MergeTypeWithOld) {
3340   if (New->isInvalidDecl() || Old->isInvalidDecl())
3341     return;
3342 
3343   QualType MergedT;
3344   if (getLangOpts().CPlusPlus) {
3345     if (New->getType()->isUndeducedType()) {
3346       // We don't know what the new type is until the initializer is attached.
3347       return;
3348     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3349       // These could still be something that needs exception specs checked.
3350       return MergeVarDeclExceptionSpecs(New, Old);
3351     }
3352     // C++ [basic.link]p10:
3353     //   [...] the types specified by all declarations referring to a given
3354     //   object or function shall be identical, except that declarations for an
3355     //   array object can specify array types that differ by the presence or
3356     //   absence of a major array bound (8.3.4).
3357     else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
3358       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3359       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3360 
3361       // We are merging a variable declaration New into Old. If it has an array
3362       // bound, and that bound differs from Old's bound, we should diagnose the
3363       // mismatch.
3364       if (!NewArray->isIncompleteArrayType()) {
3365         for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
3366              PrevVD = PrevVD->getPreviousDecl()) {
3367           const ArrayType *PrevVDTy = Context.getAsArrayType(PrevVD->getType());
3368           if (PrevVDTy->isIncompleteArrayType())
3369             continue;
3370 
3371           if (!Context.hasSameType(NewArray, PrevVDTy))
3372             return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
3373         }
3374       }
3375 
3376       if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
3377         if (Context.hasSameType(OldArray->getElementType(),
3378                                 NewArray->getElementType()))
3379           MergedT = New->getType();
3380       }
3381       // FIXME: Check visibility. New is hidden but has a complete type. If New
3382       // has no array bound, it should not inherit one from Old, if Old is not
3383       // visible.
3384       else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
3385         if (Context.hasSameType(OldArray->getElementType(),
3386                                 NewArray->getElementType()))
3387           MergedT = Old->getType();
3388       }
3389     }
3390     else if (New->getType()->isObjCObjectPointerType() &&
3391                Old->getType()->isObjCObjectPointerType()) {
3392       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3393                                               Old->getType());
3394     }
3395   } else {
3396     // C 6.2.7p2:
3397     //   All declarations that refer to the same object or function shall have
3398     //   compatible type.
3399     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3400   }
3401   if (MergedT.isNull()) {
3402     // It's OK if we couldn't merge types if either type is dependent, for a
3403     // block-scope variable. In other cases (static data members of class
3404     // templates, variable templates, ...), we require the types to be
3405     // equivalent.
3406     // FIXME: The C++ standard doesn't say anything about this.
3407     if ((New->getType()->isDependentType() ||
3408          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3409       // If the old type was dependent, we can't merge with it, so the new type
3410       // becomes dependent for now. We'll reproduce the original type when we
3411       // instantiate the TypeSourceInfo for the variable.
3412       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3413         New->setType(Context.DependentTy);
3414       return;
3415     }
3416     return diagnoseVarDeclTypeMismatch(*this, New, Old);
3417   }
3418 
3419   // Don't actually update the type on the new declaration if the old
3420   // declaration was an extern declaration in a different scope.
3421   if (MergeTypeWithOld)
3422     New->setType(MergedT);
3423 }
3424 
3425 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3426                                   LookupResult &Previous) {
3427   // C11 6.2.7p4:
3428   //   For an identifier with internal or external linkage declared
3429   //   in a scope in which a prior declaration of that identifier is
3430   //   visible, if the prior declaration specifies internal or
3431   //   external linkage, the type of the identifier at the later
3432   //   declaration becomes the composite type.
3433   //
3434   // If the variable isn't visible, we do not merge with its type.
3435   if (Previous.isShadowed())
3436     return false;
3437 
3438   if (S.getLangOpts().CPlusPlus) {
3439     // C++11 [dcl.array]p3:
3440     //   If there is a preceding declaration of the entity in the same
3441     //   scope in which the bound was specified, an omitted array bound
3442     //   is taken to be the same as in that earlier declaration.
3443     return NewVD->isPreviousDeclInSameBlockScope() ||
3444            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3445             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3446   } else {
3447     // If the old declaration was function-local, don't merge with its
3448     // type unless we're in the same function.
3449     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3450            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3451   }
3452 }
3453 
3454 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3455 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3456 /// situation, merging decls or emitting diagnostics as appropriate.
3457 ///
3458 /// Tentative definition rules (C99 6.9.2p2) are checked by
3459 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3460 /// definitions here, since the initializer hasn't been attached.
3461 ///
3462 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3463   // If the new decl is already invalid, don't do any other checking.
3464   if (New->isInvalidDecl())
3465     return;
3466 
3467   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3468     return;
3469 
3470   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3471 
3472   // Verify the old decl was also a variable or variable template.
3473   VarDecl *Old = nullptr;
3474   VarTemplateDecl *OldTemplate = nullptr;
3475   if (Previous.isSingleResult()) {
3476     if (NewTemplate) {
3477       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3478       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3479 
3480       if (auto *Shadow =
3481               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3482         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3483           return New->setInvalidDecl();
3484     } else {
3485       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3486 
3487       if (auto *Shadow =
3488               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3489         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3490           return New->setInvalidDecl();
3491     }
3492   }
3493   if (!Old) {
3494     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3495       << New->getDeclName();
3496     Diag(Previous.getRepresentativeDecl()->getLocation(),
3497          diag::note_previous_definition);
3498     return New->setInvalidDecl();
3499   }
3500 
3501   // Ensure the template parameters are compatible.
3502   if (NewTemplate &&
3503       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3504                                       OldTemplate->getTemplateParameters(),
3505                                       /*Complain=*/true, TPL_TemplateMatch))
3506     return New->setInvalidDecl();
3507 
3508   // C++ [class.mem]p1:
3509   //   A member shall not be declared twice in the member-specification [...]
3510   //
3511   // Here, we need only consider static data members.
3512   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3513     Diag(New->getLocation(), diag::err_duplicate_member)
3514       << New->getIdentifier();
3515     Diag(Old->getLocation(), diag::note_previous_declaration);
3516     New->setInvalidDecl();
3517   }
3518 
3519   mergeDeclAttributes(New, Old);
3520   // Warn if an already-declared variable is made a weak_import in a subsequent
3521   // declaration
3522   if (New->hasAttr<WeakImportAttr>() &&
3523       Old->getStorageClass() == SC_None &&
3524       !Old->hasAttr<WeakImportAttr>()) {
3525     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3526     Diag(Old->getLocation(), diag::note_previous_definition);
3527     // Remove weak_import attribute on new declaration.
3528     New->dropAttr<WeakImportAttr>();
3529   }
3530 
3531   if (New->hasAttr<InternalLinkageAttr>() &&
3532       !Old->hasAttr<InternalLinkageAttr>()) {
3533     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3534         << New->getDeclName();
3535     Diag(Old->getLocation(), diag::note_previous_definition);
3536     New->dropAttr<InternalLinkageAttr>();
3537   }
3538 
3539   // Merge the types.
3540   VarDecl *MostRecent = Old->getMostRecentDecl();
3541   if (MostRecent != Old) {
3542     MergeVarDeclTypes(New, MostRecent,
3543                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3544     if (New->isInvalidDecl())
3545       return;
3546   }
3547 
3548   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3549   if (New->isInvalidDecl())
3550     return;
3551 
3552   diag::kind PrevDiag;
3553   SourceLocation OldLocation;
3554   std::tie(PrevDiag, OldLocation) =
3555       getNoteDiagForInvalidRedeclaration(Old, New);
3556 
3557   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3558   if (New->getStorageClass() == SC_Static &&
3559       !New->isStaticDataMember() &&
3560       Old->hasExternalFormalLinkage()) {
3561     if (getLangOpts().MicrosoftExt) {
3562       Diag(New->getLocation(), diag::ext_static_non_static)
3563           << New->getDeclName();
3564       Diag(OldLocation, PrevDiag);
3565     } else {
3566       Diag(New->getLocation(), diag::err_static_non_static)
3567           << New->getDeclName();
3568       Diag(OldLocation, PrevDiag);
3569       return New->setInvalidDecl();
3570     }
3571   }
3572   // C99 6.2.2p4:
3573   //   For an identifier declared with the storage-class specifier
3574   //   extern in a scope in which a prior declaration of that
3575   //   identifier is visible,23) if the prior declaration specifies
3576   //   internal or external linkage, the linkage of the identifier at
3577   //   the later declaration is the same as the linkage specified at
3578   //   the prior declaration. If no prior declaration is visible, or
3579   //   if the prior declaration specifies no linkage, then the
3580   //   identifier has external linkage.
3581   if (New->hasExternalStorage() && Old->hasLinkage())
3582     /* Okay */;
3583   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3584            !New->isStaticDataMember() &&
3585            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3586     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3587     Diag(OldLocation, PrevDiag);
3588     return New->setInvalidDecl();
3589   }
3590 
3591   // Check if extern is followed by non-extern and vice-versa.
3592   if (New->hasExternalStorage() &&
3593       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3594     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3595     Diag(OldLocation, PrevDiag);
3596     return New->setInvalidDecl();
3597   }
3598   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3599       !New->hasExternalStorage()) {
3600     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3601     Diag(OldLocation, PrevDiag);
3602     return New->setInvalidDecl();
3603   }
3604 
3605   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3606 
3607   // FIXME: The test for external storage here seems wrong? We still
3608   // need to check for mismatches.
3609   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3610       // Don't complain about out-of-line definitions of static members.
3611       !(Old->getLexicalDeclContext()->isRecord() &&
3612         !New->getLexicalDeclContext()->isRecord())) {
3613     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3614     Diag(OldLocation, PrevDiag);
3615     return New->setInvalidDecl();
3616   }
3617 
3618   if (New->getTLSKind() != Old->getTLSKind()) {
3619     if (!Old->getTLSKind()) {
3620       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3621       Diag(OldLocation, PrevDiag);
3622     } else if (!New->getTLSKind()) {
3623       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3624       Diag(OldLocation, PrevDiag);
3625     } else {
3626       // Do not allow redeclaration to change the variable between requiring
3627       // static and dynamic initialization.
3628       // FIXME: GCC allows this, but uses the TLS keyword on the first
3629       // declaration to determine the kind. Do we need to be compatible here?
3630       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3631         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3632       Diag(OldLocation, PrevDiag);
3633     }
3634   }
3635 
3636   // C++ doesn't have tentative definitions, so go right ahead and check here.
3637   VarDecl *Def;
3638   if (getLangOpts().CPlusPlus &&
3639       New->isThisDeclarationADefinition() == VarDecl::Definition &&
3640       (Def = Old->getDefinition())) {
3641     NamedDecl *Hidden = nullptr;
3642     if (!hasVisibleDefinition(Def, &Hidden) &&
3643         (New->getFormalLinkage() == InternalLinkage ||
3644          New->getDescribedVarTemplate() ||
3645          New->getNumTemplateParameterLists() ||
3646          New->getDeclContext()->isDependentContext())) {
3647       // The previous definition is hidden, and multiple definitions are
3648       // permitted (in separate TUs). Form another definition of it.
3649     } else {
3650       Diag(New->getLocation(), diag::err_redefinition) << New;
3651       Diag(Def->getLocation(), diag::note_previous_definition);
3652       New->setInvalidDecl();
3653       return;
3654     }
3655   }
3656 
3657   if (haveIncompatibleLanguageLinkages(Old, New)) {
3658     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3659     Diag(OldLocation, PrevDiag);
3660     New->setInvalidDecl();
3661     return;
3662   }
3663 
3664   // Merge "used" flag.
3665   if (Old->getMostRecentDecl()->isUsed(false))
3666     New->setIsUsed();
3667 
3668   // Keep a chain of previous declarations.
3669   New->setPreviousDecl(Old);
3670   if (NewTemplate)
3671     NewTemplate->setPreviousDecl(OldTemplate);
3672 
3673   // Inherit access appropriately.
3674   New->setAccess(Old->getAccess());
3675   if (NewTemplate)
3676     NewTemplate->setAccess(New->getAccess());
3677 }
3678 
3679 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3680 /// no declarator (e.g. "struct foo;") is parsed.
3681 Decl *
3682 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3683                                  RecordDecl *&AnonRecord) {
3684   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
3685                                     AnonRecord);
3686 }
3687 
3688 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3689 // disambiguate entities defined in different scopes.
3690 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3691 // compatibility.
3692 // We will pick our mangling number depending on which version of MSVC is being
3693 // targeted.
3694 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3695   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3696              ? S->getMSCurManglingNumber()
3697              : S->getMSLastManglingNumber();
3698 }
3699 
3700 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3701   if (!Context.getLangOpts().CPlusPlus)
3702     return;
3703 
3704   if (isa<CXXRecordDecl>(Tag->getParent())) {
3705     // If this tag is the direct child of a class, number it if
3706     // it is anonymous.
3707     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3708       return;
3709     MangleNumberingContext &MCtx =
3710         Context.getManglingNumberContext(Tag->getParent());
3711     Context.setManglingNumber(
3712         Tag, MCtx.getManglingNumber(
3713                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3714     return;
3715   }
3716 
3717   // If this tag isn't a direct child of a class, number it if it is local.
3718   Decl *ManglingContextDecl;
3719   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3720           Tag->getDeclContext(), ManglingContextDecl)) {
3721     Context.setManglingNumber(
3722         Tag, MCtx->getManglingNumber(
3723                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3724   }
3725 }
3726 
3727 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3728                                         TypedefNameDecl *NewTD) {
3729   if (TagFromDeclSpec->isInvalidDecl())
3730     return;
3731 
3732   // Do nothing if the tag already has a name for linkage purposes.
3733   if (TagFromDeclSpec->hasNameForLinkage())
3734     return;
3735 
3736   // A well-formed anonymous tag must always be a TUK_Definition.
3737   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3738 
3739   // The type must match the tag exactly;  no qualifiers allowed.
3740   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3741                            Context.getTagDeclType(TagFromDeclSpec))) {
3742     if (getLangOpts().CPlusPlus)
3743       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3744     return;
3745   }
3746 
3747   // If we've already computed linkage for the anonymous tag, then
3748   // adding a typedef name for the anonymous decl can change that
3749   // linkage, which might be a serious problem.  Diagnose this as
3750   // unsupported and ignore the typedef name.  TODO: we should
3751   // pursue this as a language defect and establish a formal rule
3752   // for how to handle it.
3753   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3754     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3755 
3756     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3757     tagLoc = getLocForEndOfToken(tagLoc);
3758 
3759     llvm::SmallString<40> textToInsert;
3760     textToInsert += ' ';
3761     textToInsert += NewTD->getIdentifier()->getName();
3762     Diag(tagLoc, diag::note_typedef_changes_linkage)
3763         << FixItHint::CreateInsertion(tagLoc, textToInsert);
3764     return;
3765   }
3766 
3767   // Otherwise, set this is the anon-decl typedef for the tag.
3768   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3769 }
3770 
3771 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3772   switch (T) {
3773   case DeclSpec::TST_class:
3774     return 0;
3775   case DeclSpec::TST_struct:
3776     return 1;
3777   case DeclSpec::TST_interface:
3778     return 2;
3779   case DeclSpec::TST_union:
3780     return 3;
3781   case DeclSpec::TST_enum:
3782     return 4;
3783   default:
3784     llvm_unreachable("unexpected type specifier");
3785   }
3786 }
3787 
3788 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3789 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3790 /// parameters to cope with template friend declarations.
3791 Decl *
3792 Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS,
3793                                  MultiTemplateParamsArg TemplateParams,
3794                                  bool IsExplicitInstantiation,
3795                                  RecordDecl *&AnonRecord) {
3796   Decl *TagD = nullptr;
3797   TagDecl *Tag = nullptr;
3798   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3799       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3800       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3801       DS.getTypeSpecType() == DeclSpec::TST_union ||
3802       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3803     TagD = DS.getRepAsDecl();
3804 
3805     if (!TagD) // We probably had an error
3806       return nullptr;
3807 
3808     // Note that the above type specs guarantee that the
3809     // type rep is a Decl, whereas in many of the others
3810     // it's a Type.
3811     if (isa<TagDecl>(TagD))
3812       Tag = cast<TagDecl>(TagD);
3813     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3814       Tag = CTD->getTemplatedDecl();
3815   }
3816 
3817   if (Tag) {
3818     handleTagNumbering(Tag, S);
3819     Tag->setFreeStanding();
3820     if (Tag->isInvalidDecl())
3821       return Tag;
3822   }
3823 
3824   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3825     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3826     // or incomplete types shall not be restrict-qualified."
3827     if (TypeQuals & DeclSpec::TQ_restrict)
3828       Diag(DS.getRestrictSpecLoc(),
3829            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3830            << DS.getSourceRange();
3831   }
3832 
3833   if (DS.isConstexprSpecified()) {
3834     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3835     // and definitions of functions and variables.
3836     if (Tag)
3837       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3838           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3839     else
3840       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3841     // Don't emit warnings after this error.
3842     return TagD;
3843   }
3844 
3845   if (DS.isConceptSpecified()) {
3846     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3847     // either a function concept and its definition or a variable concept and
3848     // its initializer.
3849     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3850     return TagD;
3851   }
3852 
3853   DiagnoseFunctionSpecifiers(DS);
3854 
3855   if (DS.isFriendSpecified()) {
3856     // If we're dealing with a decl but not a TagDecl, assume that
3857     // whatever routines created it handled the friendship aspect.
3858     if (TagD && !Tag)
3859       return nullptr;
3860     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3861   }
3862 
3863   const CXXScopeSpec &SS = DS.getTypeSpecScope();
3864   bool IsExplicitSpecialization =
3865     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3866   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3867       !IsExplicitInstantiation && !IsExplicitSpecialization &&
3868       !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
3869     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3870     // nested-name-specifier unless it is an explicit instantiation
3871     // or an explicit specialization.
3872     //
3873     // FIXME: We allow class template partial specializations here too, per the
3874     // obvious intent of DR1819.
3875     //
3876     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3877     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3878         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
3879     return nullptr;
3880   }
3881 
3882   // Track whether this decl-specifier declares anything.
3883   bool DeclaresAnything = true;
3884 
3885   // Handle anonymous struct definitions.
3886   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3887     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3888         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3889       if (getLangOpts().CPlusPlus ||
3890           Record->getDeclContext()->isRecord()) {
3891         // If CurContext is a DeclContext that can contain statements,
3892         // RecursiveASTVisitor won't visit the decls that
3893         // BuildAnonymousStructOrUnion() will put into CurContext.
3894         // Also store them here so that they can be part of the
3895         // DeclStmt that gets created in this case.
3896         // FIXME: Also return the IndirectFieldDecls created by
3897         // BuildAnonymousStructOr union, for the same reason?
3898         if (CurContext->isFunctionOrMethod())
3899           AnonRecord = Record;
3900         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3901                                            Context.getPrintingPolicy());
3902       }
3903 
3904       DeclaresAnything = false;
3905     }
3906   }
3907 
3908   // C11 6.7.2.1p2:
3909   //   A struct-declaration that does not declare an anonymous structure or
3910   //   anonymous union shall contain a struct-declarator-list.
3911   //
3912   // This rule also existed in C89 and C99; the grammar for struct-declaration
3913   // did not permit a struct-declaration without a struct-declarator-list.
3914   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3915       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3916     // Check for Microsoft C extension: anonymous struct/union member.
3917     // Handle 2 kinds of anonymous struct/union:
3918     //   struct STRUCT;
3919     //   union UNION;
3920     // and
3921     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3922     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
3923     if ((Tag && Tag->getDeclName()) ||
3924         DS.getTypeSpecType() == DeclSpec::TST_typename) {
3925       RecordDecl *Record = nullptr;
3926       if (Tag)
3927         Record = dyn_cast<RecordDecl>(Tag);
3928       else if (const RecordType *RT =
3929                    DS.getRepAsType().get()->getAsStructureType())
3930         Record = RT->getDecl();
3931       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3932         Record = UT->getDecl();
3933 
3934       if (Record && getLangOpts().MicrosoftExt) {
3935         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3936           << Record->isUnion() << DS.getSourceRange();
3937         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3938       }
3939 
3940       DeclaresAnything = false;
3941     }
3942   }
3943 
3944   // Skip all the checks below if we have a type error.
3945   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3946       (TagD && TagD->isInvalidDecl()))
3947     return TagD;
3948 
3949   if (getLangOpts().CPlusPlus &&
3950       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3951     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3952       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3953           !Enum->getIdentifier() && !Enum->isInvalidDecl())
3954         DeclaresAnything = false;
3955 
3956   if (!DS.isMissingDeclaratorOk()) {
3957     // Customize diagnostic for a typedef missing a name.
3958     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3959       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3960         << DS.getSourceRange();
3961     else
3962       DeclaresAnything = false;
3963   }
3964 
3965   if (DS.isModulePrivateSpecified() &&
3966       Tag && Tag->getDeclContext()->isFunctionOrMethod())
3967     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3968       << Tag->getTagKind()
3969       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3970 
3971   ActOnDocumentableDecl(TagD);
3972 
3973   // C 6.7/2:
3974   //   A declaration [...] shall declare at least a declarator [...], a tag,
3975   //   or the members of an enumeration.
3976   // C++ [dcl.dcl]p3:
3977   //   [If there are no declarators], and except for the declaration of an
3978   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
3979   //   names into the program, or shall redeclare a name introduced by a
3980   //   previous declaration.
3981   if (!DeclaresAnything) {
3982     // In C, we allow this as a (popular) extension / bug. Don't bother
3983     // producing further diagnostics for redundant qualifiers after this.
3984     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3985     return TagD;
3986   }
3987 
3988   // C++ [dcl.stc]p1:
3989   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3990   //   init-declarator-list of the declaration shall not be empty.
3991   // C++ [dcl.fct.spec]p1:
3992   //   If a cv-qualifier appears in a decl-specifier-seq, the
3993   //   init-declarator-list of the declaration shall not be empty.
3994   //
3995   // Spurious qualifiers here appear to be valid in C.
3996   unsigned DiagID = diag::warn_standalone_specifier;
3997   if (getLangOpts().CPlusPlus)
3998     DiagID = diag::ext_standalone_specifier;
3999 
4000   // Note that a linkage-specification sets a storage class, but
4001   // 'extern "C" struct foo;' is actually valid and not theoretically
4002   // useless.
4003   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4004     if (SCS == DeclSpec::SCS_mutable)
4005       // Since mutable is not a viable storage class specifier in C, there is
4006       // no reason to treat it as an extension. Instead, diagnose as an error.
4007       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
4008     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
4009       Diag(DS.getStorageClassSpecLoc(), DiagID)
4010         << DeclSpec::getSpecifierName(SCS);
4011   }
4012 
4013   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
4014     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
4015       << DeclSpec::getSpecifierName(TSCS);
4016   if (DS.getTypeQualifiers()) {
4017     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4018       Diag(DS.getConstSpecLoc(), DiagID) << "const";
4019     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4020       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
4021     // Restrict is covered above.
4022     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4023       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
4024     if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4025       Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
4026   }
4027 
4028   // Warn about ignored type attributes, for example:
4029   // __attribute__((aligned)) struct A;
4030   // Attributes should be placed after tag to apply to type declaration.
4031   if (!DS.getAttributes().empty()) {
4032     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
4033     if (TypeSpecType == DeclSpec::TST_class ||
4034         TypeSpecType == DeclSpec::TST_struct ||
4035         TypeSpecType == DeclSpec::TST_interface ||
4036         TypeSpecType == DeclSpec::TST_union ||
4037         TypeSpecType == DeclSpec::TST_enum) {
4038       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
4039            attrs = attrs->getNext())
4040         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
4041             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
4042     }
4043   }
4044 
4045   return TagD;
4046 }
4047 
4048 /// We are trying to inject an anonymous member into the given scope;
4049 /// check if there's an existing declaration that can't be overloaded.
4050 ///
4051 /// \return true if this is a forbidden redeclaration
4052 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
4053                                          Scope *S,
4054                                          DeclContext *Owner,
4055                                          DeclarationName Name,
4056                                          SourceLocation NameLoc,
4057                                          bool IsUnion) {
4058   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
4059                  Sema::ForRedeclaration);
4060   if (!SemaRef.LookupName(R, S)) return false;
4061 
4062   // Pick a representative declaration.
4063   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
4064   assert(PrevDecl && "Expected a non-null Decl");
4065 
4066   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
4067     return false;
4068 
4069   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
4070     << IsUnion << Name;
4071   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
4072 
4073   return true;
4074 }
4075 
4076 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
4077 /// anonymous struct or union AnonRecord into the owning context Owner
4078 /// and scope S. This routine will be invoked just after we realize
4079 /// that an unnamed union or struct is actually an anonymous union or
4080 /// struct, e.g.,
4081 ///
4082 /// @code
4083 /// union {
4084 ///   int i;
4085 ///   float f;
4086 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
4087 ///    // f into the surrounding scope.x
4088 /// @endcode
4089 ///
4090 /// This routine is recursive, injecting the names of nested anonymous
4091 /// structs/unions into the owning context and scope as well.
4092 static bool
4093 InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner,
4094                                     RecordDecl *AnonRecord, AccessSpecifier AS,
4095                                     SmallVectorImpl<NamedDecl *> &Chaining) {
4096   bool Invalid = false;
4097 
4098   // Look every FieldDecl and IndirectFieldDecl with a name.
4099   for (auto *D : AnonRecord->decls()) {
4100     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
4101         cast<NamedDecl>(D)->getDeclName()) {
4102       ValueDecl *VD = cast<ValueDecl>(D);
4103       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
4104                                        VD->getLocation(),
4105                                        AnonRecord->isUnion())) {
4106         // C++ [class.union]p2:
4107         //   The names of the members of an anonymous union shall be
4108         //   distinct from the names of any other entity in the
4109         //   scope in which the anonymous union is declared.
4110         Invalid = true;
4111       } else {
4112         // C++ [class.union]p2:
4113         //   For the purpose of name lookup, after the anonymous union
4114         //   definition, the members of the anonymous union are
4115         //   considered to have been defined in the scope in which the
4116         //   anonymous union is declared.
4117         unsigned OldChainingSize = Chaining.size();
4118         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
4119           Chaining.append(IF->chain_begin(), IF->chain_end());
4120         else
4121           Chaining.push_back(VD);
4122 
4123         assert(Chaining.size() >= 2);
4124         NamedDecl **NamedChain =
4125           new (SemaRef.Context)NamedDecl*[Chaining.size()];
4126         for (unsigned i = 0; i < Chaining.size(); i++)
4127           NamedChain[i] = Chaining[i];
4128 
4129         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
4130             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
4131             VD->getType(), NamedChain, Chaining.size());
4132 
4133         for (const auto *Attr : VD->attrs())
4134           IndirectField->addAttr(Attr->clone(SemaRef.Context));
4135 
4136         IndirectField->setAccess(AS);
4137         IndirectField->setImplicit();
4138         SemaRef.PushOnScopeChains(IndirectField, S);
4139 
4140         // That includes picking up the appropriate access specifier.
4141         if (AS != AS_none) IndirectField->setAccess(AS);
4142 
4143         Chaining.resize(OldChainingSize);
4144       }
4145     }
4146   }
4147 
4148   return Invalid;
4149 }
4150 
4151 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4152 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4153 /// illegal input values are mapped to SC_None.
4154 static StorageClass
4155 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4156   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4157   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4158          "Parser allowed 'typedef' as storage class VarDecl.");
4159   switch (StorageClassSpec) {
4160   case DeclSpec::SCS_unspecified:    return SC_None;
4161   case DeclSpec::SCS_extern:
4162     if (DS.isExternInLinkageSpec())
4163       return SC_None;
4164     return SC_Extern;
4165   case DeclSpec::SCS_static:         return SC_Static;
4166   case DeclSpec::SCS_auto:           return SC_Auto;
4167   case DeclSpec::SCS_register:       return SC_Register;
4168   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4169     // Illegal SCSs map to None: error reporting is up to the caller.
4170   case DeclSpec::SCS_mutable:        // Fall through.
4171   case DeclSpec::SCS_typedef:        return SC_None;
4172   }
4173   llvm_unreachable("unknown storage class specifier");
4174 }
4175 
4176 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4177   assert(Record->hasInClassInitializer());
4178 
4179   for (const auto *I : Record->decls()) {
4180     const auto *FD = dyn_cast<FieldDecl>(I);
4181     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4182       FD = IFD->getAnonField();
4183     if (FD && FD->hasInClassInitializer())
4184       return FD->getLocation();
4185   }
4186 
4187   llvm_unreachable("couldn't find in-class initializer");
4188 }
4189 
4190 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4191                                       SourceLocation DefaultInitLoc) {
4192   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4193     return;
4194 
4195   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4196   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4197 }
4198 
4199 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4200                                       CXXRecordDecl *AnonUnion) {
4201   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4202     return;
4203 
4204   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4205 }
4206 
4207 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4208 /// anonymous structure or union. Anonymous unions are a C++ feature
4209 /// (C++ [class.union]) and a C11 feature; anonymous structures
4210 /// are a C11 feature and GNU C++ extension.
4211 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4212                                         AccessSpecifier AS,
4213                                         RecordDecl *Record,
4214                                         const PrintingPolicy &Policy) {
4215   DeclContext *Owner = Record->getDeclContext();
4216 
4217   // Diagnose whether this anonymous struct/union is an extension.
4218   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4219     Diag(Record->getLocation(), diag::ext_anonymous_union);
4220   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4221     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4222   else if (!Record->isUnion() && !getLangOpts().C11)
4223     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4224 
4225   // C and C++ require different kinds of checks for anonymous
4226   // structs/unions.
4227   bool Invalid = false;
4228   if (getLangOpts().CPlusPlus) {
4229     const char *PrevSpec = nullptr;
4230     unsigned DiagID;
4231     if (Record->isUnion()) {
4232       // C++ [class.union]p6:
4233       //   Anonymous unions declared in a named namespace or in the
4234       //   global namespace shall be declared static.
4235       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4236           (isa<TranslationUnitDecl>(Owner) ||
4237            (isa<NamespaceDecl>(Owner) &&
4238             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4239         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4240           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4241 
4242         // Recover by adding 'static'.
4243         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4244                                PrevSpec, DiagID, Policy);
4245       }
4246       // C++ [class.union]p6:
4247       //   A storage class is not allowed in a declaration of an
4248       //   anonymous union in a class scope.
4249       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4250                isa<RecordDecl>(Owner)) {
4251         Diag(DS.getStorageClassSpecLoc(),
4252              diag::err_anonymous_union_with_storage_spec)
4253           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4254 
4255         // Recover by removing the storage specifier.
4256         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4257                                SourceLocation(),
4258                                PrevSpec, DiagID, Context.getPrintingPolicy());
4259       }
4260     }
4261 
4262     // Ignore const/volatile/restrict qualifiers.
4263     if (DS.getTypeQualifiers()) {
4264       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4265         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4266           << Record->isUnion() << "const"
4267           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4268       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4269         Diag(DS.getVolatileSpecLoc(),
4270              diag::ext_anonymous_struct_union_qualified)
4271           << Record->isUnion() << "volatile"
4272           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4273       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4274         Diag(DS.getRestrictSpecLoc(),
4275              diag::ext_anonymous_struct_union_qualified)
4276           << Record->isUnion() << "restrict"
4277           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4278       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4279         Diag(DS.getAtomicSpecLoc(),
4280              diag::ext_anonymous_struct_union_qualified)
4281           << Record->isUnion() << "_Atomic"
4282           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4283       if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
4284         Diag(DS.getUnalignedSpecLoc(),
4285              diag::ext_anonymous_struct_union_qualified)
4286           << Record->isUnion() << "__unaligned"
4287           << FixItHint::CreateRemoval(DS.getUnalignedSpecLoc());
4288 
4289       DS.ClearTypeQualifiers();
4290     }
4291 
4292     // C++ [class.union]p2:
4293     //   The member-specification of an anonymous union shall only
4294     //   define non-static data members. [Note: nested types and
4295     //   functions cannot be declared within an anonymous union. ]
4296     for (auto *Mem : Record->decls()) {
4297       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4298         // C++ [class.union]p3:
4299         //   An anonymous union shall not have private or protected
4300         //   members (clause 11).
4301         assert(FD->getAccess() != AS_none);
4302         if (FD->getAccess() != AS_public) {
4303           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4304             << Record->isUnion() << (FD->getAccess() == AS_protected);
4305           Invalid = true;
4306         }
4307 
4308         // C++ [class.union]p1
4309         //   An object of a class with a non-trivial constructor, a non-trivial
4310         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4311         //   assignment operator cannot be a member of a union, nor can an
4312         //   array of such objects.
4313         if (CheckNontrivialField(FD))
4314           Invalid = true;
4315       } else if (Mem->isImplicit()) {
4316         // Any implicit members are fine.
4317       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4318         // This is a type that showed up in an
4319         // elaborated-type-specifier inside the anonymous struct or
4320         // union, but which actually declares a type outside of the
4321         // anonymous struct or union. It's okay.
4322       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4323         if (!MemRecord->isAnonymousStructOrUnion() &&
4324             MemRecord->getDeclName()) {
4325           // Visual C++ allows type definition in anonymous struct or union.
4326           if (getLangOpts().MicrosoftExt)
4327             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4328               << Record->isUnion();
4329           else {
4330             // This is a nested type declaration.
4331             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4332               << Record->isUnion();
4333             Invalid = true;
4334           }
4335         } else {
4336           // This is an anonymous type definition within another anonymous type.
4337           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4338           // not part of standard C++.
4339           Diag(MemRecord->getLocation(),
4340                diag::ext_anonymous_record_with_anonymous_type)
4341             << Record->isUnion();
4342         }
4343       } else if (isa<AccessSpecDecl>(Mem)) {
4344         // Any access specifier is fine.
4345       } else if (isa<StaticAssertDecl>(Mem)) {
4346         // In C++1z, static_assert declarations are also fine.
4347       } else {
4348         // We have something that isn't a non-static data
4349         // member. Complain about it.
4350         unsigned DK = diag::err_anonymous_record_bad_member;
4351         if (isa<TypeDecl>(Mem))
4352           DK = diag::err_anonymous_record_with_type;
4353         else if (isa<FunctionDecl>(Mem))
4354           DK = diag::err_anonymous_record_with_function;
4355         else if (isa<VarDecl>(Mem))
4356           DK = diag::err_anonymous_record_with_static;
4357 
4358         // Visual C++ allows type definition in anonymous struct or union.
4359         if (getLangOpts().MicrosoftExt &&
4360             DK == diag::err_anonymous_record_with_type)
4361           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4362             << Record->isUnion();
4363         else {
4364           Diag(Mem->getLocation(), DK) << Record->isUnion();
4365           Invalid = true;
4366         }
4367       }
4368     }
4369 
4370     // C++11 [class.union]p8 (DR1460):
4371     //   At most one variant member of a union may have a
4372     //   brace-or-equal-initializer.
4373     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4374         Owner->isRecord())
4375       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4376                                 cast<CXXRecordDecl>(Record));
4377   }
4378 
4379   if (!Record->isUnion() && !Owner->isRecord()) {
4380     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4381       << getLangOpts().CPlusPlus;
4382     Invalid = true;
4383   }
4384 
4385   // Mock up a declarator.
4386   Declarator Dc(DS, Declarator::MemberContext);
4387   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4388   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4389 
4390   // Create a declaration for this anonymous struct/union.
4391   NamedDecl *Anon = nullptr;
4392   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4393     Anon = FieldDecl::Create(Context, OwningClass,
4394                              DS.getLocStart(),
4395                              Record->getLocation(),
4396                              /*IdentifierInfo=*/nullptr,
4397                              Context.getTypeDeclType(Record),
4398                              TInfo,
4399                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4400                              /*InitStyle=*/ICIS_NoInit);
4401     Anon->setAccess(AS);
4402     if (getLangOpts().CPlusPlus)
4403       FieldCollector->Add(cast<FieldDecl>(Anon));
4404   } else {
4405     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4406     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4407     if (SCSpec == DeclSpec::SCS_mutable) {
4408       // mutable can only appear on non-static class members, so it's always
4409       // an error here
4410       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4411       Invalid = true;
4412       SC = SC_None;
4413     }
4414 
4415     Anon = VarDecl::Create(Context, Owner,
4416                            DS.getLocStart(),
4417                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4418                            Context.getTypeDeclType(Record),
4419                            TInfo, SC);
4420 
4421     // Default-initialize the implicit variable. This initialization will be
4422     // trivial in almost all cases, except if a union member has an in-class
4423     // initializer:
4424     //   union { int n = 0; };
4425     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4426   }
4427   Anon->setImplicit();
4428 
4429   // Mark this as an anonymous struct/union type.
4430   Record->setAnonymousStructOrUnion(true);
4431 
4432   // Add the anonymous struct/union object to the current
4433   // context. We'll be referencing this object when we refer to one of
4434   // its members.
4435   Owner->addDecl(Anon);
4436 
4437   // Inject the members of the anonymous struct/union into the owning
4438   // context and into the identifier resolver chain for name lookup
4439   // purposes.
4440   SmallVector<NamedDecl*, 2> Chain;
4441   Chain.push_back(Anon);
4442 
4443   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
4444     Invalid = true;
4445 
4446   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4447     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4448       Decl *ManglingContextDecl;
4449       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4450               NewVD->getDeclContext(), ManglingContextDecl)) {
4451         Context.setManglingNumber(
4452             NewVD, MCtx->getManglingNumber(
4453                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4454         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4455       }
4456     }
4457   }
4458 
4459   if (Invalid)
4460     Anon->setInvalidDecl();
4461 
4462   return Anon;
4463 }
4464 
4465 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4466 /// Microsoft C anonymous structure.
4467 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4468 /// Example:
4469 ///
4470 /// struct A { int a; };
4471 /// struct B { struct A; int b; };
4472 ///
4473 /// void foo() {
4474 ///   B var;
4475 ///   var.a = 3;
4476 /// }
4477 ///
4478 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4479                                            RecordDecl *Record) {
4480   assert(Record && "expected a record!");
4481 
4482   // Mock up a declarator.
4483   Declarator Dc(DS, Declarator::TypeNameContext);
4484   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4485   assert(TInfo && "couldn't build declarator info for anonymous struct");
4486 
4487   auto *ParentDecl = cast<RecordDecl>(CurContext);
4488   QualType RecTy = Context.getTypeDeclType(Record);
4489 
4490   // Create a declaration for this anonymous struct.
4491   NamedDecl *Anon = FieldDecl::Create(Context,
4492                              ParentDecl,
4493                              DS.getLocStart(),
4494                              DS.getLocStart(),
4495                              /*IdentifierInfo=*/nullptr,
4496                              RecTy,
4497                              TInfo,
4498                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4499                              /*InitStyle=*/ICIS_NoInit);
4500   Anon->setImplicit();
4501 
4502   // Add the anonymous struct object to the current context.
4503   CurContext->addDecl(Anon);
4504 
4505   // Inject the members of the anonymous struct into the current
4506   // context and into the identifier resolver chain for name lookup
4507   // purposes.
4508   SmallVector<NamedDecl*, 2> Chain;
4509   Chain.push_back(Anon);
4510 
4511   RecordDecl *RecordDef = Record->getDefinition();
4512   if (RequireCompleteType(Anon->getLocation(), RecTy,
4513                           diag::err_field_incomplete) ||
4514       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4515                                           AS_none, Chain)) {
4516     Anon->setInvalidDecl();
4517     ParentDecl->setInvalidDecl();
4518   }
4519 
4520   return Anon;
4521 }
4522 
4523 /// GetNameForDeclarator - Determine the full declaration name for the
4524 /// given Declarator.
4525 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4526   return GetNameFromUnqualifiedId(D.getName());
4527 }
4528 
4529 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4530 DeclarationNameInfo
4531 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4532   DeclarationNameInfo NameInfo;
4533   NameInfo.setLoc(Name.StartLocation);
4534 
4535   switch (Name.getKind()) {
4536 
4537   case UnqualifiedId::IK_ImplicitSelfParam:
4538   case UnqualifiedId::IK_Identifier:
4539     NameInfo.setName(Name.Identifier);
4540     NameInfo.setLoc(Name.StartLocation);
4541     return NameInfo;
4542 
4543   case UnqualifiedId::IK_OperatorFunctionId:
4544     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4545                                            Name.OperatorFunctionId.Operator));
4546     NameInfo.setLoc(Name.StartLocation);
4547     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4548       = Name.OperatorFunctionId.SymbolLocations[0];
4549     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4550       = Name.EndLocation.getRawEncoding();
4551     return NameInfo;
4552 
4553   case UnqualifiedId::IK_LiteralOperatorId:
4554     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4555                                                            Name.Identifier));
4556     NameInfo.setLoc(Name.StartLocation);
4557     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4558     return NameInfo;
4559 
4560   case UnqualifiedId::IK_ConversionFunctionId: {
4561     TypeSourceInfo *TInfo;
4562     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4563     if (Ty.isNull())
4564       return DeclarationNameInfo();
4565     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4566                                                Context.getCanonicalType(Ty)));
4567     NameInfo.setLoc(Name.StartLocation);
4568     NameInfo.setNamedTypeInfo(TInfo);
4569     return NameInfo;
4570   }
4571 
4572   case UnqualifiedId::IK_ConstructorName: {
4573     TypeSourceInfo *TInfo;
4574     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4575     if (Ty.isNull())
4576       return DeclarationNameInfo();
4577     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4578                                               Context.getCanonicalType(Ty)));
4579     NameInfo.setLoc(Name.StartLocation);
4580     NameInfo.setNamedTypeInfo(TInfo);
4581     return NameInfo;
4582   }
4583 
4584   case UnqualifiedId::IK_ConstructorTemplateId: {
4585     // In well-formed code, we can only have a constructor
4586     // template-id that refers to the current context, so go there
4587     // to find the actual type being constructed.
4588     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4589     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4590       return DeclarationNameInfo();
4591 
4592     // Determine the type of the class being constructed.
4593     QualType CurClassType = Context.getTypeDeclType(CurClass);
4594 
4595     // FIXME: Check two things: that the template-id names the same type as
4596     // CurClassType, and that the template-id does not occur when the name
4597     // was qualified.
4598 
4599     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4600                                     Context.getCanonicalType(CurClassType)));
4601     NameInfo.setLoc(Name.StartLocation);
4602     // FIXME: should we retrieve TypeSourceInfo?
4603     NameInfo.setNamedTypeInfo(nullptr);
4604     return NameInfo;
4605   }
4606 
4607   case UnqualifiedId::IK_DestructorName: {
4608     TypeSourceInfo *TInfo;
4609     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4610     if (Ty.isNull())
4611       return DeclarationNameInfo();
4612     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4613                                               Context.getCanonicalType(Ty)));
4614     NameInfo.setLoc(Name.StartLocation);
4615     NameInfo.setNamedTypeInfo(TInfo);
4616     return NameInfo;
4617   }
4618 
4619   case UnqualifiedId::IK_TemplateId: {
4620     TemplateName TName = Name.TemplateId->Template.get();
4621     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4622     return Context.getNameForTemplate(TName, TNameLoc);
4623   }
4624 
4625   } // switch (Name.getKind())
4626 
4627   llvm_unreachable("Unknown name kind");
4628 }
4629 
4630 static QualType getCoreType(QualType Ty) {
4631   do {
4632     if (Ty->isPointerType() || Ty->isReferenceType())
4633       Ty = Ty->getPointeeType();
4634     else if (Ty->isArrayType())
4635       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4636     else
4637       return Ty.withoutLocalFastQualifiers();
4638   } while (true);
4639 }
4640 
4641 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4642 /// and Definition have "nearly" matching parameters. This heuristic is
4643 /// used to improve diagnostics in the case where an out-of-line function
4644 /// definition doesn't match any declaration within the class or namespace.
4645 /// Also sets Params to the list of indices to the parameters that differ
4646 /// between the declaration and the definition. If hasSimilarParameters
4647 /// returns true and Params is empty, then all of the parameters match.
4648 static bool hasSimilarParameters(ASTContext &Context,
4649                                      FunctionDecl *Declaration,
4650                                      FunctionDecl *Definition,
4651                                      SmallVectorImpl<unsigned> &Params) {
4652   Params.clear();
4653   if (Declaration->param_size() != Definition->param_size())
4654     return false;
4655   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4656     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4657     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4658 
4659     // The parameter types are identical
4660     if (Context.hasSameType(DefParamTy, DeclParamTy))
4661       continue;
4662 
4663     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4664     QualType DefParamBaseTy = getCoreType(DefParamTy);
4665     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4666     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4667 
4668     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4669         (DeclTyName && DeclTyName == DefTyName))
4670       Params.push_back(Idx);
4671     else  // The two parameters aren't even close
4672       return false;
4673   }
4674 
4675   return true;
4676 }
4677 
4678 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4679 /// declarator needs to be rebuilt in the current instantiation.
4680 /// Any bits of declarator which appear before the name are valid for
4681 /// consideration here.  That's specifically the type in the decl spec
4682 /// and the base type in any member-pointer chunks.
4683 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4684                                                     DeclarationName Name) {
4685   // The types we specifically need to rebuild are:
4686   //   - typenames, typeofs, and decltypes
4687   //   - types which will become injected class names
4688   // Of course, we also need to rebuild any type referencing such a
4689   // type.  It's safest to just say "dependent", but we call out a
4690   // few cases here.
4691 
4692   DeclSpec &DS = D.getMutableDeclSpec();
4693   switch (DS.getTypeSpecType()) {
4694   case DeclSpec::TST_typename:
4695   case DeclSpec::TST_typeofType:
4696   case DeclSpec::TST_underlyingType:
4697   case DeclSpec::TST_atomic: {
4698     // Grab the type from the parser.
4699     TypeSourceInfo *TSI = nullptr;
4700     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4701     if (T.isNull() || !T->isDependentType()) break;
4702 
4703     // Make sure there's a type source info.  This isn't really much
4704     // of a waste; most dependent types should have type source info
4705     // attached already.
4706     if (!TSI)
4707       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4708 
4709     // Rebuild the type in the current instantiation.
4710     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4711     if (!TSI) return true;
4712 
4713     // Store the new type back in the decl spec.
4714     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4715     DS.UpdateTypeRep(LocType);
4716     break;
4717   }
4718 
4719   case DeclSpec::TST_decltype:
4720   case DeclSpec::TST_typeofExpr: {
4721     Expr *E = DS.getRepAsExpr();
4722     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4723     if (Result.isInvalid()) return true;
4724     DS.UpdateExprRep(Result.get());
4725     break;
4726   }
4727 
4728   default:
4729     // Nothing to do for these decl specs.
4730     break;
4731   }
4732 
4733   // It doesn't matter what order we do this in.
4734   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4735     DeclaratorChunk &Chunk = D.getTypeObject(I);
4736 
4737     // The only type information in the declarator which can come
4738     // before the declaration name is the base type of a member
4739     // pointer.
4740     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4741       continue;
4742 
4743     // Rebuild the scope specifier in-place.
4744     CXXScopeSpec &SS = Chunk.Mem.Scope();
4745     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4746       return true;
4747   }
4748 
4749   return false;
4750 }
4751 
4752 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4753   D.setFunctionDefinitionKind(FDK_Declaration);
4754   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4755 
4756   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4757       Dcl && Dcl->getDeclContext()->isFileContext())
4758     Dcl->setTopLevelDeclInObjCContainer();
4759 
4760   return Dcl;
4761 }
4762 
4763 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4764 ///   If T is the name of a class, then each of the following shall have a
4765 ///   name different from T:
4766 ///     - every static data member of class T;
4767 ///     - every member function of class T
4768 ///     - every member of class T that is itself a type;
4769 /// \returns true if the declaration name violates these rules.
4770 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4771                                    DeclarationNameInfo NameInfo) {
4772   DeclarationName Name = NameInfo.getName();
4773 
4774   CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
4775   while (Record && Record->isAnonymousStructOrUnion())
4776     Record = dyn_cast<CXXRecordDecl>(Record->getParent());
4777   if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
4778     Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4779     return true;
4780   }
4781 
4782   return false;
4783 }
4784 
4785 /// \brief Diagnose a declaration whose declarator-id has the given
4786 /// nested-name-specifier.
4787 ///
4788 /// \param SS The nested-name-specifier of the declarator-id.
4789 ///
4790 /// \param DC The declaration context to which the nested-name-specifier
4791 /// resolves.
4792 ///
4793 /// \param Name The name of the entity being declared.
4794 ///
4795 /// \param Loc The location of the name of the entity being declared.
4796 ///
4797 /// \returns true if we cannot safely recover from this error, false otherwise.
4798 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4799                                         DeclarationName Name,
4800                                         SourceLocation Loc) {
4801   DeclContext *Cur = CurContext;
4802   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4803     Cur = Cur->getParent();
4804 
4805   // If the user provided a superfluous scope specifier that refers back to the
4806   // class in which the entity is already declared, diagnose and ignore it.
4807   //
4808   // class X {
4809   //   void X::f();
4810   // };
4811   //
4812   // Note, it was once ill-formed to give redundant qualification in all
4813   // contexts, but that rule was removed by DR482.
4814   if (Cur->Equals(DC)) {
4815     if (Cur->isRecord()) {
4816       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4817                                       : diag::err_member_extra_qualification)
4818         << Name << FixItHint::CreateRemoval(SS.getRange());
4819       SS.clear();
4820     } else {
4821       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4822     }
4823     return false;
4824   }
4825 
4826   // Check whether the qualifying scope encloses the scope of the original
4827   // declaration.
4828   if (!Cur->Encloses(DC)) {
4829     if (Cur->isRecord())
4830       Diag(Loc, diag::err_member_qualification)
4831         << Name << SS.getRange();
4832     else if (isa<TranslationUnitDecl>(DC))
4833       Diag(Loc, diag::err_invalid_declarator_global_scope)
4834         << Name << SS.getRange();
4835     else if (isa<FunctionDecl>(Cur))
4836       Diag(Loc, diag::err_invalid_declarator_in_function)
4837         << Name << SS.getRange();
4838     else if (isa<BlockDecl>(Cur))
4839       Diag(Loc, diag::err_invalid_declarator_in_block)
4840         << Name << SS.getRange();
4841     else
4842       Diag(Loc, diag::err_invalid_declarator_scope)
4843       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4844 
4845     return true;
4846   }
4847 
4848   if (Cur->isRecord()) {
4849     // Cannot qualify members within a class.
4850     Diag(Loc, diag::err_member_qualification)
4851       << Name << SS.getRange();
4852     SS.clear();
4853 
4854     // C++ constructors and destructors with incorrect scopes can break
4855     // our AST invariants by having the wrong underlying types. If
4856     // that's the case, then drop this declaration entirely.
4857     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4858          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4859         !Context.hasSameType(Name.getCXXNameType(),
4860                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4861       return true;
4862 
4863     return false;
4864   }
4865 
4866   // C++11 [dcl.meaning]p1:
4867   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4868   //   not begin with a decltype-specifer"
4869   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4870   while (SpecLoc.getPrefix())
4871     SpecLoc = SpecLoc.getPrefix();
4872   if (dyn_cast_or_null<DecltypeType>(
4873         SpecLoc.getNestedNameSpecifier()->getAsType()))
4874     Diag(Loc, diag::err_decltype_in_declarator)
4875       << SpecLoc.getTypeLoc().getSourceRange();
4876 
4877   return false;
4878 }
4879 
4880 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4881                                   MultiTemplateParamsArg TemplateParamLists) {
4882   // TODO: consider using NameInfo for diagnostic.
4883   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4884   DeclarationName Name = NameInfo.getName();
4885 
4886   // All of these full declarators require an identifier.  If it doesn't have
4887   // one, the ParsedFreeStandingDeclSpec action should be used.
4888   if (!Name) {
4889     if (!D.isInvalidType())  // Reject this if we think it is valid.
4890       Diag(D.getDeclSpec().getLocStart(),
4891            diag::err_declarator_need_ident)
4892         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4893     return nullptr;
4894   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4895     return nullptr;
4896 
4897   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4898   // we find one that is.
4899   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4900          (S->getFlags() & Scope::TemplateParamScope) != 0)
4901     S = S->getParent();
4902 
4903   DeclContext *DC = CurContext;
4904   if (D.getCXXScopeSpec().isInvalid())
4905     D.setInvalidType();
4906   else if (D.getCXXScopeSpec().isSet()) {
4907     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4908                                         UPPC_DeclarationQualifier))
4909       return nullptr;
4910 
4911     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4912     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4913     if (!DC || isa<EnumDecl>(DC)) {
4914       // If we could not compute the declaration context, it's because the
4915       // declaration context is dependent but does not refer to a class,
4916       // class template, or class template partial specialization. Complain
4917       // and return early, to avoid the coming semantic disaster.
4918       Diag(D.getIdentifierLoc(),
4919            diag::err_template_qualified_declarator_no_match)
4920         << D.getCXXScopeSpec().getScopeRep()
4921         << D.getCXXScopeSpec().getRange();
4922       return nullptr;
4923     }
4924     bool IsDependentContext = DC->isDependentContext();
4925 
4926     if (!IsDependentContext &&
4927         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4928       return nullptr;
4929 
4930     // If a class is incomplete, do not parse entities inside it.
4931     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4932       Diag(D.getIdentifierLoc(),
4933            diag::err_member_def_undefined_record)
4934         << Name << DC << D.getCXXScopeSpec().getRange();
4935       return nullptr;
4936     }
4937     if (!D.getDeclSpec().isFriendSpecified()) {
4938       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4939                                       Name, D.getIdentifierLoc())) {
4940         if (DC->isRecord())
4941           return nullptr;
4942 
4943         D.setInvalidType();
4944       }
4945     }
4946 
4947     // Check whether we need to rebuild the type of the given
4948     // declaration in the current instantiation.
4949     if (EnteringContext && IsDependentContext &&
4950         TemplateParamLists.size() != 0) {
4951       ContextRAII SavedContext(*this, DC);
4952       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4953         D.setInvalidType();
4954     }
4955   }
4956 
4957   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4958   QualType R = TInfo->getType();
4959 
4960   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
4961     // If this is a typedef, we'll end up spewing multiple diagnostics.
4962     // Just return early; it's safer. If this is a function, let the
4963     // "constructor cannot have a return type" diagnostic handle it.
4964     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4965       return nullptr;
4966 
4967   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4968                                       UPPC_DeclarationType))
4969     D.setInvalidType();
4970 
4971   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4972                         ForRedeclaration);
4973 
4974   // See if this is a redefinition of a variable in the same scope.
4975   if (!D.getCXXScopeSpec().isSet()) {
4976     bool IsLinkageLookup = false;
4977     bool CreateBuiltins = false;
4978 
4979     // If the declaration we're planning to build will be a function
4980     // or object with linkage, then look for another declaration with
4981     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4982     //
4983     // If the declaration we're planning to build will be declared with
4984     // external linkage in the translation unit, create any builtin with
4985     // the same name.
4986     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4987       /* Do nothing*/;
4988     else if (CurContext->isFunctionOrMethod() &&
4989              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4990               R->isFunctionType())) {
4991       IsLinkageLookup = true;
4992       CreateBuiltins =
4993           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4994     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4995                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4996       CreateBuiltins = true;
4997 
4998     if (IsLinkageLookup)
4999       Previous.clear(LookupRedeclarationWithLinkage);
5000 
5001     LookupName(Previous, S, CreateBuiltins);
5002   } else { // Something like "int foo::x;"
5003     LookupQualifiedName(Previous, DC);
5004 
5005     // C++ [dcl.meaning]p1:
5006     //   When the declarator-id is qualified, the declaration shall refer to a
5007     //  previously declared member of the class or namespace to which the
5008     //  qualifier refers (or, in the case of a namespace, of an element of the
5009     //  inline namespace set of that namespace (7.3.1)) or to a specialization
5010     //  thereof; [...]
5011     //
5012     // Note that we already checked the context above, and that we do not have
5013     // enough information to make sure that Previous contains the declaration
5014     // we want to match. For example, given:
5015     //
5016     //   class X {
5017     //     void f();
5018     //     void f(float);
5019     //   };
5020     //
5021     //   void X::f(int) { } // ill-formed
5022     //
5023     // In this case, Previous will point to the overload set
5024     // containing the two f's declared in X, but neither of them
5025     // matches.
5026 
5027     // C++ [dcl.meaning]p1:
5028     //   [...] the member shall not merely have been introduced by a
5029     //   using-declaration in the scope of the class or namespace nominated by
5030     //   the nested-name-specifier of the declarator-id.
5031     RemoveUsingDecls(Previous);
5032   }
5033 
5034   if (Previous.isSingleResult() &&
5035       Previous.getFoundDecl()->isTemplateParameter()) {
5036     // Maybe we will complain about the shadowed template parameter.
5037     if (!D.isInvalidType())
5038       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
5039                                       Previous.getFoundDecl());
5040 
5041     // Just pretend that we didn't see the previous declaration.
5042     Previous.clear();
5043   }
5044 
5045   // In C++, the previous declaration we find might be a tag type
5046   // (class or enum). In this case, the new declaration will hide the
5047   // tag type. Note that this does does not apply if we're declaring a
5048   // typedef (C++ [dcl.typedef]p4).
5049   if (Previous.isSingleTagDecl() &&
5050       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
5051     Previous.clear();
5052 
5053   // Check that there are no default arguments other than in the parameters
5054   // of a function declaration (C++ only).
5055   if (getLangOpts().CPlusPlus)
5056     CheckExtraCXXDefaultArguments(D);
5057 
5058   if (D.getDeclSpec().isConceptSpecified()) {
5059     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
5060     // applied only to the definition of a function template or variable
5061     // template, declared in namespace scope
5062     if (!TemplateParamLists.size()) {
5063       Diag(D.getDeclSpec().getConceptSpecLoc(),
5064            diag:: err_concept_wrong_decl_kind);
5065       return nullptr;
5066     }
5067 
5068     if (!DC->getRedeclContext()->isFileContext()) {
5069       Diag(D.getIdentifierLoc(),
5070            diag::err_concept_decls_may_only_appear_in_namespace_scope);
5071       return nullptr;
5072     }
5073   }
5074 
5075   NamedDecl *New;
5076 
5077   bool AddToScope = true;
5078   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
5079     if (TemplateParamLists.size()) {
5080       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
5081       return nullptr;
5082     }
5083 
5084     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
5085   } else if (R->isFunctionType()) {
5086     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
5087                                   TemplateParamLists,
5088                                   AddToScope);
5089   } else {
5090     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
5091                                   AddToScope);
5092   }
5093 
5094   if (!New)
5095     return nullptr;
5096 
5097   // If this has an identifier and is not an invalid redeclaration or
5098   // function template specialization, add it to the scope stack.
5099   if (New->getDeclName() && AddToScope &&
5100        !(D.isRedeclaration() && New->isInvalidDecl())) {
5101     // Only make a locally-scoped extern declaration visible if it is the first
5102     // declaration of this entity. Qualified lookup for such an entity should
5103     // only find this declaration if there is no visible declaration of it.
5104     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
5105     PushOnScopeChains(New, S, AddToContext);
5106     if (!AddToContext)
5107       CurContext->addHiddenDecl(New);
5108   }
5109 
5110   if (isInOpenMPDeclareTargetContext())
5111     checkDeclIsAllowedInOpenMPTarget(nullptr, New);
5112 
5113   return New;
5114 }
5115 
5116 /// Helper method to turn variable array types into constant array
5117 /// types in certain situations which would otherwise be errors (for
5118 /// GCC compatibility).
5119 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
5120                                                     ASTContext &Context,
5121                                                     bool &SizeIsNegative,
5122                                                     llvm::APSInt &Oversized) {
5123   // This method tries to turn a variable array into a constant
5124   // array even when the size isn't an ICE.  This is necessary
5125   // for compatibility with code that depends on gcc's buggy
5126   // constant expression folding, like struct {char x[(int)(char*)2];}
5127   SizeIsNegative = false;
5128   Oversized = 0;
5129 
5130   if (T->isDependentType())
5131     return QualType();
5132 
5133   QualifierCollector Qs;
5134   const Type *Ty = Qs.strip(T);
5135 
5136   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
5137     QualType Pointee = PTy->getPointeeType();
5138     QualType FixedType =
5139         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
5140                                             Oversized);
5141     if (FixedType.isNull()) return FixedType;
5142     FixedType = Context.getPointerType(FixedType);
5143     return Qs.apply(Context, FixedType);
5144   }
5145   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5146     QualType Inner = PTy->getInnerType();
5147     QualType FixedType =
5148         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5149                                             Oversized);
5150     if (FixedType.isNull()) return FixedType;
5151     FixedType = Context.getParenType(FixedType);
5152     return Qs.apply(Context, FixedType);
5153   }
5154 
5155   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5156   if (!VLATy)
5157     return QualType();
5158   // FIXME: We should probably handle this case
5159   if (VLATy->getElementType()->isVariablyModifiedType())
5160     return QualType();
5161 
5162   llvm::APSInt Res;
5163   if (!VLATy->getSizeExpr() ||
5164       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5165     return QualType();
5166 
5167   // Check whether the array size is negative.
5168   if (Res.isSigned() && Res.isNegative()) {
5169     SizeIsNegative = true;
5170     return QualType();
5171   }
5172 
5173   // Check whether the array is too large to be addressed.
5174   unsigned ActiveSizeBits
5175     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5176                                               Res);
5177   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5178     Oversized = Res;
5179     return QualType();
5180   }
5181 
5182   return Context.getConstantArrayType(VLATy->getElementType(),
5183                                       Res, ArrayType::Normal, 0);
5184 }
5185 
5186 static void
5187 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5188   SrcTL = SrcTL.getUnqualifiedLoc();
5189   DstTL = DstTL.getUnqualifiedLoc();
5190   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5191     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5192     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5193                                       DstPTL.getPointeeLoc());
5194     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5195     return;
5196   }
5197   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5198     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5199     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5200                                       DstPTL.getInnerLoc());
5201     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5202     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5203     return;
5204   }
5205   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5206   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5207   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5208   TypeLoc DstElemTL = DstATL.getElementLoc();
5209   DstElemTL.initializeFullCopy(SrcElemTL);
5210   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5211   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5212   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5213 }
5214 
5215 /// Helper method to turn variable array types into constant array
5216 /// types in certain situations which would otherwise be errors (for
5217 /// GCC compatibility).
5218 static TypeSourceInfo*
5219 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5220                                               ASTContext &Context,
5221                                               bool &SizeIsNegative,
5222                                               llvm::APSInt &Oversized) {
5223   QualType FixedTy
5224     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5225                                           SizeIsNegative, Oversized);
5226   if (FixedTy.isNull())
5227     return nullptr;
5228   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5229   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5230                                     FixedTInfo->getTypeLoc());
5231   return FixedTInfo;
5232 }
5233 
5234 /// \brief Register the given locally-scoped extern "C" declaration so
5235 /// that it can be found later for redeclarations. We include any extern "C"
5236 /// declaration that is not visible in the translation unit here, not just
5237 /// function-scope declarations.
5238 void
5239 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5240   if (!getLangOpts().CPlusPlus &&
5241       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5242     // Don't need to track declarations in the TU in C.
5243     return;
5244 
5245   // Note that we have a locally-scoped external with this name.
5246   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5247 }
5248 
5249 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5250   // FIXME: We can have multiple results via __attribute__((overloadable)).
5251   auto Result = Context.getExternCContextDecl()->lookup(Name);
5252   return Result.empty() ? nullptr : *Result.begin();
5253 }
5254 
5255 /// \brief Diagnose function specifiers on a declaration of an identifier that
5256 /// does not identify a function.
5257 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5258   // FIXME: We should probably indicate the identifier in question to avoid
5259   // confusion for constructs like "inline int a(), b;"
5260   if (DS.isInlineSpecified())
5261     Diag(DS.getInlineSpecLoc(),
5262          diag::err_inline_non_function);
5263 
5264   if (DS.isVirtualSpecified())
5265     Diag(DS.getVirtualSpecLoc(),
5266          diag::err_virtual_non_function);
5267 
5268   if (DS.isExplicitSpecified())
5269     Diag(DS.getExplicitSpecLoc(),
5270          diag::err_explicit_non_function);
5271 
5272   if (DS.isNoreturnSpecified())
5273     Diag(DS.getNoreturnSpecLoc(),
5274          diag::err_noreturn_non_function);
5275 }
5276 
5277 NamedDecl*
5278 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5279                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5280   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5281   if (D.getCXXScopeSpec().isSet()) {
5282     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5283       << D.getCXXScopeSpec().getRange();
5284     D.setInvalidType();
5285     // Pretend we didn't see the scope specifier.
5286     DC = CurContext;
5287     Previous.clear();
5288   }
5289 
5290   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5291 
5292   if (D.getDeclSpec().isConstexprSpecified())
5293     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5294       << 1;
5295   if (D.getDeclSpec().isConceptSpecified())
5296     Diag(D.getDeclSpec().getConceptSpecLoc(),
5297          diag::err_concept_wrong_decl_kind);
5298 
5299   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5300     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5301       << D.getName().getSourceRange();
5302     return nullptr;
5303   }
5304 
5305   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5306   if (!NewTD) return nullptr;
5307 
5308   // Handle attributes prior to checking for duplicates in MergeVarDecl
5309   ProcessDeclAttributes(S, NewTD, D);
5310 
5311   CheckTypedefForVariablyModifiedType(S, NewTD);
5312 
5313   bool Redeclaration = D.isRedeclaration();
5314   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5315   D.setRedeclaration(Redeclaration);
5316   return ND;
5317 }
5318 
5319 void
5320 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5321   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5322   // then it shall have block scope.
5323   // Note that variably modified types must be fixed before merging the decl so
5324   // that redeclarations will match.
5325   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5326   QualType T = TInfo->getType();
5327   if (T->isVariablyModifiedType()) {
5328     getCurFunction()->setHasBranchProtectedScope();
5329 
5330     if (S->getFnParent() == nullptr) {
5331       bool SizeIsNegative;
5332       llvm::APSInt Oversized;
5333       TypeSourceInfo *FixedTInfo =
5334         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5335                                                       SizeIsNegative,
5336                                                       Oversized);
5337       if (FixedTInfo) {
5338         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5339         NewTD->setTypeSourceInfo(FixedTInfo);
5340       } else {
5341         if (SizeIsNegative)
5342           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5343         else if (T->isVariableArrayType())
5344           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5345         else if (Oversized.getBoolValue())
5346           Diag(NewTD->getLocation(), diag::err_array_too_large)
5347             << Oversized.toString(10);
5348         else
5349           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5350         NewTD->setInvalidDecl();
5351       }
5352     }
5353   }
5354 }
5355 
5356 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5357 /// declares a typedef-name, either using the 'typedef' type specifier or via
5358 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5359 NamedDecl*
5360 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5361                            LookupResult &Previous, bool &Redeclaration) {
5362   // Merge the decl with the existing one if appropriate. If the decl is
5363   // in an outer scope, it isn't the same thing.
5364   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5365                        /*AllowInlineNamespace*/false);
5366   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5367   if (!Previous.empty()) {
5368     Redeclaration = true;
5369     MergeTypedefNameDecl(S, NewTD, Previous);
5370   }
5371 
5372   // If this is the C FILE type, notify the AST context.
5373   if (IdentifierInfo *II = NewTD->getIdentifier())
5374     if (!NewTD->isInvalidDecl() &&
5375         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5376       if (II->isStr("FILE"))
5377         Context.setFILEDecl(NewTD);
5378       else if (II->isStr("jmp_buf"))
5379         Context.setjmp_bufDecl(NewTD);
5380       else if (II->isStr("sigjmp_buf"))
5381         Context.setsigjmp_bufDecl(NewTD);
5382       else if (II->isStr("ucontext_t"))
5383         Context.setucontext_tDecl(NewTD);
5384     }
5385 
5386   return NewTD;
5387 }
5388 
5389 /// \brief Determines whether the given declaration is an out-of-scope
5390 /// previous declaration.
5391 ///
5392 /// This routine should be invoked when name lookup has found a
5393 /// previous declaration (PrevDecl) that is not in the scope where a
5394 /// new declaration by the same name is being introduced. If the new
5395 /// declaration occurs in a local scope, previous declarations with
5396 /// linkage may still be considered previous declarations (C99
5397 /// 6.2.2p4-5, C++ [basic.link]p6).
5398 ///
5399 /// \param PrevDecl the previous declaration found by name
5400 /// lookup
5401 ///
5402 /// \param DC the context in which the new declaration is being
5403 /// declared.
5404 ///
5405 /// \returns true if PrevDecl is an out-of-scope previous declaration
5406 /// for a new delcaration with the same name.
5407 static bool
5408 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5409                                 ASTContext &Context) {
5410   if (!PrevDecl)
5411     return false;
5412 
5413   if (!PrevDecl->hasLinkage())
5414     return false;
5415 
5416   if (Context.getLangOpts().CPlusPlus) {
5417     // C++ [basic.link]p6:
5418     //   If there is a visible declaration of an entity with linkage
5419     //   having the same name and type, ignoring entities declared
5420     //   outside the innermost enclosing namespace scope, the block
5421     //   scope declaration declares that same entity and receives the
5422     //   linkage of the previous declaration.
5423     DeclContext *OuterContext = DC->getRedeclContext();
5424     if (!OuterContext->isFunctionOrMethod())
5425       // This rule only applies to block-scope declarations.
5426       return false;
5427 
5428     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5429     if (PrevOuterContext->isRecord())
5430       // We found a member function: ignore it.
5431       return false;
5432 
5433     // Find the innermost enclosing namespace for the new and
5434     // previous declarations.
5435     OuterContext = OuterContext->getEnclosingNamespaceContext();
5436     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5437 
5438     // The previous declaration is in a different namespace, so it
5439     // isn't the same function.
5440     if (!OuterContext->Equals(PrevOuterContext))
5441       return false;
5442   }
5443 
5444   return true;
5445 }
5446 
5447 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5448   CXXScopeSpec &SS = D.getCXXScopeSpec();
5449   if (!SS.isSet()) return;
5450   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5451 }
5452 
5453 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5454   QualType type = decl->getType();
5455   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5456   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5457     // Various kinds of declaration aren't allowed to be __autoreleasing.
5458     unsigned kind = -1U;
5459     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5460       if (var->hasAttr<BlocksAttr>())
5461         kind = 0; // __block
5462       else if (!var->hasLocalStorage())
5463         kind = 1; // global
5464     } else if (isa<ObjCIvarDecl>(decl)) {
5465       kind = 3; // ivar
5466     } else if (isa<FieldDecl>(decl)) {
5467       kind = 2; // field
5468     }
5469 
5470     if (kind != -1U) {
5471       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5472         << kind;
5473     }
5474   } else if (lifetime == Qualifiers::OCL_None) {
5475     // Try to infer lifetime.
5476     if (!type->isObjCLifetimeType())
5477       return false;
5478 
5479     lifetime = type->getObjCARCImplicitLifetime();
5480     type = Context.getLifetimeQualifiedType(type, lifetime);
5481     decl->setType(type);
5482   }
5483 
5484   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5485     // Thread-local variables cannot have lifetime.
5486     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5487         var->getTLSKind()) {
5488       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5489         << var->getType();
5490       return true;
5491     }
5492   }
5493 
5494   return false;
5495 }
5496 
5497 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5498   // Ensure that an auto decl is deduced otherwise the checks below might cache
5499   // the wrong linkage.
5500   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5501 
5502   // 'weak' only applies to declarations with external linkage.
5503   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5504     if (!ND.isExternallyVisible()) {
5505       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5506       ND.dropAttr<WeakAttr>();
5507     }
5508   }
5509   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5510     if (ND.isExternallyVisible()) {
5511       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5512       ND.dropAttr<WeakRefAttr>();
5513       ND.dropAttr<AliasAttr>();
5514     }
5515   }
5516 
5517   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5518     if (VD->hasInit()) {
5519       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5520         assert(VD->isThisDeclarationADefinition() &&
5521                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5522         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
5523         VD->dropAttr<AliasAttr>();
5524       }
5525     }
5526   }
5527 
5528   // 'selectany' only applies to externally visible variable declarations.
5529   // It does not apply to functions.
5530   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5531     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5532       S.Diag(Attr->getLocation(),
5533              diag::err_attribute_selectany_non_extern_data);
5534       ND.dropAttr<SelectAnyAttr>();
5535     }
5536   }
5537 
5538   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5539     // dll attributes require external linkage. Static locals may have external
5540     // linkage but still cannot be explicitly imported or exported.
5541     auto *VD = dyn_cast<VarDecl>(&ND);
5542     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5543       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5544         << &ND << Attr;
5545       ND.setInvalidDecl();
5546     }
5547   }
5548 
5549   // Virtual functions cannot be marked as 'notail'.
5550   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5551     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5552       if (MD->isVirtual()) {
5553         S.Diag(ND.getLocation(),
5554                diag::err_invalid_attribute_on_virtual_function)
5555             << Attr;
5556         ND.dropAttr<NotTailCalledAttr>();
5557       }
5558 }
5559 
5560 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5561                                            NamedDecl *NewDecl,
5562                                            bool IsSpecialization,
5563                                            bool IsDefinition) {
5564   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
5565     OldDecl = OldTD->getTemplatedDecl();
5566     if (!IsSpecialization)
5567       IsDefinition = false;
5568   }
5569   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5570     NewDecl = NewTD->getTemplatedDecl();
5571 
5572   if (!OldDecl || !NewDecl)
5573     return;
5574 
5575   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5576   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5577   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5578   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5579 
5580   // dllimport and dllexport are inheritable attributes so we have to exclude
5581   // inherited attribute instances.
5582   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5583                     (NewExportAttr && !NewExportAttr->isInherited());
5584 
5585   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5586   // the only exception being explicit specializations.
5587   // Implicitly generated declarations are also excluded for now because there
5588   // is no other way to switch these to use dllimport or dllexport.
5589   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5590 
5591   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5592     // Allow with a warning for free functions and global variables.
5593     bool JustWarn = false;
5594     if (!OldDecl->isCXXClassMember()) {
5595       auto *VD = dyn_cast<VarDecl>(OldDecl);
5596       if (VD && !VD->getDescribedVarTemplate())
5597         JustWarn = true;
5598       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5599       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5600         JustWarn = true;
5601     }
5602 
5603     // We cannot change a declaration that's been used because IR has already
5604     // been emitted. Dllimported functions will still work though (modulo
5605     // address equality) as they can use the thunk.
5606     if (OldDecl->isUsed())
5607       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5608         JustWarn = false;
5609 
5610     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5611                                : diag::err_attribute_dll_redeclaration;
5612     S.Diag(NewDecl->getLocation(), DiagID)
5613         << NewDecl
5614         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5615     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5616     if (!JustWarn) {
5617       NewDecl->setInvalidDecl();
5618       return;
5619     }
5620   }
5621 
5622   // A redeclaration is not allowed to drop a dllimport attribute, the only
5623   // exceptions being inline function definitions, local extern declarations,
5624   // qualified friend declarations or special MSVC extension: in the last case,
5625   // the declaration is treated as if it were marked dllexport.
5626   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5627   bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
5628   if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
5629     // Ignore static data because out-of-line definitions are diagnosed
5630     // separately.
5631     IsStaticDataMember = VD->isStaticDataMember();
5632     IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
5633                    VarDecl::DeclarationOnly;
5634   } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5635     IsInline = FD->isInlined();
5636     IsQualifiedFriend = FD->getQualifier() &&
5637                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5638   }
5639 
5640   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5641       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5642     if (IsMicrosoft && IsDefinition) {
5643       S.Diag(NewDecl->getLocation(),
5644              diag::warn_redeclaration_without_import_attribute)
5645           << NewDecl;
5646       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5647       NewDecl->dropAttr<DLLImportAttr>();
5648       NewDecl->addAttr(::new (S.Context) DLLExportAttr(
5649           NewImportAttr->getRange(), S.Context,
5650           NewImportAttr->getSpellingListIndex()));
5651     } else {
5652       S.Diag(NewDecl->getLocation(),
5653              diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5654           << NewDecl << OldImportAttr;
5655       S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5656       S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5657       OldDecl->dropAttr<DLLImportAttr>();
5658       NewDecl->dropAttr<DLLImportAttr>();
5659     }
5660   } else if (IsInline && OldImportAttr && !IsMicrosoft) {
5661     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5662     OldDecl->dropAttr<DLLImportAttr>();
5663     NewDecl->dropAttr<DLLImportAttr>();
5664     S.Diag(NewDecl->getLocation(),
5665            diag::warn_dllimport_dropped_from_inline_function)
5666         << NewDecl << OldImportAttr;
5667   }
5668 }
5669 
5670 /// Given that we are within the definition of the given function,
5671 /// will that definition behave like C99's 'inline', where the
5672 /// definition is discarded except for optimization purposes?
5673 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5674   // Try to avoid calling GetGVALinkageForFunction.
5675 
5676   // All cases of this require the 'inline' keyword.
5677   if (!FD->isInlined()) return false;
5678 
5679   // This is only possible in C++ with the gnu_inline attribute.
5680   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5681     return false;
5682 
5683   // Okay, go ahead and call the relatively-more-expensive function.
5684 
5685 #ifndef NDEBUG
5686   // AST quite reasonably asserts that it's working on a function
5687   // definition.  We don't really have a way to tell it that we're
5688   // currently defining the function, so just lie to it in +Asserts
5689   // builds.  This is an awful hack.
5690   FD->setLazyBody(1);
5691 #endif
5692 
5693   bool isC99Inline =
5694       S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5695 
5696 #ifndef NDEBUG
5697   FD->setLazyBody(0);
5698 #endif
5699 
5700   return isC99Inline;
5701 }
5702 
5703 /// Determine whether a variable is extern "C" prior to attaching
5704 /// an initializer. We can't just call isExternC() here, because that
5705 /// will also compute and cache whether the declaration is externally
5706 /// visible, which might change when we attach the initializer.
5707 ///
5708 /// This can only be used if the declaration is known to not be a
5709 /// redeclaration of an internal linkage declaration.
5710 ///
5711 /// For instance:
5712 ///
5713 ///   auto x = []{};
5714 ///
5715 /// Attaching the initializer here makes this declaration not externally
5716 /// visible, because its type has internal linkage.
5717 ///
5718 /// FIXME: This is a hack.
5719 template<typename T>
5720 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5721   if (S.getLangOpts().CPlusPlus) {
5722     // In C++, the overloadable attribute negates the effects of extern "C".
5723     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5724       return false;
5725 
5726     // So do CUDA's host/device attributes.
5727     if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
5728                                  D->template hasAttr<CUDAHostAttr>()))
5729       return false;
5730   }
5731   return D->isExternC();
5732 }
5733 
5734 static bool shouldConsiderLinkage(const VarDecl *VD) {
5735   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5736   if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC))
5737     return VD->hasExternalStorage();
5738   if (DC->isFileContext())
5739     return true;
5740   if (DC->isRecord())
5741     return false;
5742   llvm_unreachable("Unexpected context");
5743 }
5744 
5745 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5746   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5747   if (DC->isFileContext() || DC->isFunctionOrMethod() ||
5748       isa<OMPDeclareReductionDecl>(DC))
5749     return true;
5750   if (DC->isRecord())
5751     return false;
5752   llvm_unreachable("Unexpected context");
5753 }
5754 
5755 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5756                           AttributeList::Kind Kind) {
5757   for (const AttributeList *L = AttrList; L; L = L->getNext())
5758     if (L->getKind() == Kind)
5759       return true;
5760   return false;
5761 }
5762 
5763 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5764                           AttributeList::Kind Kind) {
5765   // Check decl attributes on the DeclSpec.
5766   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5767     return true;
5768 
5769   // Walk the declarator structure, checking decl attributes that were in a type
5770   // position to the decl itself.
5771   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5772     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5773       return true;
5774   }
5775 
5776   // Finally, check attributes on the decl itself.
5777   return hasParsedAttr(S, PD.getAttributes(), Kind);
5778 }
5779 
5780 /// Adjust the \c DeclContext for a function or variable that might be a
5781 /// function-local external declaration.
5782 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5783   if (!DC->isFunctionOrMethod())
5784     return false;
5785 
5786   // If this is a local extern function or variable declared within a function
5787   // template, don't add it into the enclosing namespace scope until it is
5788   // instantiated; it might have a dependent type right now.
5789   if (DC->isDependentContext())
5790     return true;
5791 
5792   // C++11 [basic.link]p7:
5793   //   When a block scope declaration of an entity with linkage is not found to
5794   //   refer to some other declaration, then that entity is a member of the
5795   //   innermost enclosing namespace.
5796   //
5797   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5798   // semantically-enclosing namespace, not a lexically-enclosing one.
5799   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5800     DC = DC->getParent();
5801   return true;
5802 }
5803 
5804 /// \brief Returns true if given declaration has external C language linkage.
5805 static bool isDeclExternC(const Decl *D) {
5806   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5807     return FD->isExternC();
5808   if (const auto *VD = dyn_cast<VarDecl>(D))
5809     return VD->isExternC();
5810 
5811   llvm_unreachable("Unknown type of decl!");
5812 }
5813 
5814 NamedDecl *
5815 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5816                               TypeSourceInfo *TInfo, LookupResult &Previous,
5817                               MultiTemplateParamsArg TemplateParamLists,
5818                               bool &AddToScope) {
5819   QualType R = TInfo->getType();
5820   DeclarationName Name = GetNameForDeclarator(D).getName();
5821 
5822   // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
5823   // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
5824   // argument.
5825   if (getLangOpts().OpenCL && (R->isImageType() || R->isPipeType())) {
5826     Diag(D.getIdentifierLoc(),
5827          diag::err_opencl_type_can_only_be_used_as_function_parameter)
5828         << R;
5829     D.setInvalidType();
5830     return nullptr;
5831   }
5832 
5833   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5834   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5835 
5836   // dllimport globals without explicit storage class are treated as extern. We
5837   // have to change the storage class this early to get the right DeclContext.
5838   if (SC == SC_None && !DC->isRecord() &&
5839       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5840       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5841     SC = SC_Extern;
5842 
5843   DeclContext *OriginalDC = DC;
5844   bool IsLocalExternDecl = SC == SC_Extern &&
5845                            adjustContextForLocalExternDecl(DC);
5846 
5847   if (getLangOpts().OpenCL) {
5848     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5849     QualType NR = R;
5850     while (NR->isPointerType()) {
5851       if (NR->isFunctionPointerType()) {
5852         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5853         D.setInvalidType();
5854         break;
5855       }
5856       NR = NR->getPointeeType();
5857     }
5858 
5859     if (!getOpenCLOptions().cl_khr_fp16) {
5860       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5861       // half array type (unless the cl_khr_fp16 extension is enabled).
5862       if (Context.getBaseElementType(R)->isHalfType()) {
5863         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5864         D.setInvalidType();
5865       }
5866     }
5867   }
5868 
5869   if (SCSpec == DeclSpec::SCS_mutable) {
5870     // mutable can only appear on non-static class members, so it's always
5871     // an error here
5872     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5873     D.setInvalidType();
5874     SC = SC_None;
5875   }
5876 
5877   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5878       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5879                               D.getDeclSpec().getStorageClassSpecLoc())) {
5880     // In C++11, the 'register' storage class specifier is deprecated.
5881     // Suppress the warning in system macros, it's used in macros in some
5882     // popular C system headers, such as in glibc's htonl() macro.
5883     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5884          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
5885                                    : diag::warn_deprecated_register)
5886       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5887   }
5888 
5889   IdentifierInfo *II = Name.getAsIdentifierInfo();
5890   if (!II) {
5891     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5892       << Name;
5893     return nullptr;
5894   }
5895 
5896   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5897 
5898   if (!DC->isRecord() && S->getFnParent() == nullptr) {
5899     // C99 6.9p2: The storage-class specifiers auto and register shall not
5900     // appear in the declaration specifiers in an external declaration.
5901     // Global Register+Asm is a GNU extension we support.
5902     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5903       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5904       D.setInvalidType();
5905     }
5906   }
5907 
5908   if (getLangOpts().OpenCL) {
5909     // OpenCL v1.2 s6.9.b p4:
5910     // The sampler type cannot be used with the __local and __global address
5911     // space qualifiers.
5912     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5913       R.getAddressSpace() == LangAS::opencl_global)) {
5914       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5915     }
5916 
5917     // OpenCL 1.2 spec, p6.9 r:
5918     // The event type cannot be used to declare a program scope variable.
5919     // The event type cannot be used with the __local, __constant and __global
5920     // address space qualifiers.
5921     if (R->isEventT()) {
5922       if (S->getParent() == nullptr) {
5923         Diag(D.getLocStart(), diag::err_event_t_global_var);
5924         D.setInvalidType();
5925       }
5926 
5927       if (R.getAddressSpace()) {
5928         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5929         D.setInvalidType();
5930       }
5931     }
5932   }
5933 
5934   bool IsExplicitSpecialization = false;
5935   bool IsVariableTemplateSpecialization = false;
5936   bool IsPartialSpecialization = false;
5937   bool IsVariableTemplate = false;
5938   VarDecl *NewVD = nullptr;
5939   VarTemplateDecl *NewTemplate = nullptr;
5940   TemplateParameterList *TemplateParams = nullptr;
5941   if (!getLangOpts().CPlusPlus) {
5942     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5943                             D.getIdentifierLoc(), II,
5944                             R, TInfo, SC);
5945 
5946     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5947       ParsingInitForAutoVars.insert(NewVD);
5948 
5949     if (D.isInvalidType())
5950       NewVD->setInvalidDecl();
5951   } else {
5952     bool Invalid = false;
5953 
5954     if (DC->isRecord() && !CurContext->isRecord()) {
5955       // This is an out-of-line definition of a static data member.
5956       switch (SC) {
5957       case SC_None:
5958         break;
5959       case SC_Static:
5960         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5961              diag::err_static_out_of_line)
5962           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5963         break;
5964       case SC_Auto:
5965       case SC_Register:
5966       case SC_Extern:
5967         // [dcl.stc] p2: The auto or register specifiers shall be applied only
5968         // to names of variables declared in a block or to function parameters.
5969         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5970         // of class members
5971 
5972         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5973              diag::err_storage_class_for_static_member)
5974           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5975         break;
5976       case SC_PrivateExtern:
5977         llvm_unreachable("C storage class in c++!");
5978       }
5979     }
5980 
5981     if (SC == SC_Static && CurContext->isRecord()) {
5982       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5983         if (RD->isLocalClass())
5984           Diag(D.getIdentifierLoc(),
5985                diag::err_static_data_member_not_allowed_in_local_class)
5986             << Name << RD->getDeclName();
5987 
5988         // C++98 [class.union]p1: If a union contains a static data member,
5989         // the program is ill-formed. C++11 drops this restriction.
5990         if (RD->isUnion())
5991           Diag(D.getIdentifierLoc(),
5992                getLangOpts().CPlusPlus11
5993                  ? diag::warn_cxx98_compat_static_data_member_in_union
5994                  : diag::ext_static_data_member_in_union) << Name;
5995         // We conservatively disallow static data members in anonymous structs.
5996         else if (!RD->getDeclName())
5997           Diag(D.getIdentifierLoc(),
5998                diag::err_static_data_member_not_allowed_in_anon_struct)
5999             << Name << RD->isUnion();
6000       }
6001     }
6002 
6003     // Match up the template parameter lists with the scope specifier, then
6004     // determine whether we have a template or a template specialization.
6005     TemplateParams = MatchTemplateParametersToScopeSpecifier(
6006         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
6007         D.getCXXScopeSpec(),
6008         D.getName().getKind() == UnqualifiedId::IK_TemplateId
6009             ? D.getName().TemplateId
6010             : nullptr,
6011         TemplateParamLists,
6012         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
6013 
6014     if (TemplateParams) {
6015       if (!TemplateParams->size() &&
6016           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
6017         // There is an extraneous 'template<>' for this variable. Complain
6018         // about it, but allow the declaration of the variable.
6019         Diag(TemplateParams->getTemplateLoc(),
6020              diag::err_template_variable_noparams)
6021           << II
6022           << SourceRange(TemplateParams->getTemplateLoc(),
6023                          TemplateParams->getRAngleLoc());
6024         TemplateParams = nullptr;
6025       } else {
6026         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
6027           // This is an explicit specialization or a partial specialization.
6028           // FIXME: Check that we can declare a specialization here.
6029           IsVariableTemplateSpecialization = true;
6030           IsPartialSpecialization = TemplateParams->size() > 0;
6031         } else { // if (TemplateParams->size() > 0)
6032           // This is a template declaration.
6033           IsVariableTemplate = true;
6034 
6035           // Check that we can declare a template here.
6036           if (CheckTemplateDeclScope(S, TemplateParams))
6037             return nullptr;
6038 
6039           // Only C++1y supports variable templates (N3651).
6040           Diag(D.getIdentifierLoc(),
6041                getLangOpts().CPlusPlus14
6042                    ? diag::warn_cxx11_compat_variable_template
6043                    : diag::ext_variable_template);
6044         }
6045       }
6046     } else {
6047       assert(
6048           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
6049           "should have a 'template<>' for this decl");
6050     }
6051 
6052     if (IsVariableTemplateSpecialization) {
6053       SourceLocation TemplateKWLoc =
6054           TemplateParamLists.size() > 0
6055               ? TemplateParamLists[0]->getTemplateLoc()
6056               : SourceLocation();
6057       DeclResult Res = ActOnVarTemplateSpecialization(
6058           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
6059           IsPartialSpecialization);
6060       if (Res.isInvalid())
6061         return nullptr;
6062       NewVD = cast<VarDecl>(Res.get());
6063       AddToScope = false;
6064     } else
6065       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
6066                               D.getIdentifierLoc(), II, R, TInfo, SC);
6067 
6068     // If this is supposed to be a variable template, create it as such.
6069     if (IsVariableTemplate) {
6070       NewTemplate =
6071           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
6072                                   TemplateParams, NewVD);
6073       NewVD->setDescribedVarTemplate(NewTemplate);
6074     }
6075 
6076     // If this decl has an auto type in need of deduction, make a note of the
6077     // Decl so we can diagnose uses of it in its own initializer.
6078     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
6079       ParsingInitForAutoVars.insert(NewVD);
6080 
6081     if (D.isInvalidType() || Invalid) {
6082       NewVD->setInvalidDecl();
6083       if (NewTemplate)
6084         NewTemplate->setInvalidDecl();
6085     }
6086 
6087     SetNestedNameSpecifier(NewVD, D);
6088 
6089     // If we have any template parameter lists that don't directly belong to
6090     // the variable (matching the scope specifier), store them.
6091     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
6092     if (TemplateParamLists.size() > VDTemplateParamLists)
6093       NewVD->setTemplateParameterListsInfo(
6094           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
6095 
6096     if (D.getDeclSpec().isConstexprSpecified())
6097       NewVD->setConstexpr(true);
6098 
6099     if (D.getDeclSpec().isConceptSpecified()) {
6100       if (VarTemplateDecl *VTD = NewVD->getDescribedVarTemplate())
6101         VTD->setConcept();
6102 
6103       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
6104       // be declared with the thread_local, inline, friend, or constexpr
6105       // specifiers, [...]
6106       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
6107         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6108              diag::err_concept_decl_invalid_specifiers)
6109             << 0 << 0;
6110         NewVD->setInvalidDecl(true);
6111       }
6112 
6113       if (D.getDeclSpec().isConstexprSpecified()) {
6114         Diag(D.getDeclSpec().getConstexprSpecLoc(),
6115              diag::err_concept_decl_invalid_specifiers)
6116             << 0 << 3;
6117         NewVD->setInvalidDecl(true);
6118       }
6119 
6120       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
6121       // applied only to the definition of a function template or variable
6122       // template, declared in namespace scope.
6123       if (IsVariableTemplateSpecialization) {
6124         Diag(D.getDeclSpec().getConceptSpecLoc(),
6125              diag::err_concept_specified_specialization)
6126             << (IsPartialSpecialization ? 2 : 1);
6127       }
6128 
6129       // C++ Concepts TS [dcl.spec.concept]p6: A variable concept has the
6130       // following restrictions:
6131       // - The declared type shall have the type bool.
6132       if (!Context.hasSameType(NewVD->getType(), Context.BoolTy) &&
6133           !NewVD->isInvalidDecl()) {
6134         Diag(D.getIdentifierLoc(), diag::err_variable_concept_bool_decl);
6135         NewVD->setInvalidDecl(true);
6136       }
6137     }
6138   }
6139 
6140   // Set the lexical context. If the declarator has a C++ scope specifier, the
6141   // lexical context will be different from the semantic context.
6142   NewVD->setLexicalDeclContext(CurContext);
6143   if (NewTemplate)
6144     NewTemplate->setLexicalDeclContext(CurContext);
6145 
6146   if (IsLocalExternDecl)
6147     NewVD->setLocalExternDecl();
6148 
6149   bool EmitTLSUnsupportedError = false;
6150   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
6151     // C++11 [dcl.stc]p4:
6152     //   When thread_local is applied to a variable of block scope the
6153     //   storage-class-specifier static is implied if it does not appear
6154     //   explicitly.
6155     // Core issue: 'static' is not implied if the variable is declared
6156     //   'extern'.
6157     if (NewVD->hasLocalStorage() &&
6158         (SCSpec != DeclSpec::SCS_unspecified ||
6159          TSCS != DeclSpec::TSCS_thread_local ||
6160          !DC->isFunctionOrMethod()))
6161       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6162            diag::err_thread_non_global)
6163         << DeclSpec::getSpecifierName(TSCS);
6164     else if (!Context.getTargetInfo().isTLSSupported()) {
6165       if (getLangOpts().CUDA) {
6166         // Postpone error emission until we've collected attributes required to
6167         // figure out whether it's a host or device variable and whether the
6168         // error should be ignored.
6169         EmitTLSUnsupportedError = true;
6170         // We still need to mark the variable as TLS so it shows up in AST with
6171         // proper storage class for other tools to use even if we're not going
6172         // to emit any code for it.
6173         NewVD->setTSCSpec(TSCS);
6174       } else
6175         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6176              diag::err_thread_unsupported);
6177     } else
6178       NewVD->setTSCSpec(TSCS);
6179   }
6180 
6181   // C99 6.7.4p3
6182   //   An inline definition of a function with external linkage shall
6183   //   not contain a definition of a modifiable object with static or
6184   //   thread storage duration...
6185   // We only apply this when the function is required to be defined
6186   // elsewhere, i.e. when the function is not 'extern inline'.  Note
6187   // that a local variable with thread storage duration still has to
6188   // be marked 'static'.  Also note that it's possible to get these
6189   // semantics in C++ using __attribute__((gnu_inline)).
6190   if (SC == SC_Static && S->getFnParent() != nullptr &&
6191       !NewVD->getType().isConstQualified()) {
6192     FunctionDecl *CurFD = getCurFunctionDecl();
6193     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6194       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6195            diag::warn_static_local_in_extern_inline);
6196       MaybeSuggestAddingStaticToDecl(CurFD);
6197     }
6198   }
6199 
6200   if (D.getDeclSpec().isModulePrivateSpecified()) {
6201     if (IsVariableTemplateSpecialization)
6202       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6203           << (IsPartialSpecialization ? 1 : 0)
6204           << FixItHint::CreateRemoval(
6205                  D.getDeclSpec().getModulePrivateSpecLoc());
6206     else if (IsExplicitSpecialization)
6207       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6208         << 2
6209         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6210     else if (NewVD->hasLocalStorage())
6211       Diag(NewVD->getLocation(), diag::err_module_private_local)
6212         << 0 << NewVD->getDeclName()
6213         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6214         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6215     else {
6216       NewVD->setModulePrivate();
6217       if (NewTemplate)
6218         NewTemplate->setModulePrivate();
6219     }
6220   }
6221 
6222   // Handle attributes prior to checking for duplicates in MergeVarDecl
6223   ProcessDeclAttributes(S, NewVD, D);
6224 
6225   if (getLangOpts().CUDA) {
6226     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6227       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6228            diag::err_thread_unsupported);
6229     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6230     // storage [duration]."
6231     if (SC == SC_None && S->getFnParent() != nullptr &&
6232         (NewVD->hasAttr<CUDASharedAttr>() ||
6233          NewVD->hasAttr<CUDAConstantAttr>())) {
6234       NewVD->setStorageClass(SC_Static);
6235     }
6236   }
6237 
6238   // Ensure that dllimport globals without explicit storage class are treated as
6239   // extern. The storage class is set above using parsed attributes. Now we can
6240   // check the VarDecl itself.
6241   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6242          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6243          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6244 
6245   // In auto-retain/release, infer strong retension for variables of
6246   // retainable type.
6247   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6248     NewVD->setInvalidDecl();
6249 
6250   // Handle GNU asm-label extension (encoded as an attribute).
6251   if (Expr *E = (Expr*)D.getAsmLabel()) {
6252     // The parser guarantees this is a string.
6253     StringLiteral *SE = cast<StringLiteral>(E);
6254     StringRef Label = SE->getString();
6255     if (S->getFnParent() != nullptr) {
6256       switch (SC) {
6257       case SC_None:
6258       case SC_Auto:
6259         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6260         break;
6261       case SC_Register:
6262         // Local Named register
6263         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6264             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6265           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6266         break;
6267       case SC_Static:
6268       case SC_Extern:
6269       case SC_PrivateExtern:
6270         break;
6271       }
6272     } else if (SC == SC_Register) {
6273       // Global Named register
6274       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6275         const auto &TI = Context.getTargetInfo();
6276         bool HasSizeMismatch;
6277 
6278         if (!TI.isValidGCCRegisterName(Label))
6279           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6280         else if (!TI.validateGlobalRegisterVariable(Label,
6281                                                     Context.getTypeSize(R),
6282                                                     HasSizeMismatch))
6283           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6284         else if (HasSizeMismatch)
6285           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6286       }
6287 
6288       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6289         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6290         NewVD->setInvalidDecl(true);
6291       }
6292     }
6293 
6294     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6295                                                 Context, Label, 0));
6296   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6297     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6298       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6299     if (I != ExtnameUndeclaredIdentifiers.end()) {
6300       if (isDeclExternC(NewVD)) {
6301         NewVD->addAttr(I->second);
6302         ExtnameUndeclaredIdentifiers.erase(I);
6303       } else
6304         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6305             << /*Variable*/1 << NewVD;
6306     }
6307   }
6308 
6309   // Diagnose shadowed variables before filtering for scope.
6310   if (D.getCXXScopeSpec().isEmpty())
6311     CheckShadow(S, NewVD, Previous);
6312 
6313   // Don't consider existing declarations that are in a different
6314   // scope and are out-of-semantic-context declarations (if the new
6315   // declaration has linkage).
6316   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6317                        D.getCXXScopeSpec().isNotEmpty() ||
6318                        IsExplicitSpecialization ||
6319                        IsVariableTemplateSpecialization);
6320 
6321   // Check whether the previous declaration is in the same block scope. This
6322   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6323   if (getLangOpts().CPlusPlus &&
6324       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6325     NewVD->setPreviousDeclInSameBlockScope(
6326         Previous.isSingleResult() && !Previous.isShadowed() &&
6327         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6328 
6329   if (!getLangOpts().CPlusPlus) {
6330     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6331   } else {
6332     // If this is an explicit specialization of a static data member, check it.
6333     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6334         CheckMemberSpecialization(NewVD, Previous))
6335       NewVD->setInvalidDecl();
6336 
6337     // Merge the decl with the existing one if appropriate.
6338     if (!Previous.empty()) {
6339       if (Previous.isSingleResult() &&
6340           isa<FieldDecl>(Previous.getFoundDecl()) &&
6341           D.getCXXScopeSpec().isSet()) {
6342         // The user tried to define a non-static data member
6343         // out-of-line (C++ [dcl.meaning]p1).
6344         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6345           << D.getCXXScopeSpec().getRange();
6346         Previous.clear();
6347         NewVD->setInvalidDecl();
6348       }
6349     } else if (D.getCXXScopeSpec().isSet()) {
6350       // No previous declaration in the qualifying scope.
6351       Diag(D.getIdentifierLoc(), diag::err_no_member)
6352         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6353         << D.getCXXScopeSpec().getRange();
6354       NewVD->setInvalidDecl();
6355     }
6356 
6357     if (!IsVariableTemplateSpecialization)
6358       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6359 
6360     // C++ Concepts TS [dcl.spec.concept]p7: A program shall not declare [...]
6361     // an explicit specialization (14.8.3) or a partial specialization of a
6362     // concept definition.
6363     if (IsVariableTemplateSpecialization &&
6364         !D.getDeclSpec().isConceptSpecified() && !Previous.empty() &&
6365         Previous.isSingleResult()) {
6366       NamedDecl *PreviousDecl = Previous.getFoundDecl();
6367       if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(PreviousDecl)) {
6368         if (VarTmpl->isConcept()) {
6369           Diag(NewVD->getLocation(), diag::err_concept_specialized)
6370               << 1                            /*variable*/
6371               << (IsPartialSpecialization ? 2 /*partially specialized*/
6372                                           : 1 /*explicitly specialized*/);
6373           Diag(VarTmpl->getLocation(), diag::note_previous_declaration);
6374           NewVD->setInvalidDecl();
6375         }
6376       }
6377     }
6378 
6379     if (NewTemplate) {
6380       VarTemplateDecl *PrevVarTemplate =
6381           NewVD->getPreviousDecl()
6382               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6383               : nullptr;
6384 
6385       // Check the template parameter list of this declaration, possibly
6386       // merging in the template parameter list from the previous variable
6387       // template declaration.
6388       if (CheckTemplateParameterList(
6389               TemplateParams,
6390               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6391                               : nullptr,
6392               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6393                DC->isDependentContext())
6394                   ? TPC_ClassTemplateMember
6395                   : TPC_VarTemplate))
6396         NewVD->setInvalidDecl();
6397 
6398       // If we are providing an explicit specialization of a static variable
6399       // template, make a note of that.
6400       if (PrevVarTemplate &&
6401           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6402         PrevVarTemplate->setMemberSpecialization();
6403     }
6404   }
6405 
6406   ProcessPragmaWeak(S, NewVD);
6407 
6408   // If this is the first declaration of an extern C variable, update
6409   // the map of such variables.
6410   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6411       isIncompleteDeclExternC(*this, NewVD))
6412     RegisterLocallyScopedExternCDecl(NewVD, S);
6413 
6414   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6415     Decl *ManglingContextDecl;
6416     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6417             NewVD->getDeclContext(), ManglingContextDecl)) {
6418       Context.setManglingNumber(
6419           NewVD, MCtx->getManglingNumber(
6420                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6421       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6422     }
6423   }
6424 
6425   // Special handling of variable named 'main'.
6426   if (Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main") &&
6427       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6428       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6429 
6430     // C++ [basic.start.main]p3
6431     // A program that declares a variable main at global scope is ill-formed.
6432     if (getLangOpts().CPlusPlus)
6433       Diag(D.getLocStart(), diag::err_main_global_variable);
6434 
6435     // In C, and external-linkage variable named main results in undefined
6436     // behavior.
6437     else if (NewVD->hasExternalFormalLinkage())
6438       Diag(D.getLocStart(), diag::warn_main_redefined);
6439   }
6440 
6441   if (D.isRedeclaration() && !Previous.empty()) {
6442     checkDLLAttributeRedeclaration(
6443         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6444         IsExplicitSpecialization, D.isFunctionDefinition());
6445   }
6446 
6447   if (NewTemplate) {
6448     if (NewVD->isInvalidDecl())
6449       NewTemplate->setInvalidDecl();
6450     ActOnDocumentableDecl(NewTemplate);
6451     return NewTemplate;
6452   }
6453 
6454   return NewVD;
6455 }
6456 
6457 /// Enum describing the %select options in diag::warn_decl_shadow.
6458 enum ShadowedDeclKind { SDK_Local, SDK_Global, SDK_StaticMember, SDK_Field };
6459 
6460 /// Determine what kind of declaration we're shadowing.
6461 static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl,
6462                                                 const DeclContext *OldDC) {
6463   if (isa<RecordDecl>(OldDC))
6464     return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
6465   return OldDC->isFileContext() ? SDK_Global : SDK_Local;
6466 }
6467 
6468 /// \brief Diagnose variable or built-in function shadowing.  Implements
6469 /// -Wshadow.
6470 ///
6471 /// This method is called whenever a VarDecl is added to a "useful"
6472 /// scope.
6473 ///
6474 /// \param S the scope in which the shadowing name is being declared
6475 /// \param R the lookup of the name
6476 ///
6477 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
6478   // Return if warning is ignored.
6479   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6480     return;
6481 
6482   // Don't diagnose declarations at file scope.
6483   if (D->hasGlobalStorage())
6484     return;
6485 
6486   DeclContext *NewDC = D->getDeclContext();
6487 
6488   // Only diagnose if we're shadowing an unambiguous field or variable.
6489   if (R.getResultKind() != LookupResult::Found)
6490     return;
6491 
6492   NamedDecl* ShadowedDecl = R.getFoundDecl();
6493   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
6494     return;
6495 
6496   if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
6497     // Fields are not shadowed by variables in C++ static methods.
6498     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6499       if (MD->isStatic())
6500         return;
6501 
6502     // Fields shadowed by constructor parameters are a special case. Usually
6503     // the constructor initializes the field with the parameter.
6504     if (isa<CXXConstructorDecl>(NewDC) && isa<ParmVarDecl>(D)) {
6505       // Remember that this was shadowed so we can either warn about its
6506       // modification or its existence depending on warning settings.
6507       D = D->getCanonicalDecl();
6508       ShadowingDecls.insert({D, FD});
6509       return;
6510     }
6511   }
6512 
6513   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6514     if (shadowedVar->isExternC()) {
6515       // For shadowing external vars, make sure that we point to the global
6516       // declaration, not a locally scoped extern declaration.
6517       for (auto I : shadowedVar->redecls())
6518         if (I->isFileVarDecl()) {
6519           ShadowedDecl = I;
6520           break;
6521         }
6522     }
6523 
6524   DeclContext *OldDC = ShadowedDecl->getDeclContext();
6525 
6526   // Only warn about certain kinds of shadowing for class members.
6527   if (NewDC && NewDC->isRecord()) {
6528     // In particular, don't warn about shadowing non-class members.
6529     if (!OldDC->isRecord())
6530       return;
6531 
6532     // TODO: should we warn about static data members shadowing
6533     // static data members from base classes?
6534 
6535     // TODO: don't diagnose for inaccessible shadowed members.
6536     // This is hard to do perfectly because we might friend the
6537     // shadowing context, but that's just a false negative.
6538   }
6539 
6540 
6541   DeclarationName Name = R.getLookupName();
6542 
6543   // Emit warning and note.
6544   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6545     return;
6546   ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
6547   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
6548   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6549 }
6550 
6551 /// \brief Check -Wshadow without the advantage of a previous lookup.
6552 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6553   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6554     return;
6555 
6556   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6557                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6558   LookupName(R, S);
6559   CheckShadow(S, D, R);
6560 }
6561 
6562 /// Check if 'E', which is an expression that is about to be modified, refers
6563 /// to a constructor parameter that shadows a field.
6564 void Sema::CheckShadowingDeclModification(Expr *E, SourceLocation Loc) {
6565   // Quickly ignore expressions that can't be shadowing ctor parameters.
6566   if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
6567     return;
6568   E = E->IgnoreParenImpCasts();
6569   auto *DRE = dyn_cast<DeclRefExpr>(E);
6570   if (!DRE)
6571     return;
6572   const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
6573   auto I = ShadowingDecls.find(D);
6574   if (I == ShadowingDecls.end())
6575     return;
6576   const NamedDecl *ShadowedDecl = I->second;
6577   const DeclContext *OldDC = ShadowedDecl->getDeclContext();
6578   Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
6579   Diag(D->getLocation(), diag::note_var_declared_here) << D;
6580   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6581 
6582   // Avoid issuing multiple warnings about the same decl.
6583   ShadowingDecls.erase(I);
6584 }
6585 
6586 /// Check for conflict between this global or extern "C" declaration and
6587 /// previous global or extern "C" declarations. This is only used in C++.
6588 template<typename T>
6589 static bool checkGlobalOrExternCConflict(
6590     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6591   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6592   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6593 
6594   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6595     // The common case: this global doesn't conflict with any extern "C"
6596     // declaration.
6597     return false;
6598   }
6599 
6600   if (Prev) {
6601     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6602       // Both the old and new declarations have C language linkage. This is a
6603       // redeclaration.
6604       Previous.clear();
6605       Previous.addDecl(Prev);
6606       return true;
6607     }
6608 
6609     // This is a global, non-extern "C" declaration, and there is a previous
6610     // non-global extern "C" declaration. Diagnose if this is a variable
6611     // declaration.
6612     if (!isa<VarDecl>(ND))
6613       return false;
6614   } else {
6615     // The declaration is extern "C". Check for any declaration in the
6616     // translation unit which might conflict.
6617     if (IsGlobal) {
6618       // We have already performed the lookup into the translation unit.
6619       IsGlobal = false;
6620       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6621            I != E; ++I) {
6622         if (isa<VarDecl>(*I)) {
6623           Prev = *I;
6624           break;
6625         }
6626       }
6627     } else {
6628       DeclContext::lookup_result R =
6629           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6630       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6631            I != E; ++I) {
6632         if (isa<VarDecl>(*I)) {
6633           Prev = *I;
6634           break;
6635         }
6636         // FIXME: If we have any other entity with this name in global scope,
6637         // the declaration is ill-formed, but that is a defect: it breaks the
6638         // 'stat' hack, for instance. Only variables can have mangled name
6639         // clashes with extern "C" declarations, so only they deserve a
6640         // diagnostic.
6641       }
6642     }
6643 
6644     if (!Prev)
6645       return false;
6646   }
6647 
6648   // Use the first declaration's location to ensure we point at something which
6649   // is lexically inside an extern "C" linkage-spec.
6650   assert(Prev && "should have found a previous declaration to diagnose");
6651   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6652     Prev = FD->getFirstDecl();
6653   else
6654     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6655 
6656   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6657     << IsGlobal << ND;
6658   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6659     << IsGlobal;
6660   return false;
6661 }
6662 
6663 /// Apply special rules for handling extern "C" declarations. Returns \c true
6664 /// if we have found that this is a redeclaration of some prior entity.
6665 ///
6666 /// Per C++ [dcl.link]p6:
6667 ///   Two declarations [for a function or variable] with C language linkage
6668 ///   with the same name that appear in different scopes refer to the same
6669 ///   [entity]. An entity with C language linkage shall not be declared with
6670 ///   the same name as an entity in global scope.
6671 template<typename T>
6672 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6673                                                   LookupResult &Previous) {
6674   if (!S.getLangOpts().CPlusPlus) {
6675     // In C, when declaring a global variable, look for a corresponding 'extern'
6676     // variable declared in function scope. We don't need this in C++, because
6677     // we find local extern decls in the surrounding file-scope DeclContext.
6678     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6679       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6680         Previous.clear();
6681         Previous.addDecl(Prev);
6682         return true;
6683       }
6684     }
6685     return false;
6686   }
6687 
6688   // A declaration in the translation unit can conflict with an extern "C"
6689   // declaration.
6690   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6691     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6692 
6693   // An extern "C" declaration can conflict with a declaration in the
6694   // translation unit or can be a redeclaration of an extern "C" declaration
6695   // in another scope.
6696   if (isIncompleteDeclExternC(S,ND))
6697     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6698 
6699   // Neither global nor extern "C": nothing to do.
6700   return false;
6701 }
6702 
6703 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6704   // If the decl is already known invalid, don't check it.
6705   if (NewVD->isInvalidDecl())
6706     return;
6707 
6708   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6709   QualType T = TInfo->getType();
6710 
6711   // Defer checking an 'auto' type until its initializer is attached.
6712   if (T->isUndeducedType())
6713     return;
6714 
6715   if (NewVD->hasAttrs())
6716     CheckAlignasUnderalignment(NewVD);
6717 
6718   if (T->isObjCObjectType()) {
6719     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6720       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6721     T = Context.getObjCObjectPointerType(T);
6722     NewVD->setType(T);
6723   }
6724 
6725   // Emit an error if an address space was applied to decl with local storage.
6726   // This includes arrays of objects with address space qualifiers, but not
6727   // automatic variables that point to other address spaces.
6728   // ISO/IEC TR 18037 S5.1.2
6729   if (!getLangOpts().OpenCL
6730       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6731     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6732     NewVD->setInvalidDecl();
6733     return;
6734   }
6735 
6736   // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
6737   // scope.
6738   if (getLangOpts().OpenCLVersion == 120 &&
6739       !getOpenCLOptions().cl_clang_storage_class_specifiers &&
6740       NewVD->isStaticLocal()) {
6741     Diag(NewVD->getLocation(), diag::err_static_function_scope);
6742     NewVD->setInvalidDecl();
6743     return;
6744   }
6745 
6746   if (getLangOpts().OpenCL) {
6747     // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
6748     if (NewVD->hasAttr<BlocksAttr>()) {
6749       Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
6750       return;
6751     }
6752 
6753     if (T->isBlockPointerType()) {
6754       // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
6755       // can't use 'extern' storage class.
6756       if (!T.isConstQualified()) {
6757         Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
6758             << 0 /*const*/;
6759         NewVD->setInvalidDecl();
6760         return;
6761       }
6762       if (NewVD->hasExternalStorage()) {
6763         Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
6764         NewVD->setInvalidDecl();
6765         return;
6766       }
6767       // OpenCL v2.0 s6.12.5 - Blocks with variadic arguments are not supported.
6768       // TODO: this check is not enough as it doesn't diagnose the typedef
6769       const BlockPointerType *BlkTy = T->getAs<BlockPointerType>();
6770       const FunctionProtoType *FTy =
6771           BlkTy->getPointeeType()->getAs<FunctionProtoType>();
6772       if (FTy && FTy->isVariadic()) {
6773         Diag(NewVD->getLocation(), diag::err_opencl_block_proto_variadic)
6774             << T << NewVD->getSourceRange();
6775         NewVD->setInvalidDecl();
6776         return;
6777       }
6778     }
6779     // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6780     // __constant address space.
6781     // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6782     // variables inside a function can also be declared in the global
6783     // address space.
6784     if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
6785         NewVD->hasExternalStorage()) {
6786       if (!T->isSamplerT() &&
6787           !(T.getAddressSpace() == LangAS::opencl_constant ||
6788             (T.getAddressSpace() == LangAS::opencl_global &&
6789              getLangOpts().OpenCLVersion == 200))) {
6790         int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
6791         if (getLangOpts().OpenCLVersion == 200)
6792           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6793               << Scope << "global or constant";
6794         else
6795           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6796               << Scope << "constant";
6797         NewVD->setInvalidDecl();
6798         return;
6799       }
6800     } else {
6801       if (T.getAddressSpace() == LangAS::opencl_global) {
6802         Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6803             << 1 /*is any function*/ << "global";
6804         NewVD->setInvalidDecl();
6805         return;
6806       }
6807       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
6808       // in functions.
6809       if (T.getAddressSpace() == LangAS::opencl_constant ||
6810           T.getAddressSpace() == LangAS::opencl_local) {
6811         FunctionDecl *FD = getCurFunctionDecl();
6812         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
6813           if (T.getAddressSpace() == LangAS::opencl_constant)
6814             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6815                 << 0 /*non-kernel only*/ << "constant";
6816           else
6817             Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
6818                 << 0 /*non-kernel only*/ << "local";
6819           NewVD->setInvalidDecl();
6820           return;
6821         }
6822       }
6823     }
6824   }
6825 
6826   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6827       && !NewVD->hasAttr<BlocksAttr>()) {
6828     if (getLangOpts().getGC() != LangOptions::NonGC)
6829       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6830     else {
6831       assert(!getLangOpts().ObjCAutoRefCount);
6832       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6833     }
6834   }
6835 
6836   bool isVM = T->isVariablyModifiedType();
6837   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6838       NewVD->hasAttr<BlocksAttr>())
6839     getCurFunction()->setHasBranchProtectedScope();
6840 
6841   if ((isVM && NewVD->hasLinkage()) ||
6842       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6843     bool SizeIsNegative;
6844     llvm::APSInt Oversized;
6845     TypeSourceInfo *FixedTInfo =
6846       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6847                                                     SizeIsNegative, Oversized);
6848     if (!FixedTInfo && T->isVariableArrayType()) {
6849       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6850       // FIXME: This won't give the correct result for
6851       // int a[10][n];
6852       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6853 
6854       if (NewVD->isFileVarDecl())
6855         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6856         << SizeRange;
6857       else if (NewVD->isStaticLocal())
6858         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6859         << SizeRange;
6860       else
6861         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6862         << SizeRange;
6863       NewVD->setInvalidDecl();
6864       return;
6865     }
6866 
6867     if (!FixedTInfo) {
6868       if (NewVD->isFileVarDecl())
6869         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6870       else
6871         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6872       NewVD->setInvalidDecl();
6873       return;
6874     }
6875 
6876     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6877     NewVD->setType(FixedTInfo->getType());
6878     NewVD->setTypeSourceInfo(FixedTInfo);
6879   }
6880 
6881   if (T->isVoidType()) {
6882     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6883     //                    of objects and functions.
6884     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6885       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6886         << T;
6887       NewVD->setInvalidDecl();
6888       return;
6889     }
6890   }
6891 
6892   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6893     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6894     NewVD->setInvalidDecl();
6895     return;
6896   }
6897 
6898   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6899     Diag(NewVD->getLocation(), diag::err_block_on_vm);
6900     NewVD->setInvalidDecl();
6901     return;
6902   }
6903 
6904   if (NewVD->isConstexpr() && !T->isDependentType() &&
6905       RequireLiteralType(NewVD->getLocation(), T,
6906                          diag::err_constexpr_var_non_literal)) {
6907     NewVD->setInvalidDecl();
6908     return;
6909   }
6910 }
6911 
6912 /// \brief Perform semantic checking on a newly-created variable
6913 /// declaration.
6914 ///
6915 /// This routine performs all of the type-checking required for a
6916 /// variable declaration once it has been built. It is used both to
6917 /// check variables after they have been parsed and their declarators
6918 /// have been translated into a declaration, and to check variables
6919 /// that have been instantiated from a template.
6920 ///
6921 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6922 ///
6923 /// Returns true if the variable declaration is a redeclaration.
6924 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6925   CheckVariableDeclarationType(NewVD);
6926 
6927   // If the decl is already known invalid, don't check it.
6928   if (NewVD->isInvalidDecl())
6929     return false;
6930 
6931   // If we did not find anything by this name, look for a non-visible
6932   // extern "C" declaration with the same name.
6933   if (Previous.empty() &&
6934       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6935     Previous.setShadowed();
6936 
6937   if (!Previous.empty()) {
6938     MergeVarDecl(NewVD, Previous);
6939     return true;
6940   }
6941   return false;
6942 }
6943 
6944 namespace {
6945 struct FindOverriddenMethod {
6946   Sema *S;
6947   CXXMethodDecl *Method;
6948 
6949   /// Member lookup function that determines whether a given C++
6950   /// method overrides a method in a base class, to be used with
6951   /// CXXRecordDecl::lookupInBases().
6952   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
6953     RecordDecl *BaseRecord =
6954         Specifier->getType()->getAs<RecordType>()->getDecl();
6955 
6956     DeclarationName Name = Method->getDeclName();
6957 
6958     // FIXME: Do we care about other names here too?
6959     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6960       // We really want to find the base class destructor here.
6961       QualType T = S->Context.getTypeDeclType(BaseRecord);
6962       CanQualType CT = S->Context.getCanonicalType(T);
6963 
6964       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
6965     }
6966 
6967     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
6968          Path.Decls = Path.Decls.slice(1)) {
6969       NamedDecl *D = Path.Decls.front();
6970       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6971         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
6972           return true;
6973       }
6974     }
6975 
6976     return false;
6977   }
6978 };
6979 
6980 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6981 } // end anonymous namespace
6982 
6983 /// \brief Report an error regarding overriding, along with any relevant
6984 /// overriden methods.
6985 ///
6986 /// \param DiagID the primary error to report.
6987 /// \param MD the overriding method.
6988 /// \param OEK which overrides to include as notes.
6989 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6990                             OverrideErrorKind OEK = OEK_All) {
6991   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6992   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6993                                       E = MD->end_overridden_methods();
6994        I != E; ++I) {
6995     // This check (& the OEK parameter) could be replaced by a predicate, but
6996     // without lambdas that would be overkill. This is still nicer than writing
6997     // out the diag loop 3 times.
6998     if ((OEK == OEK_All) ||
6999         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
7000         (OEK == OEK_Deleted && (*I)->isDeleted()))
7001       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
7002   }
7003 }
7004 
7005 /// AddOverriddenMethods - See if a method overrides any in the base classes,
7006 /// and if so, check that it's a valid override and remember it.
7007 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
7008   // Look for methods in base classes that this method might override.
7009   CXXBasePaths Paths;
7010   FindOverriddenMethod FOM;
7011   FOM.Method = MD;
7012   FOM.S = this;
7013   bool hasDeletedOverridenMethods = false;
7014   bool hasNonDeletedOverridenMethods = false;
7015   bool AddedAny = false;
7016   if (DC->lookupInBases(FOM, Paths)) {
7017     for (auto *I : Paths.found_decls()) {
7018       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
7019         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
7020         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
7021             !CheckOverridingFunctionAttributes(MD, OldMD) &&
7022             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
7023             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
7024           hasDeletedOverridenMethods |= OldMD->isDeleted();
7025           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
7026           AddedAny = true;
7027         }
7028       }
7029     }
7030   }
7031 
7032   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
7033     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
7034   }
7035   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
7036     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
7037   }
7038 
7039   return AddedAny;
7040 }
7041 
7042 namespace {
7043   // Struct for holding all of the extra arguments needed by
7044   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
7045   struct ActOnFDArgs {
7046     Scope *S;
7047     Declarator &D;
7048     MultiTemplateParamsArg TemplateParamLists;
7049     bool AddToScope;
7050   };
7051 } // end anonymous namespace
7052 
7053 namespace {
7054 
7055 // Callback to only accept typo corrections that have a non-zero edit distance.
7056 // Also only accept corrections that have the same parent decl.
7057 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
7058  public:
7059   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
7060                             CXXRecordDecl *Parent)
7061       : Context(Context), OriginalFD(TypoFD),
7062         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
7063 
7064   bool ValidateCandidate(const TypoCorrection &candidate) override {
7065     if (candidate.getEditDistance() == 0)
7066       return false;
7067 
7068     SmallVector<unsigned, 1> MismatchedParams;
7069     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
7070                                           CDeclEnd = candidate.end();
7071          CDecl != CDeclEnd; ++CDecl) {
7072       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7073 
7074       if (FD && !FD->hasBody() &&
7075           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
7076         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
7077           CXXRecordDecl *Parent = MD->getParent();
7078           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
7079             return true;
7080         } else if (!ExpectedParent) {
7081           return true;
7082         }
7083       }
7084     }
7085 
7086     return false;
7087   }
7088 
7089  private:
7090   ASTContext &Context;
7091   FunctionDecl *OriginalFD;
7092   CXXRecordDecl *ExpectedParent;
7093 };
7094 
7095 } // end anonymous namespace
7096 
7097 /// \brief Generate diagnostics for an invalid function redeclaration.
7098 ///
7099 /// This routine handles generating the diagnostic messages for an invalid
7100 /// function redeclaration, including finding possible similar declarations
7101 /// or performing typo correction if there are no previous declarations with
7102 /// the same name.
7103 ///
7104 /// Returns a NamedDecl iff typo correction was performed and substituting in
7105 /// the new declaration name does not cause new errors.
7106 static NamedDecl *DiagnoseInvalidRedeclaration(
7107     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
7108     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
7109   DeclarationName Name = NewFD->getDeclName();
7110   DeclContext *NewDC = NewFD->getDeclContext();
7111   SmallVector<unsigned, 1> MismatchedParams;
7112   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
7113   TypoCorrection Correction;
7114   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
7115   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
7116                                    : diag::err_member_decl_does_not_match;
7117   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
7118                     IsLocalFriend ? Sema::LookupLocalFriendName
7119                                   : Sema::LookupOrdinaryName,
7120                     Sema::ForRedeclaration);
7121 
7122   NewFD->setInvalidDecl();
7123   if (IsLocalFriend)
7124     SemaRef.LookupName(Prev, S);
7125   else
7126     SemaRef.LookupQualifiedName(Prev, NewDC);
7127   assert(!Prev.isAmbiguous() &&
7128          "Cannot have an ambiguity in previous-declaration lookup");
7129   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
7130   if (!Prev.empty()) {
7131     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
7132          Func != FuncEnd; ++Func) {
7133       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
7134       if (FD &&
7135           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7136         // Add 1 to the index so that 0 can mean the mismatch didn't
7137         // involve a parameter
7138         unsigned ParamNum =
7139             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
7140         NearMatches.push_back(std::make_pair(FD, ParamNum));
7141       }
7142     }
7143   // If the qualified name lookup yielded nothing, try typo correction
7144   } else if ((Correction = SemaRef.CorrectTypo(
7145                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
7146                   &ExtraArgs.D.getCXXScopeSpec(),
7147                   llvm::make_unique<DifferentNameValidatorCCC>(
7148                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
7149                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
7150     // Set up everything for the call to ActOnFunctionDeclarator
7151     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
7152                               ExtraArgs.D.getIdentifierLoc());
7153     Previous.clear();
7154     Previous.setLookupName(Correction.getCorrection());
7155     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
7156                                     CDeclEnd = Correction.end();
7157          CDecl != CDeclEnd; ++CDecl) {
7158       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
7159       if (FD && !FD->hasBody() &&
7160           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
7161         Previous.addDecl(FD);
7162       }
7163     }
7164     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
7165 
7166     NamedDecl *Result;
7167     // Retry building the function declaration with the new previous
7168     // declarations, and with errors suppressed.
7169     {
7170       // Trap errors.
7171       Sema::SFINAETrap Trap(SemaRef);
7172 
7173       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
7174       // pieces need to verify the typo-corrected C++ declaration and hopefully
7175       // eliminate the need for the parameter pack ExtraArgs.
7176       Result = SemaRef.ActOnFunctionDeclarator(
7177           ExtraArgs.S, ExtraArgs.D,
7178           Correction.getCorrectionDecl()->getDeclContext(),
7179           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
7180           ExtraArgs.AddToScope);
7181 
7182       if (Trap.hasErrorOccurred())
7183         Result = nullptr;
7184     }
7185 
7186     if (Result) {
7187       // Determine which correction we picked.
7188       Decl *Canonical = Result->getCanonicalDecl();
7189       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
7190            I != E; ++I)
7191         if ((*I)->getCanonicalDecl() == Canonical)
7192           Correction.setCorrectionDecl(*I);
7193 
7194       SemaRef.diagnoseTypo(
7195           Correction,
7196           SemaRef.PDiag(IsLocalFriend
7197                           ? diag::err_no_matching_local_friend_suggest
7198                           : diag::err_member_decl_does_not_match_suggest)
7199             << Name << NewDC << IsDefinition);
7200       return Result;
7201     }
7202 
7203     // Pretend the typo correction never occurred
7204     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
7205                               ExtraArgs.D.getIdentifierLoc());
7206     ExtraArgs.D.setRedeclaration(wasRedeclaration);
7207     Previous.clear();
7208     Previous.setLookupName(Name);
7209   }
7210 
7211   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
7212       << Name << NewDC << IsDefinition << NewFD->getLocation();
7213 
7214   bool NewFDisConst = false;
7215   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
7216     NewFDisConst = NewMD->isConst();
7217 
7218   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
7219        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
7220        NearMatch != NearMatchEnd; ++NearMatch) {
7221     FunctionDecl *FD = NearMatch->first;
7222     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7223     bool FDisConst = MD && MD->isConst();
7224     bool IsMember = MD || !IsLocalFriend;
7225 
7226     // FIXME: These notes are poorly worded for the local friend case.
7227     if (unsigned Idx = NearMatch->second) {
7228       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
7229       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
7230       if (Loc.isInvalid()) Loc = FD->getLocation();
7231       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
7232                                  : diag::note_local_decl_close_param_match)
7233         << Idx << FDParam->getType()
7234         << NewFD->getParamDecl(Idx - 1)->getType();
7235     } else if (FDisConst != NewFDisConst) {
7236       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
7237           << NewFDisConst << FD->getSourceRange().getEnd();
7238     } else
7239       SemaRef.Diag(FD->getLocation(),
7240                    IsMember ? diag::note_member_def_close_match
7241                             : diag::note_local_decl_close_match);
7242   }
7243   return nullptr;
7244 }
7245 
7246 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
7247   switch (D.getDeclSpec().getStorageClassSpec()) {
7248   default: llvm_unreachable("Unknown storage class!");
7249   case DeclSpec::SCS_auto:
7250   case DeclSpec::SCS_register:
7251   case DeclSpec::SCS_mutable:
7252     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7253                  diag::err_typecheck_sclass_func);
7254     D.setInvalidType();
7255     break;
7256   case DeclSpec::SCS_unspecified: break;
7257   case DeclSpec::SCS_extern:
7258     if (D.getDeclSpec().isExternInLinkageSpec())
7259       return SC_None;
7260     return SC_Extern;
7261   case DeclSpec::SCS_static: {
7262     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
7263       // C99 6.7.1p5:
7264       //   The declaration of an identifier for a function that has
7265       //   block scope shall have no explicit storage-class specifier
7266       //   other than extern
7267       // See also (C++ [dcl.stc]p4).
7268       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7269                    diag::err_static_block_func);
7270       break;
7271     } else
7272       return SC_Static;
7273   }
7274   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7275   }
7276 
7277   // No explicit storage class has already been returned
7278   return SC_None;
7279 }
7280 
7281 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7282                                            DeclContext *DC, QualType &R,
7283                                            TypeSourceInfo *TInfo,
7284                                            StorageClass SC,
7285                                            bool &IsVirtualOkay) {
7286   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7287   DeclarationName Name = NameInfo.getName();
7288 
7289   FunctionDecl *NewFD = nullptr;
7290   bool isInline = D.getDeclSpec().isInlineSpecified();
7291 
7292   if (!SemaRef.getLangOpts().CPlusPlus) {
7293     // Determine whether the function was written with a
7294     // prototype. This true when:
7295     //   - there is a prototype in the declarator, or
7296     //   - the type R of the function is some kind of typedef or other reference
7297     //     to a type name (which eventually refers to a function type).
7298     bool HasPrototype =
7299       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7300       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
7301 
7302     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7303                                  D.getLocStart(), NameInfo, R,
7304                                  TInfo, SC, isInline,
7305                                  HasPrototype, false);
7306     if (D.isInvalidType())
7307       NewFD->setInvalidDecl();
7308 
7309     return NewFD;
7310   }
7311 
7312   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7313   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7314 
7315   // Check that the return type is not an abstract class type.
7316   // For record types, this is done by the AbstractClassUsageDiagnoser once
7317   // the class has been completely parsed.
7318   if (!DC->isRecord() &&
7319       SemaRef.RequireNonAbstractType(
7320           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7321           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7322     D.setInvalidType();
7323 
7324   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7325     // This is a C++ constructor declaration.
7326     assert(DC->isRecord() &&
7327            "Constructors can only be declared in a member context");
7328 
7329     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7330     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7331                                       D.getLocStart(), NameInfo,
7332                                       R, TInfo, isExplicit, isInline,
7333                                       /*isImplicitlyDeclared=*/false,
7334                                       isConstexpr);
7335 
7336   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7337     // This is a C++ destructor declaration.
7338     if (DC->isRecord()) {
7339       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7340       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7341       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7342                                         SemaRef.Context, Record,
7343                                         D.getLocStart(),
7344                                         NameInfo, R, TInfo, isInline,
7345                                         /*isImplicitlyDeclared=*/false);
7346 
7347       // If the class is complete, then we now create the implicit exception
7348       // specification. If the class is incomplete or dependent, we can't do
7349       // it yet.
7350       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7351           Record->getDefinition() && !Record->isBeingDefined() &&
7352           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7353         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7354       }
7355 
7356       IsVirtualOkay = true;
7357       return NewDD;
7358 
7359     } else {
7360       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7361       D.setInvalidType();
7362 
7363       // Create a FunctionDecl to satisfy the function definition parsing
7364       // code path.
7365       return FunctionDecl::Create(SemaRef.Context, DC,
7366                                   D.getLocStart(),
7367                                   D.getIdentifierLoc(), Name, R, TInfo,
7368                                   SC, isInline,
7369                                   /*hasPrototype=*/true, isConstexpr);
7370     }
7371 
7372   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7373     if (!DC->isRecord()) {
7374       SemaRef.Diag(D.getIdentifierLoc(),
7375            diag::err_conv_function_not_member);
7376       return nullptr;
7377     }
7378 
7379     SemaRef.CheckConversionDeclarator(D, R, SC);
7380     IsVirtualOkay = true;
7381     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7382                                      D.getLocStart(), NameInfo,
7383                                      R, TInfo, isInline, isExplicit,
7384                                      isConstexpr, SourceLocation());
7385 
7386   } else if (DC->isRecord()) {
7387     // If the name of the function is the same as the name of the record,
7388     // then this must be an invalid constructor that has a return type.
7389     // (The parser checks for a return type and makes the declarator a
7390     // constructor if it has no return type).
7391     if (Name.getAsIdentifierInfo() &&
7392         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7393       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7394         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7395         << SourceRange(D.getIdentifierLoc());
7396       return nullptr;
7397     }
7398 
7399     // This is a C++ method declaration.
7400     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7401                                                cast<CXXRecordDecl>(DC),
7402                                                D.getLocStart(), NameInfo, R,
7403                                                TInfo, SC, isInline,
7404                                                isConstexpr, SourceLocation());
7405     IsVirtualOkay = !Ret->isStatic();
7406     return Ret;
7407   } else {
7408     bool isFriend =
7409         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7410     if (!isFriend && SemaRef.CurContext->isRecord())
7411       return nullptr;
7412 
7413     // Determine whether the function was written with a
7414     // prototype. This true when:
7415     //   - we're in C++ (where every function has a prototype),
7416     return FunctionDecl::Create(SemaRef.Context, DC,
7417                                 D.getLocStart(),
7418                                 NameInfo, R, TInfo, SC, isInline,
7419                                 true/*HasPrototype*/, isConstexpr);
7420   }
7421 }
7422 
7423 enum OpenCLParamType {
7424   ValidKernelParam,
7425   PtrPtrKernelParam,
7426   PtrKernelParam,
7427   PrivatePtrKernelParam,
7428   InvalidKernelParam,
7429   RecordKernelParam
7430 };
7431 
7432 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
7433   if (PT->isPointerType()) {
7434     QualType PointeeType = PT->getPointeeType();
7435     if (PointeeType->isPointerType())
7436       return PtrPtrKernelParam;
7437     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
7438                                               : PtrKernelParam;
7439   }
7440 
7441   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7442   // be used as builtin types.
7443 
7444   if (PT->isImageType())
7445     return PtrKernelParam;
7446 
7447   if (PT->isBooleanType())
7448     return InvalidKernelParam;
7449 
7450   if (PT->isEventT())
7451     return InvalidKernelParam;
7452 
7453   if (PT->isHalfType())
7454     return InvalidKernelParam;
7455 
7456   if (PT->isRecordType())
7457     return RecordKernelParam;
7458 
7459   return ValidKernelParam;
7460 }
7461 
7462 static void checkIsValidOpenCLKernelParameter(
7463   Sema &S,
7464   Declarator &D,
7465   ParmVarDecl *Param,
7466   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7467   QualType PT = Param->getType();
7468 
7469   // Cache the valid types we encounter to avoid rechecking structs that are
7470   // used again
7471   if (ValidTypes.count(PT.getTypePtr()))
7472     return;
7473 
7474   switch (getOpenCLKernelParameterType(PT)) {
7475   case PtrPtrKernelParam:
7476     // OpenCL v1.2 s6.9.a:
7477     // A kernel function argument cannot be declared as a
7478     // pointer to a pointer type.
7479     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7480     D.setInvalidType();
7481     return;
7482 
7483   case PrivatePtrKernelParam:
7484     // OpenCL v1.2 s6.9.a:
7485     // A kernel function argument cannot be declared as a
7486     // pointer to the private address space.
7487     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
7488     D.setInvalidType();
7489     return;
7490 
7491     // OpenCL v1.2 s6.9.k:
7492     // Arguments to kernel functions in a program cannot be declared with the
7493     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7494     // uintptr_t or a struct and/or union that contain fields declared to be
7495     // one of these built-in scalar types.
7496 
7497   case InvalidKernelParam:
7498     // OpenCL v1.2 s6.8 n:
7499     // A kernel function argument cannot be declared
7500     // of event_t type.
7501     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7502     D.setInvalidType();
7503     return;
7504 
7505   case PtrKernelParam:
7506   case ValidKernelParam:
7507     ValidTypes.insert(PT.getTypePtr());
7508     return;
7509 
7510   case RecordKernelParam:
7511     break;
7512   }
7513 
7514   // Track nested structs we will inspect
7515   SmallVector<const Decl *, 4> VisitStack;
7516 
7517   // Track where we are in the nested structs. Items will migrate from
7518   // VisitStack to HistoryStack as we do the DFS for bad field.
7519   SmallVector<const FieldDecl *, 4> HistoryStack;
7520   HistoryStack.push_back(nullptr);
7521 
7522   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7523   VisitStack.push_back(PD);
7524 
7525   assert(VisitStack.back() && "First decl null?");
7526 
7527   do {
7528     const Decl *Next = VisitStack.pop_back_val();
7529     if (!Next) {
7530       assert(!HistoryStack.empty());
7531       // Found a marker, we have gone up a level
7532       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7533         ValidTypes.insert(Hist->getType().getTypePtr());
7534 
7535       continue;
7536     }
7537 
7538     // Adds everything except the original parameter declaration (which is not a
7539     // field itself) to the history stack.
7540     const RecordDecl *RD;
7541     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7542       HistoryStack.push_back(Field);
7543       RD = Field->getType()->castAs<RecordType>()->getDecl();
7544     } else {
7545       RD = cast<RecordDecl>(Next);
7546     }
7547 
7548     // Add a null marker so we know when we've gone back up a level
7549     VisitStack.push_back(nullptr);
7550 
7551     for (const auto *FD : RD->fields()) {
7552       QualType QT = FD->getType();
7553 
7554       if (ValidTypes.count(QT.getTypePtr()))
7555         continue;
7556 
7557       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
7558       if (ParamType == ValidKernelParam)
7559         continue;
7560 
7561       if (ParamType == RecordKernelParam) {
7562         VisitStack.push_back(FD);
7563         continue;
7564       }
7565 
7566       // OpenCL v1.2 s6.9.p:
7567       // Arguments to kernel functions that are declared to be a struct or union
7568       // do not allow OpenCL objects to be passed as elements of the struct or
7569       // union.
7570       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7571           ParamType == PrivatePtrKernelParam) {
7572         S.Diag(Param->getLocation(),
7573                diag::err_record_with_pointers_kernel_param)
7574           << PT->isUnionType()
7575           << PT;
7576       } else {
7577         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7578       }
7579 
7580       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7581         << PD->getDeclName();
7582 
7583       // We have an error, now let's go back up through history and show where
7584       // the offending field came from
7585       for (ArrayRef<const FieldDecl *>::const_iterator
7586                I = HistoryStack.begin() + 1,
7587                E = HistoryStack.end();
7588            I != E; ++I) {
7589         const FieldDecl *OuterField = *I;
7590         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7591           << OuterField->getType();
7592       }
7593 
7594       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7595         << QT->isPointerType()
7596         << QT;
7597       D.setInvalidType();
7598       return;
7599     }
7600   } while (!VisitStack.empty());
7601 }
7602 
7603 NamedDecl*
7604 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7605                               TypeSourceInfo *TInfo, LookupResult &Previous,
7606                               MultiTemplateParamsArg TemplateParamLists,
7607                               bool &AddToScope) {
7608   QualType R = TInfo->getType();
7609 
7610   assert(R.getTypePtr()->isFunctionType());
7611 
7612   // TODO: consider using NameInfo for diagnostic.
7613   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7614   DeclarationName Name = NameInfo.getName();
7615   StorageClass SC = getFunctionStorageClass(*this, D);
7616 
7617   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7618     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7619          diag::err_invalid_thread)
7620       << DeclSpec::getSpecifierName(TSCS);
7621 
7622   if (D.isFirstDeclarationOfMember())
7623     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7624                            D.getIdentifierLoc());
7625 
7626   bool isFriend = false;
7627   FunctionTemplateDecl *FunctionTemplate = nullptr;
7628   bool isExplicitSpecialization = false;
7629   bool isFunctionTemplateSpecialization = false;
7630 
7631   bool isDependentClassScopeExplicitSpecialization = false;
7632   bool HasExplicitTemplateArgs = false;
7633   TemplateArgumentListInfo TemplateArgs;
7634 
7635   bool isVirtualOkay = false;
7636 
7637   DeclContext *OriginalDC = DC;
7638   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7639 
7640   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7641                                               isVirtualOkay);
7642   if (!NewFD) return nullptr;
7643 
7644   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7645     NewFD->setTopLevelDeclInObjCContainer();
7646 
7647   // Set the lexical context. If this is a function-scope declaration, or has a
7648   // C++ scope specifier, or is the object of a friend declaration, the lexical
7649   // context will be different from the semantic context.
7650   NewFD->setLexicalDeclContext(CurContext);
7651 
7652   if (IsLocalExternDecl)
7653     NewFD->setLocalExternDecl();
7654 
7655   if (getLangOpts().CPlusPlus) {
7656     bool isInline = D.getDeclSpec().isInlineSpecified();
7657     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7658     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7659     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7660     bool isConcept = D.getDeclSpec().isConceptSpecified();
7661     isFriend = D.getDeclSpec().isFriendSpecified();
7662     if (isFriend && !isInline && D.isFunctionDefinition()) {
7663       // C++ [class.friend]p5
7664       //   A function can be defined in a friend declaration of a
7665       //   class . . . . Such a function is implicitly inline.
7666       NewFD->setImplicitlyInline();
7667     }
7668 
7669     // If this is a method defined in an __interface, and is not a constructor
7670     // or an overloaded operator, then set the pure flag (isVirtual will already
7671     // return true).
7672     if (const CXXRecordDecl *Parent =
7673           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7674       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7675         NewFD->setPure(true);
7676 
7677       // C++ [class.union]p2
7678       //   A union can have member functions, but not virtual functions.
7679       if (isVirtual && Parent->isUnion())
7680         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7681     }
7682 
7683     SetNestedNameSpecifier(NewFD, D);
7684     isExplicitSpecialization = false;
7685     isFunctionTemplateSpecialization = false;
7686     if (D.isInvalidType())
7687       NewFD->setInvalidDecl();
7688 
7689     // Match up the template parameter lists with the scope specifier, then
7690     // determine whether we have a template or a template specialization.
7691     bool Invalid = false;
7692     if (TemplateParameterList *TemplateParams =
7693             MatchTemplateParametersToScopeSpecifier(
7694                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7695                 D.getCXXScopeSpec(),
7696                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7697                     ? D.getName().TemplateId
7698                     : nullptr,
7699                 TemplateParamLists, isFriend, isExplicitSpecialization,
7700                 Invalid)) {
7701       if (TemplateParams->size() > 0) {
7702         // This is a function template
7703 
7704         // Check that we can declare a template here.
7705         if (CheckTemplateDeclScope(S, TemplateParams))
7706           NewFD->setInvalidDecl();
7707 
7708         // A destructor cannot be a template.
7709         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7710           Diag(NewFD->getLocation(), diag::err_destructor_template);
7711           NewFD->setInvalidDecl();
7712         }
7713 
7714         // If we're adding a template to a dependent context, we may need to
7715         // rebuilding some of the types used within the template parameter list,
7716         // now that we know what the current instantiation is.
7717         if (DC->isDependentContext()) {
7718           ContextRAII SavedContext(*this, DC);
7719           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7720             Invalid = true;
7721         }
7722 
7723         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7724                                                         NewFD->getLocation(),
7725                                                         Name, TemplateParams,
7726                                                         NewFD);
7727         FunctionTemplate->setLexicalDeclContext(CurContext);
7728         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7729 
7730         // For source fidelity, store the other template param lists.
7731         if (TemplateParamLists.size() > 1) {
7732           NewFD->setTemplateParameterListsInfo(Context,
7733                                                TemplateParamLists.drop_back(1));
7734         }
7735       } else {
7736         // This is a function template specialization.
7737         isFunctionTemplateSpecialization = true;
7738         // For source fidelity, store all the template param lists.
7739         if (TemplateParamLists.size() > 0)
7740           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7741 
7742         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7743         if (isFriend) {
7744           // We want to remove the "template<>", found here.
7745           SourceRange RemoveRange = TemplateParams->getSourceRange();
7746 
7747           // If we remove the template<> and the name is not a
7748           // template-id, we're actually silently creating a problem:
7749           // the friend declaration will refer to an untemplated decl,
7750           // and clearly the user wants a template specialization.  So
7751           // we need to insert '<>' after the name.
7752           SourceLocation InsertLoc;
7753           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7754             InsertLoc = D.getName().getSourceRange().getEnd();
7755             InsertLoc = getLocForEndOfToken(InsertLoc);
7756           }
7757 
7758           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7759             << Name << RemoveRange
7760             << FixItHint::CreateRemoval(RemoveRange)
7761             << FixItHint::CreateInsertion(InsertLoc, "<>");
7762         }
7763       }
7764     }
7765     else {
7766       // All template param lists were matched against the scope specifier:
7767       // this is NOT (an explicit specialization of) a template.
7768       if (TemplateParamLists.size() > 0)
7769         // For source fidelity, store all the template param lists.
7770         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7771     }
7772 
7773     if (Invalid) {
7774       NewFD->setInvalidDecl();
7775       if (FunctionTemplate)
7776         FunctionTemplate->setInvalidDecl();
7777     }
7778 
7779     // C++ [dcl.fct.spec]p5:
7780     //   The virtual specifier shall only be used in declarations of
7781     //   nonstatic class member functions that appear within a
7782     //   member-specification of a class declaration; see 10.3.
7783     //
7784     if (isVirtual && !NewFD->isInvalidDecl()) {
7785       if (!isVirtualOkay) {
7786         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7787              diag::err_virtual_non_function);
7788       } else if (!CurContext->isRecord()) {
7789         // 'virtual' was specified outside of the class.
7790         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7791              diag::err_virtual_out_of_class)
7792           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7793       } else if (NewFD->getDescribedFunctionTemplate()) {
7794         // C++ [temp.mem]p3:
7795         //  A member function template shall not be virtual.
7796         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7797              diag::err_virtual_member_function_template)
7798           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7799       } else {
7800         // Okay: Add virtual to the method.
7801         NewFD->setVirtualAsWritten(true);
7802       }
7803 
7804       if (getLangOpts().CPlusPlus14 &&
7805           NewFD->getReturnType()->isUndeducedType())
7806         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7807     }
7808 
7809     if (getLangOpts().CPlusPlus14 &&
7810         (NewFD->isDependentContext() ||
7811          (isFriend && CurContext->isDependentContext())) &&
7812         NewFD->getReturnType()->isUndeducedType()) {
7813       // If the function template is referenced directly (for instance, as a
7814       // member of the current instantiation), pretend it has a dependent type.
7815       // This is not really justified by the standard, but is the only sane
7816       // thing to do.
7817       // FIXME: For a friend function, we have not marked the function as being
7818       // a friend yet, so 'isDependentContext' on the FD doesn't work.
7819       const FunctionProtoType *FPT =
7820           NewFD->getType()->castAs<FunctionProtoType>();
7821       QualType Result =
7822           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7823       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7824                                              FPT->getExtProtoInfo()));
7825     }
7826 
7827     // C++ [dcl.fct.spec]p3:
7828     //  The inline specifier shall not appear on a block scope function
7829     //  declaration.
7830     if (isInline && !NewFD->isInvalidDecl()) {
7831       if (CurContext->isFunctionOrMethod()) {
7832         // 'inline' is not allowed on block scope function declaration.
7833         Diag(D.getDeclSpec().getInlineSpecLoc(),
7834              diag::err_inline_declaration_block_scope) << Name
7835           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7836       }
7837     }
7838 
7839     // C++ [dcl.fct.spec]p6:
7840     //  The explicit specifier shall be used only in the declaration of a
7841     //  constructor or conversion function within its class definition;
7842     //  see 12.3.1 and 12.3.2.
7843     if (isExplicit && !NewFD->isInvalidDecl()) {
7844       if (!CurContext->isRecord()) {
7845         // 'explicit' was specified outside of the class.
7846         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7847              diag::err_explicit_out_of_class)
7848           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7849       } else if (!isa<CXXConstructorDecl>(NewFD) &&
7850                  !isa<CXXConversionDecl>(NewFD)) {
7851         // 'explicit' was specified on a function that wasn't a constructor
7852         // or conversion function.
7853         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7854              diag::err_explicit_non_ctor_or_conv_function)
7855           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7856       }
7857     }
7858 
7859     if (isConstexpr) {
7860       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7861       // are implicitly inline.
7862       NewFD->setImplicitlyInline();
7863 
7864       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7865       // be either constructors or to return a literal type. Therefore,
7866       // destructors cannot be declared constexpr.
7867       if (isa<CXXDestructorDecl>(NewFD))
7868         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7869     }
7870 
7871     if (isConcept) {
7872       // This is a function concept.
7873       if (FunctionTemplateDecl *FTD = NewFD->getDescribedFunctionTemplate())
7874         FTD->setConcept();
7875 
7876       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7877       // applied only to the definition of a function template [...]
7878       if (!D.isFunctionDefinition()) {
7879         Diag(D.getDeclSpec().getConceptSpecLoc(),
7880              diag::err_function_concept_not_defined);
7881         NewFD->setInvalidDecl();
7882       }
7883 
7884       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
7885       // have no exception-specification and is treated as if it were specified
7886       // with noexcept(true) (15.4). [...]
7887       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
7888         if (FPT->hasExceptionSpec()) {
7889           SourceRange Range;
7890           if (D.isFunctionDeclarator())
7891             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
7892           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
7893               << FixItHint::CreateRemoval(Range);
7894           NewFD->setInvalidDecl();
7895         } else {
7896           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
7897         }
7898 
7899         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7900         // following restrictions:
7901         // - The declared return type shall have the type bool.
7902         if (!Context.hasSameType(FPT->getReturnType(), Context.BoolTy)) {
7903           Diag(D.getIdentifierLoc(), diag::err_function_concept_bool_ret);
7904           NewFD->setInvalidDecl();
7905         }
7906 
7907         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7908         // following restrictions:
7909         // - The declaration's parameter list shall be equivalent to an empty
7910         //   parameter list.
7911         if (FPT->getNumParams() > 0 || FPT->isVariadic())
7912           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
7913       }
7914 
7915       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
7916       // implicity defined to be a constexpr declaration (implicitly inline)
7917       NewFD->setImplicitlyInline();
7918 
7919       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
7920       // be declared with the thread_local, inline, friend, or constexpr
7921       // specifiers, [...]
7922       if (isInline) {
7923         Diag(D.getDeclSpec().getInlineSpecLoc(),
7924              diag::err_concept_decl_invalid_specifiers)
7925             << 1 << 1;
7926         NewFD->setInvalidDecl(true);
7927       }
7928 
7929       if (isFriend) {
7930         Diag(D.getDeclSpec().getFriendSpecLoc(),
7931              diag::err_concept_decl_invalid_specifiers)
7932             << 1 << 2;
7933         NewFD->setInvalidDecl(true);
7934       }
7935 
7936       if (isConstexpr) {
7937         Diag(D.getDeclSpec().getConstexprSpecLoc(),
7938              diag::err_concept_decl_invalid_specifiers)
7939             << 1 << 3;
7940         NewFD->setInvalidDecl(true);
7941       }
7942 
7943       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7944       // applied only to the definition of a function template or variable
7945       // template, declared in namespace scope.
7946       if (isFunctionTemplateSpecialization) {
7947         Diag(D.getDeclSpec().getConceptSpecLoc(),
7948              diag::err_concept_specified_specialization) << 1;
7949         NewFD->setInvalidDecl(true);
7950         return NewFD;
7951       }
7952     }
7953 
7954     // If __module_private__ was specified, mark the function accordingly.
7955     if (D.getDeclSpec().isModulePrivateSpecified()) {
7956       if (isFunctionTemplateSpecialization) {
7957         SourceLocation ModulePrivateLoc
7958           = D.getDeclSpec().getModulePrivateSpecLoc();
7959         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
7960           << 0
7961           << FixItHint::CreateRemoval(ModulePrivateLoc);
7962       } else {
7963         NewFD->setModulePrivate();
7964         if (FunctionTemplate)
7965           FunctionTemplate->setModulePrivate();
7966       }
7967     }
7968 
7969     if (isFriend) {
7970       if (FunctionTemplate) {
7971         FunctionTemplate->setObjectOfFriendDecl();
7972         FunctionTemplate->setAccess(AS_public);
7973       }
7974       NewFD->setObjectOfFriendDecl();
7975       NewFD->setAccess(AS_public);
7976     }
7977 
7978     // If a function is defined as defaulted or deleted, mark it as such now.
7979     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
7980     // definition kind to FDK_Definition.
7981     switch (D.getFunctionDefinitionKind()) {
7982       case FDK_Declaration:
7983       case FDK_Definition:
7984         break;
7985 
7986       case FDK_Defaulted:
7987         NewFD->setDefaulted();
7988         break;
7989 
7990       case FDK_Deleted:
7991         NewFD->setDeletedAsWritten();
7992         break;
7993     }
7994 
7995     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
7996         D.isFunctionDefinition()) {
7997       // C++ [class.mfct]p2:
7998       //   A member function may be defined (8.4) in its class definition, in
7999       //   which case it is an inline member function (7.1.2)
8000       NewFD->setImplicitlyInline();
8001     }
8002 
8003     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
8004         !CurContext->isRecord()) {
8005       // C++ [class.static]p1:
8006       //   A data or function member of a class may be declared static
8007       //   in a class definition, in which case it is a static member of
8008       //   the class.
8009 
8010       // Complain about the 'static' specifier if it's on an out-of-line
8011       // member function definition.
8012       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8013            diag::err_static_out_of_line)
8014         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
8015     }
8016 
8017     // C++11 [except.spec]p15:
8018     //   A deallocation function with no exception-specification is treated
8019     //   as if it were specified with noexcept(true).
8020     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
8021     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
8022          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
8023         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
8024       NewFD->setType(Context.getFunctionType(
8025           FPT->getReturnType(), FPT->getParamTypes(),
8026           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
8027   }
8028 
8029   // Filter out previous declarations that don't match the scope.
8030   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
8031                        D.getCXXScopeSpec().isNotEmpty() ||
8032                        isExplicitSpecialization ||
8033                        isFunctionTemplateSpecialization);
8034 
8035   // Handle GNU asm-label extension (encoded as an attribute).
8036   if (Expr *E = (Expr*) D.getAsmLabel()) {
8037     // The parser guarantees this is a string.
8038     StringLiteral *SE = cast<StringLiteral>(E);
8039     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
8040                                                 SE->getString(), 0));
8041   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
8042     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
8043       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
8044     if (I != ExtnameUndeclaredIdentifiers.end()) {
8045       if (isDeclExternC(NewFD)) {
8046         NewFD->addAttr(I->second);
8047         ExtnameUndeclaredIdentifiers.erase(I);
8048       } else
8049         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
8050             << /*Variable*/0 << NewFD;
8051     }
8052   }
8053 
8054   // Copy the parameter declarations from the declarator D to the function
8055   // declaration NewFD, if they are available.  First scavenge them into Params.
8056   SmallVector<ParmVarDecl*, 16> Params;
8057   if (D.isFunctionDeclarator()) {
8058     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8059 
8060     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
8061     // function that takes no arguments, not a function that takes a
8062     // single void argument.
8063     // We let through "const void" here because Sema::GetTypeForDeclarator
8064     // already checks for that case.
8065     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
8066       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
8067         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
8068         assert(Param->getDeclContext() != NewFD && "Was set before ?");
8069         Param->setDeclContext(NewFD);
8070         Params.push_back(Param);
8071 
8072         if (Param->isInvalidDecl())
8073           NewFD->setInvalidDecl();
8074       }
8075     }
8076   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
8077     // When we're declaring a function with a typedef, typeof, etc as in the
8078     // following example, we'll need to synthesize (unnamed)
8079     // parameters for use in the declaration.
8080     //
8081     // @code
8082     // typedef void fn(int);
8083     // fn f;
8084     // @endcode
8085 
8086     // Synthesize a parameter for each argument type.
8087     for (const auto &AI : FT->param_types()) {
8088       ParmVarDecl *Param =
8089           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
8090       Param->setScopeInfo(0, Params.size());
8091       Params.push_back(Param);
8092     }
8093   } else {
8094     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
8095            "Should not need args for typedef of non-prototype fn");
8096   }
8097 
8098   // Finally, we know we have the right number of parameters, install them.
8099   NewFD->setParams(Params);
8100 
8101   // Find all anonymous symbols defined during the declaration of this function
8102   // and add to NewFD. This lets us track decls such 'enum Y' in:
8103   //
8104   //   void f(enum Y {AA} x) {}
8105   //
8106   // which would otherwise incorrectly end up in the translation unit scope.
8107   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
8108   DeclsInPrototypeScope.clear();
8109 
8110   if (D.getDeclSpec().isNoreturnSpecified())
8111     NewFD->addAttr(
8112         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
8113                                        Context, 0));
8114 
8115   // Functions returning a variably modified type violate C99 6.7.5.2p2
8116   // because all functions have linkage.
8117   if (!NewFD->isInvalidDecl() &&
8118       NewFD->getReturnType()->isVariablyModifiedType()) {
8119     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
8120     NewFD->setInvalidDecl();
8121   }
8122 
8123   // Apply an implicit SectionAttr if #pragma code_seg is active.
8124   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
8125       !NewFD->hasAttr<SectionAttr>()) {
8126     NewFD->addAttr(
8127         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
8128                                     CodeSegStack.CurrentValue->getString(),
8129                                     CodeSegStack.CurrentPragmaLocation));
8130     if (UnifySection(CodeSegStack.CurrentValue->getString(),
8131                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
8132                          ASTContext::PSF_Read,
8133                      NewFD))
8134       NewFD->dropAttr<SectionAttr>();
8135   }
8136 
8137   // Handle attributes.
8138   ProcessDeclAttributes(S, NewFD, D);
8139 
8140   if (getLangOpts().CUDA)
8141     maybeAddCUDAHostDeviceAttrs(S, NewFD, Previous);
8142 
8143   if (getLangOpts().OpenCL) {
8144     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
8145     // type declaration will generate a compilation error.
8146     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
8147     if (AddressSpace == LangAS::opencl_local ||
8148         AddressSpace == LangAS::opencl_global ||
8149         AddressSpace == LangAS::opencl_constant) {
8150       Diag(NewFD->getLocation(),
8151            diag::err_opencl_return_value_with_address_space);
8152       NewFD->setInvalidDecl();
8153     }
8154   }
8155 
8156   if (!getLangOpts().CPlusPlus) {
8157     // Perform semantic checking on the function declaration.
8158     bool isExplicitSpecialization=false;
8159     if (!NewFD->isInvalidDecl() && NewFD->isMain())
8160       CheckMain(NewFD, D.getDeclSpec());
8161 
8162     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8163       CheckMSVCRTEntryPoint(NewFD);
8164 
8165     if (!NewFD->isInvalidDecl())
8166       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8167                                                   isExplicitSpecialization));
8168     else if (!Previous.empty())
8169       // Recover gracefully from an invalid redeclaration.
8170       D.setRedeclaration(true);
8171     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8172             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8173            "previous declaration set still overloaded");
8174 
8175     // Diagnose no-prototype function declarations with calling conventions that
8176     // don't support variadic calls. Only do this in C and do it after merging
8177     // possibly prototyped redeclarations.
8178     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
8179     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
8180       CallingConv CC = FT->getExtInfo().getCC();
8181       if (!supportsVariadicCall(CC)) {
8182         // Windows system headers sometimes accidentally use stdcall without
8183         // (void) parameters, so we relax this to a warning.
8184         int DiagID =
8185             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
8186         Diag(NewFD->getLocation(), DiagID)
8187             << FunctionType::getNameForCallConv(CC);
8188       }
8189     }
8190   } else {
8191     // C++11 [replacement.functions]p3:
8192     //  The program's definitions shall not be specified as inline.
8193     //
8194     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
8195     //
8196     // Suppress the diagnostic if the function is __attribute__((used)), since
8197     // that forces an external definition to be emitted.
8198     if (D.getDeclSpec().isInlineSpecified() &&
8199         NewFD->isReplaceableGlobalAllocationFunction() &&
8200         !NewFD->hasAttr<UsedAttr>())
8201       Diag(D.getDeclSpec().getInlineSpecLoc(),
8202            diag::ext_operator_new_delete_declared_inline)
8203         << NewFD->getDeclName();
8204 
8205     // If the declarator is a template-id, translate the parser's template
8206     // argument list into our AST format.
8207     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
8208       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
8209       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
8210       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
8211       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
8212                                          TemplateId->NumArgs);
8213       translateTemplateArguments(TemplateArgsPtr,
8214                                  TemplateArgs);
8215 
8216       HasExplicitTemplateArgs = true;
8217 
8218       if (NewFD->isInvalidDecl()) {
8219         HasExplicitTemplateArgs = false;
8220       } else if (FunctionTemplate) {
8221         // Function template with explicit template arguments.
8222         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
8223           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
8224 
8225         HasExplicitTemplateArgs = false;
8226       } else {
8227         assert((isFunctionTemplateSpecialization ||
8228                 D.getDeclSpec().isFriendSpecified()) &&
8229                "should have a 'template<>' for this decl");
8230         // "friend void foo<>(int);" is an implicit specialization decl.
8231         isFunctionTemplateSpecialization = true;
8232       }
8233     } else if (isFriend && isFunctionTemplateSpecialization) {
8234       // This combination is only possible in a recovery case;  the user
8235       // wrote something like:
8236       //   template <> friend void foo(int);
8237       // which we're recovering from as if the user had written:
8238       //   friend void foo<>(int);
8239       // Go ahead and fake up a template id.
8240       HasExplicitTemplateArgs = true;
8241       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
8242       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
8243     }
8244 
8245     // If it's a friend (and only if it's a friend), it's possible
8246     // that either the specialized function type or the specialized
8247     // template is dependent, and therefore matching will fail.  In
8248     // this case, don't check the specialization yet.
8249     bool InstantiationDependent = false;
8250     if (isFunctionTemplateSpecialization && isFriend &&
8251         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
8252          TemplateSpecializationType::anyDependentTemplateArguments(
8253             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
8254             InstantiationDependent))) {
8255       assert(HasExplicitTemplateArgs &&
8256              "friend function specialization without template args");
8257       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
8258                                                        Previous))
8259         NewFD->setInvalidDecl();
8260     } else if (isFunctionTemplateSpecialization) {
8261       if (CurContext->isDependentContext() && CurContext->isRecord()
8262           && !isFriend) {
8263         isDependentClassScopeExplicitSpecialization = true;
8264         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
8265           diag::ext_function_specialization_in_class :
8266           diag::err_function_specialization_in_class)
8267           << NewFD->getDeclName();
8268       } else if (CheckFunctionTemplateSpecialization(NewFD,
8269                                   (HasExplicitTemplateArgs ? &TemplateArgs
8270                                                            : nullptr),
8271                                                      Previous))
8272         NewFD->setInvalidDecl();
8273 
8274       // C++ [dcl.stc]p1:
8275       //   A storage-class-specifier shall not be specified in an explicit
8276       //   specialization (14.7.3)
8277       FunctionTemplateSpecializationInfo *Info =
8278           NewFD->getTemplateSpecializationInfo();
8279       if (Info && SC != SC_None) {
8280         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
8281           Diag(NewFD->getLocation(),
8282                diag::err_explicit_specialization_inconsistent_storage_class)
8283             << SC
8284             << FixItHint::CreateRemoval(
8285                                       D.getDeclSpec().getStorageClassSpecLoc());
8286 
8287         else
8288           Diag(NewFD->getLocation(),
8289                diag::ext_explicit_specialization_storage_class)
8290             << FixItHint::CreateRemoval(
8291                                       D.getDeclSpec().getStorageClassSpecLoc());
8292       }
8293     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
8294       if (CheckMemberSpecialization(NewFD, Previous))
8295           NewFD->setInvalidDecl();
8296     }
8297 
8298     // Perform semantic checking on the function declaration.
8299     if (!isDependentClassScopeExplicitSpecialization) {
8300       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8301         CheckMain(NewFD, D.getDeclSpec());
8302 
8303       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8304         CheckMSVCRTEntryPoint(NewFD);
8305 
8306       if (!NewFD->isInvalidDecl())
8307         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8308                                                     isExplicitSpecialization));
8309       else if (!Previous.empty())
8310         // Recover gracefully from an invalid redeclaration.
8311         D.setRedeclaration(true);
8312     }
8313 
8314     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8315             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8316            "previous declaration set still overloaded");
8317 
8318     NamedDecl *PrincipalDecl = (FunctionTemplate
8319                                 ? cast<NamedDecl>(FunctionTemplate)
8320                                 : NewFD);
8321 
8322     if (isFriend && D.isRedeclaration()) {
8323       AccessSpecifier Access = AS_public;
8324       if (!NewFD->isInvalidDecl())
8325         Access = NewFD->getPreviousDecl()->getAccess();
8326 
8327       NewFD->setAccess(Access);
8328       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8329     }
8330 
8331     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8332         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8333       PrincipalDecl->setNonMemberOperator();
8334 
8335     // If we have a function template, check the template parameter
8336     // list. This will check and merge default template arguments.
8337     if (FunctionTemplate) {
8338       FunctionTemplateDecl *PrevTemplate =
8339                                      FunctionTemplate->getPreviousDecl();
8340       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8341                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8342                                     : nullptr,
8343                             D.getDeclSpec().isFriendSpecified()
8344                               ? (D.isFunctionDefinition()
8345                                    ? TPC_FriendFunctionTemplateDefinition
8346                                    : TPC_FriendFunctionTemplate)
8347                               : (D.getCXXScopeSpec().isSet() &&
8348                                  DC && DC->isRecord() &&
8349                                  DC->isDependentContext())
8350                                   ? TPC_ClassTemplateMember
8351                                   : TPC_FunctionTemplate);
8352     }
8353 
8354     if (NewFD->isInvalidDecl()) {
8355       // Ignore all the rest of this.
8356     } else if (!D.isRedeclaration()) {
8357       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8358                                        AddToScope };
8359       // Fake up an access specifier if it's supposed to be a class member.
8360       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8361         NewFD->setAccess(AS_public);
8362 
8363       // Qualified decls generally require a previous declaration.
8364       if (D.getCXXScopeSpec().isSet()) {
8365         // ...with the major exception of templated-scope or
8366         // dependent-scope friend declarations.
8367 
8368         // TODO: we currently also suppress this check in dependent
8369         // contexts because (1) the parameter depth will be off when
8370         // matching friend templates and (2) we might actually be
8371         // selecting a friend based on a dependent factor.  But there
8372         // are situations where these conditions don't apply and we
8373         // can actually do this check immediately.
8374         if (isFriend &&
8375             (TemplateParamLists.size() ||
8376              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8377              CurContext->isDependentContext())) {
8378           // ignore these
8379         } else {
8380           // The user tried to provide an out-of-line definition for a
8381           // function that is a member of a class or namespace, but there
8382           // was no such member function declared (C++ [class.mfct]p2,
8383           // C++ [namespace.memdef]p2). For example:
8384           //
8385           // class X {
8386           //   void f() const;
8387           // };
8388           //
8389           // void X::f() { } // ill-formed
8390           //
8391           // Complain about this problem, and attempt to suggest close
8392           // matches (e.g., those that differ only in cv-qualifiers and
8393           // whether the parameter types are references).
8394 
8395           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8396                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8397             AddToScope = ExtraArgs.AddToScope;
8398             return Result;
8399           }
8400         }
8401 
8402         // Unqualified local friend declarations are required to resolve
8403         // to something.
8404       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8405         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8406                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8407           AddToScope = ExtraArgs.AddToScope;
8408           return Result;
8409         }
8410       }
8411     } else if (!D.isFunctionDefinition() &&
8412                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8413                !isFriend && !isFunctionTemplateSpecialization &&
8414                !isExplicitSpecialization) {
8415       // An out-of-line member function declaration must also be a
8416       // definition (C++ [class.mfct]p2).
8417       // Note that this is not the case for explicit specializations of
8418       // function templates or member functions of class templates, per
8419       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8420       // extension for compatibility with old SWIG code which likes to
8421       // generate them.
8422       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8423         << D.getCXXScopeSpec().getRange();
8424     }
8425   }
8426 
8427   ProcessPragmaWeak(S, NewFD);
8428   checkAttributesAfterMerging(*this, *NewFD);
8429 
8430   AddKnownFunctionAttributes(NewFD);
8431 
8432   if (NewFD->hasAttr<OverloadableAttr>() &&
8433       !NewFD->getType()->getAs<FunctionProtoType>()) {
8434     Diag(NewFD->getLocation(),
8435          diag::err_attribute_overloadable_no_prototype)
8436       << NewFD;
8437 
8438     // Turn this into a variadic function with no parameters.
8439     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8440     FunctionProtoType::ExtProtoInfo EPI(
8441         Context.getDefaultCallingConvention(true, false));
8442     EPI.Variadic = true;
8443     EPI.ExtInfo = FT->getExtInfo();
8444 
8445     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8446     NewFD->setType(R);
8447   }
8448 
8449   // If there's a #pragma GCC visibility in scope, and this isn't a class
8450   // member, set the visibility of this function.
8451   if (!DC->isRecord() && NewFD->isExternallyVisible())
8452     AddPushedVisibilityAttribute(NewFD);
8453 
8454   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8455   // marking the function.
8456   AddCFAuditedAttribute(NewFD);
8457 
8458   // If this is a function definition, check if we have to apply optnone due to
8459   // a pragma.
8460   if(D.isFunctionDefinition())
8461     AddRangeBasedOptnone(NewFD);
8462 
8463   // If this is the first declaration of an extern C variable, update
8464   // the map of such variables.
8465   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8466       isIncompleteDeclExternC(*this, NewFD))
8467     RegisterLocallyScopedExternCDecl(NewFD, S);
8468 
8469   // Set this FunctionDecl's range up to the right paren.
8470   NewFD->setRangeEnd(D.getSourceRange().getEnd());
8471 
8472   if (D.isRedeclaration() && !Previous.empty()) {
8473     checkDLLAttributeRedeclaration(
8474         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8475         isExplicitSpecialization || isFunctionTemplateSpecialization,
8476         D.isFunctionDefinition());
8477   }
8478 
8479   if (getLangOpts().CUDA) {
8480     IdentifierInfo *II = NewFD->getIdentifier();
8481     if (II && II->isStr("cudaConfigureCall") && !NewFD->isInvalidDecl() &&
8482         NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8483       if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8484         Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8485 
8486       Context.setcudaConfigureCallDecl(NewFD);
8487     }
8488 
8489     // Variadic functions, other than a *declaration* of printf, are not allowed
8490     // in device-side CUDA code, unless someone passed
8491     // -fcuda-allow-variadic-functions.
8492     if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
8493         (NewFD->hasAttr<CUDADeviceAttr>() ||
8494          NewFD->hasAttr<CUDAGlobalAttr>()) &&
8495         !(II && II->isStr("printf") && NewFD->isExternC() &&
8496           !D.isFunctionDefinition())) {
8497       Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
8498     }
8499   }
8500 
8501   if (getLangOpts().CPlusPlus) {
8502     if (FunctionTemplate) {
8503       if (NewFD->isInvalidDecl())
8504         FunctionTemplate->setInvalidDecl();
8505       return FunctionTemplate;
8506     }
8507   }
8508 
8509   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8510     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8511     if ((getLangOpts().OpenCLVersion >= 120)
8512         && (SC == SC_Static)) {
8513       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8514       D.setInvalidType();
8515     }
8516 
8517     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8518     if (!NewFD->getReturnType()->isVoidType()) {
8519       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8520       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8521           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8522                                 : FixItHint());
8523       D.setInvalidType();
8524     }
8525 
8526     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8527     for (auto Param : NewFD->params())
8528       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8529   }
8530   for (FunctionDecl::param_iterator PI = NewFD->param_begin(),
8531        PE = NewFD->param_end(); PI != PE; ++PI) {
8532     ParmVarDecl *Param = *PI;
8533     QualType PT = Param->getType();
8534 
8535     // OpenCL 2.0 pipe restrictions forbids pipe packet types to be non-value
8536     // types.
8537     if (getLangOpts().OpenCLVersion >= 200) {
8538       if(const PipeType *PipeTy = PT->getAs<PipeType>()) {
8539         QualType ElemTy = PipeTy->getElementType();
8540           if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
8541             Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
8542             D.setInvalidType();
8543           }
8544       }
8545     }
8546   }
8547 
8548   MarkUnusedFileScopedDecl(NewFD);
8549 
8550   // Here we have an function template explicit specialization at class scope.
8551   // The actually specialization will be postponed to template instatiation
8552   // time via the ClassScopeFunctionSpecializationDecl node.
8553   if (isDependentClassScopeExplicitSpecialization) {
8554     ClassScopeFunctionSpecializationDecl *NewSpec =
8555                          ClassScopeFunctionSpecializationDecl::Create(
8556                                 Context, CurContext, SourceLocation(),
8557                                 cast<CXXMethodDecl>(NewFD),
8558                                 HasExplicitTemplateArgs, TemplateArgs);
8559     CurContext->addDecl(NewSpec);
8560     AddToScope = false;
8561   }
8562 
8563   return NewFD;
8564 }
8565 
8566 /// \brief Perform semantic checking of a new function declaration.
8567 ///
8568 /// Performs semantic analysis of the new function declaration
8569 /// NewFD. This routine performs all semantic checking that does not
8570 /// require the actual declarator involved in the declaration, and is
8571 /// used both for the declaration of functions as they are parsed
8572 /// (called via ActOnDeclarator) and for the declaration of functions
8573 /// that have been instantiated via C++ template instantiation (called
8574 /// via InstantiateDecl).
8575 ///
8576 /// \param IsExplicitSpecialization whether this new function declaration is
8577 /// an explicit specialization of the previous declaration.
8578 ///
8579 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8580 ///
8581 /// \returns true if the function declaration is a redeclaration.
8582 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8583                                     LookupResult &Previous,
8584                                     bool IsExplicitSpecialization) {
8585   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8586          "Variably modified return types are not handled here");
8587 
8588   // Determine whether the type of this function should be merged with
8589   // a previous visible declaration. This never happens for functions in C++,
8590   // and always happens in C if the previous declaration was visible.
8591   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8592                                !Previous.isShadowed();
8593 
8594   bool Redeclaration = false;
8595   NamedDecl *OldDecl = nullptr;
8596 
8597   // Merge or overload the declaration with an existing declaration of
8598   // the same name, if appropriate.
8599   if (!Previous.empty()) {
8600     // Determine whether NewFD is an overload of PrevDecl or
8601     // a declaration that requires merging. If it's an overload,
8602     // there's no more work to do here; we'll just add the new
8603     // function to the scope.
8604     if (!AllowOverloadingOfFunction(Previous, Context)) {
8605       NamedDecl *Candidate = Previous.getRepresentativeDecl();
8606       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8607         Redeclaration = true;
8608         OldDecl = Candidate;
8609       }
8610     } else {
8611       switch (CheckOverload(S, NewFD, Previous, OldDecl,
8612                             /*NewIsUsingDecl*/ false)) {
8613       case Ovl_Match:
8614         Redeclaration = true;
8615         break;
8616 
8617       case Ovl_NonFunction:
8618         Redeclaration = true;
8619         break;
8620 
8621       case Ovl_Overload:
8622         Redeclaration = false;
8623         break;
8624       }
8625 
8626       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8627         // If a function name is overloadable in C, then every function
8628         // with that name must be marked "overloadable".
8629         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8630           << Redeclaration << NewFD;
8631         NamedDecl *OverloadedDecl = nullptr;
8632         if (Redeclaration)
8633           OverloadedDecl = OldDecl;
8634         else if (!Previous.empty())
8635           OverloadedDecl = Previous.getRepresentativeDecl();
8636         if (OverloadedDecl)
8637           Diag(OverloadedDecl->getLocation(),
8638                diag::note_attribute_overloadable_prev_overload);
8639         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8640       }
8641     }
8642   }
8643 
8644   // Check for a previous extern "C" declaration with this name.
8645   if (!Redeclaration &&
8646       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8647     if (!Previous.empty()) {
8648       // This is an extern "C" declaration with the same name as a previous
8649       // declaration, and thus redeclares that entity...
8650       Redeclaration = true;
8651       OldDecl = Previous.getFoundDecl();
8652       MergeTypeWithPrevious = false;
8653 
8654       // ... except in the presence of __attribute__((overloadable)).
8655       if (OldDecl->hasAttr<OverloadableAttr>()) {
8656         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8657           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8658             << Redeclaration << NewFD;
8659           Diag(Previous.getFoundDecl()->getLocation(),
8660                diag::note_attribute_overloadable_prev_overload);
8661           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8662         }
8663         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8664           Redeclaration = false;
8665           OldDecl = nullptr;
8666         }
8667       }
8668     }
8669   }
8670 
8671   // C++11 [dcl.constexpr]p8:
8672   //   A constexpr specifier for a non-static member function that is not
8673   //   a constructor declares that member function to be const.
8674   //
8675   // This needs to be delayed until we know whether this is an out-of-line
8676   // definition of a static member function.
8677   //
8678   // This rule is not present in C++1y, so we produce a backwards
8679   // compatibility warning whenever it happens in C++11.
8680   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8681   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8682       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8683       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8684     CXXMethodDecl *OldMD = nullptr;
8685     if (OldDecl)
8686       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8687     if (!OldMD || !OldMD->isStatic()) {
8688       const FunctionProtoType *FPT =
8689         MD->getType()->castAs<FunctionProtoType>();
8690       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8691       EPI.TypeQuals |= Qualifiers::Const;
8692       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8693                                           FPT->getParamTypes(), EPI));
8694 
8695       // Warn that we did this, if we're not performing template instantiation.
8696       // In that case, we'll have warned already when the template was defined.
8697       if (ActiveTemplateInstantiations.empty()) {
8698         SourceLocation AddConstLoc;
8699         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
8700                 .IgnoreParens().getAs<FunctionTypeLoc>())
8701           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
8702 
8703         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
8704           << FixItHint::CreateInsertion(AddConstLoc, " const");
8705       }
8706     }
8707   }
8708 
8709   if (Redeclaration) {
8710     // NewFD and OldDecl represent declarations that need to be
8711     // merged.
8712     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
8713       NewFD->setInvalidDecl();
8714       return Redeclaration;
8715     }
8716 
8717     Previous.clear();
8718     Previous.addDecl(OldDecl);
8719 
8720     if (FunctionTemplateDecl *OldTemplateDecl
8721                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
8722       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
8723       FunctionTemplateDecl *NewTemplateDecl
8724         = NewFD->getDescribedFunctionTemplate();
8725       assert(NewTemplateDecl && "Template/non-template mismatch");
8726       if (CXXMethodDecl *Method
8727             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
8728         Method->setAccess(OldTemplateDecl->getAccess());
8729         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8730       }
8731 
8732       // If this is an explicit specialization of a member that is a function
8733       // template, mark it as a member specialization.
8734       if (IsExplicitSpecialization &&
8735           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
8736         NewTemplateDecl->setMemberSpecialization();
8737         assert(OldTemplateDecl->isMemberSpecialization());
8738         // Explicit specializations of a member template do not inherit deleted
8739         // status from the parent member template that they are specializing.
8740         if (OldTemplateDecl->getTemplatedDecl()->isDeleted()) {
8741           FunctionDecl *const OldTemplatedDecl =
8742               OldTemplateDecl->getTemplatedDecl();
8743           assert(OldTemplatedDecl->getCanonicalDecl() == OldTemplatedDecl);
8744           OldTemplatedDecl->setDeletedAsWritten(false);
8745         }
8746       }
8747 
8748     } else {
8749       // This needs to happen first so that 'inline' propagates.
8750       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
8751 
8752       if (isa<CXXMethodDecl>(NewFD))
8753         NewFD->setAccess(OldDecl->getAccess());
8754     }
8755   }
8756 
8757   // Semantic checking for this function declaration (in isolation).
8758 
8759   if (getLangOpts().CPlusPlus) {
8760     // C++-specific checks.
8761     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
8762       CheckConstructor(Constructor);
8763     } else if (CXXDestructorDecl *Destructor =
8764                 dyn_cast<CXXDestructorDecl>(NewFD)) {
8765       CXXRecordDecl *Record = Destructor->getParent();
8766       QualType ClassType = Context.getTypeDeclType(Record);
8767 
8768       // FIXME: Shouldn't we be able to perform this check even when the class
8769       // type is dependent? Both gcc and edg can handle that.
8770       if (!ClassType->isDependentType()) {
8771         DeclarationName Name
8772           = Context.DeclarationNames.getCXXDestructorName(
8773                                         Context.getCanonicalType(ClassType));
8774         if (NewFD->getDeclName() != Name) {
8775           Diag(NewFD->getLocation(), diag::err_destructor_name);
8776           NewFD->setInvalidDecl();
8777           return Redeclaration;
8778         }
8779       }
8780     } else if (CXXConversionDecl *Conversion
8781                = dyn_cast<CXXConversionDecl>(NewFD)) {
8782       ActOnConversionDeclarator(Conversion);
8783     }
8784 
8785     // Find any virtual functions that this function overrides.
8786     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8787       if (!Method->isFunctionTemplateSpecialization() &&
8788           !Method->getDescribedFunctionTemplate() &&
8789           Method->isCanonicalDecl()) {
8790         if (AddOverriddenMethods(Method->getParent(), Method)) {
8791           // If the function was marked as "static", we have a problem.
8792           if (NewFD->getStorageClass() == SC_Static) {
8793             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8794           }
8795         }
8796       }
8797 
8798       if (Method->isStatic())
8799         checkThisInStaticMemberFunctionType(Method);
8800     }
8801 
8802     // Extra checking for C++ overloaded operators (C++ [over.oper]).
8803     if (NewFD->isOverloadedOperator() &&
8804         CheckOverloadedOperatorDeclaration(NewFD)) {
8805       NewFD->setInvalidDecl();
8806       return Redeclaration;
8807     }
8808 
8809     // Extra checking for C++0x literal operators (C++0x [over.literal]).
8810     if (NewFD->getLiteralIdentifier() &&
8811         CheckLiteralOperatorDeclaration(NewFD)) {
8812       NewFD->setInvalidDecl();
8813       return Redeclaration;
8814     }
8815 
8816     // In C++, check default arguments now that we have merged decls. Unless
8817     // the lexical context is the class, because in this case this is done
8818     // during delayed parsing anyway.
8819     if (!CurContext->isRecord())
8820       CheckCXXDefaultArguments(NewFD);
8821 
8822     // If this function declares a builtin function, check the type of this
8823     // declaration against the expected type for the builtin.
8824     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8825       ASTContext::GetBuiltinTypeError Error;
8826       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8827       QualType T = Context.GetBuiltinType(BuiltinID, Error);
8828       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8829         // The type of this function differs from the type of the builtin,
8830         // so forget about the builtin entirely.
8831         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
8832       }
8833     }
8834 
8835     // If this function is declared as being extern "C", then check to see if
8836     // the function returns a UDT (class, struct, or union type) that is not C
8837     // compatible, and if it does, warn the user.
8838     // But, issue any diagnostic on the first declaration only.
8839     if (Previous.empty() && NewFD->isExternC()) {
8840       QualType R = NewFD->getReturnType();
8841       if (R->isIncompleteType() && !R->isVoidType())
8842         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8843             << NewFD << R;
8844       else if (!R.isPODType(Context) && !R->isVoidType() &&
8845                !R->isObjCObjectPointerType())
8846         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8847     }
8848   }
8849   return Redeclaration;
8850 }
8851 
8852 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8853   // C++11 [basic.start.main]p3:
8854   //   A program that [...] declares main to be inline, static or
8855   //   constexpr is ill-formed.
8856   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
8857   //   appear in a declaration of main.
8858   // static main is not an error under C99, but we should warn about it.
8859   // We accept _Noreturn main as an extension.
8860   if (FD->getStorageClass() == SC_Static)
8861     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8862          ? diag::err_static_main : diag::warn_static_main)
8863       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8864   if (FD->isInlineSpecified())
8865     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8866       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8867   if (DS.isNoreturnSpecified()) {
8868     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8869     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8870     Diag(NoreturnLoc, diag::ext_noreturn_main);
8871     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8872       << FixItHint::CreateRemoval(NoreturnRange);
8873   }
8874   if (FD->isConstexpr()) {
8875     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8876       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8877     FD->setConstexpr(false);
8878   }
8879 
8880   if (getLangOpts().OpenCL) {
8881     Diag(FD->getLocation(), diag::err_opencl_no_main)
8882         << FD->hasAttr<OpenCLKernelAttr>();
8883     FD->setInvalidDecl();
8884     return;
8885   }
8886 
8887   QualType T = FD->getType();
8888   assert(T->isFunctionType() && "function decl is not of function type");
8889   const FunctionType* FT = T->castAs<FunctionType>();
8890 
8891   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8892     // In C with GNU extensions we allow main() to have non-integer return
8893     // type, but we should warn about the extension, and we disable the
8894     // implicit-return-zero rule.
8895 
8896     // GCC in C mode accepts qualified 'int'.
8897     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8898       FD->setHasImplicitReturnZero(true);
8899     else {
8900       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8901       SourceRange RTRange = FD->getReturnTypeSourceRange();
8902       if (RTRange.isValid())
8903         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8904             << FixItHint::CreateReplacement(RTRange, "int");
8905     }
8906   } else {
8907     // In C and C++, main magically returns 0 if you fall off the end;
8908     // set the flag which tells us that.
8909     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8910 
8911     // All the standards say that main() should return 'int'.
8912     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8913       FD->setHasImplicitReturnZero(true);
8914     else {
8915       // Otherwise, this is just a flat-out error.
8916       SourceRange RTRange = FD->getReturnTypeSourceRange();
8917       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8918           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8919                                 : FixItHint());
8920       FD->setInvalidDecl(true);
8921     }
8922   }
8923 
8924   // Treat protoless main() as nullary.
8925   if (isa<FunctionNoProtoType>(FT)) return;
8926 
8927   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8928   unsigned nparams = FTP->getNumParams();
8929   assert(FD->getNumParams() == nparams);
8930 
8931   bool HasExtraParameters = (nparams > 3);
8932 
8933   if (FTP->isVariadic()) {
8934     Diag(FD->getLocation(), diag::ext_variadic_main);
8935     // FIXME: if we had information about the location of the ellipsis, we
8936     // could add a FixIt hint to remove it as a parameter.
8937   }
8938 
8939   // Darwin passes an undocumented fourth argument of type char**.  If
8940   // other platforms start sprouting these, the logic below will start
8941   // getting shifty.
8942   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8943     HasExtraParameters = false;
8944 
8945   if (HasExtraParameters) {
8946     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8947     FD->setInvalidDecl(true);
8948     nparams = 3;
8949   }
8950 
8951   // FIXME: a lot of the following diagnostics would be improved
8952   // if we had some location information about types.
8953 
8954   QualType CharPP =
8955     Context.getPointerType(Context.getPointerType(Context.CharTy));
8956   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
8957 
8958   for (unsigned i = 0; i < nparams; ++i) {
8959     QualType AT = FTP->getParamType(i);
8960 
8961     bool mismatch = true;
8962 
8963     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
8964       mismatch = false;
8965     else if (Expected[i] == CharPP) {
8966       // As an extension, the following forms are okay:
8967       //   char const **
8968       //   char const * const *
8969       //   char * const *
8970 
8971       QualifierCollector qs;
8972       const PointerType* PT;
8973       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
8974           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
8975           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
8976                               Context.CharTy)) {
8977         qs.removeConst();
8978         mismatch = !qs.empty();
8979       }
8980     }
8981 
8982     if (mismatch) {
8983       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
8984       // TODO: suggest replacing given type with expected type
8985       FD->setInvalidDecl(true);
8986     }
8987   }
8988 
8989   if (nparams == 1 && !FD->isInvalidDecl()) {
8990     Diag(FD->getLocation(), diag::warn_main_one_arg);
8991   }
8992 
8993   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8994     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8995     FD->setInvalidDecl();
8996   }
8997 }
8998 
8999 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
9000   QualType T = FD->getType();
9001   assert(T->isFunctionType() && "function decl is not of function type");
9002   const FunctionType *FT = T->castAs<FunctionType>();
9003 
9004   // Set an implicit return of 'zero' if the function can return some integral,
9005   // enumeration, pointer or nullptr type.
9006   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
9007       FT->getReturnType()->isAnyPointerType() ||
9008       FT->getReturnType()->isNullPtrType())
9009     // DllMain is exempt because a return value of zero means it failed.
9010     if (FD->getName() != "DllMain")
9011       FD->setHasImplicitReturnZero(true);
9012 
9013   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
9014     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
9015     FD->setInvalidDecl();
9016   }
9017 }
9018 
9019 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
9020   // FIXME: Need strict checking.  In C89, we need to check for
9021   // any assignment, increment, decrement, function-calls, or
9022   // commas outside of a sizeof.  In C99, it's the same list,
9023   // except that the aforementioned are allowed in unevaluated
9024   // expressions.  Everything else falls under the
9025   // "may accept other forms of constant expressions" exception.
9026   // (We never end up here for C++, so the constant expression
9027   // rules there don't matter.)
9028   const Expr *Culprit;
9029   if (Init->isConstantInitializer(Context, false, &Culprit))
9030     return false;
9031   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
9032     << Culprit->getSourceRange();
9033   return true;
9034 }
9035 
9036 namespace {
9037   // Visits an initialization expression to see if OrigDecl is evaluated in
9038   // its own initialization and throws a warning if it does.
9039   class SelfReferenceChecker
9040       : public EvaluatedExprVisitor<SelfReferenceChecker> {
9041     Sema &S;
9042     Decl *OrigDecl;
9043     bool isRecordType;
9044     bool isPODType;
9045     bool isReferenceType;
9046 
9047     bool isInitList;
9048     llvm::SmallVector<unsigned, 4> InitFieldIndex;
9049 
9050   public:
9051     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
9052 
9053     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
9054                                                     S(S), OrigDecl(OrigDecl) {
9055       isPODType = false;
9056       isRecordType = false;
9057       isReferenceType = false;
9058       isInitList = false;
9059       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
9060         isPODType = VD->getType().isPODType(S.Context);
9061         isRecordType = VD->getType()->isRecordType();
9062         isReferenceType = VD->getType()->isReferenceType();
9063       }
9064     }
9065 
9066     // For most expressions, just call the visitor.  For initializer lists,
9067     // track the index of the field being initialized since fields are
9068     // initialized in order allowing use of previously initialized fields.
9069     void CheckExpr(Expr *E) {
9070       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
9071       if (!InitList) {
9072         Visit(E);
9073         return;
9074       }
9075 
9076       // Track and increment the index here.
9077       isInitList = true;
9078       InitFieldIndex.push_back(0);
9079       for (auto Child : InitList->children()) {
9080         CheckExpr(cast<Expr>(Child));
9081         ++InitFieldIndex.back();
9082       }
9083       InitFieldIndex.pop_back();
9084     }
9085 
9086     // Returns true if MemberExpr is checked and no futher checking is needed.
9087     // Returns false if additional checking is required.
9088     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
9089       llvm::SmallVector<FieldDecl*, 4> Fields;
9090       Expr *Base = E;
9091       bool ReferenceField = false;
9092 
9093       // Get the field memebers used.
9094       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9095         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
9096         if (!FD)
9097           return false;
9098         Fields.push_back(FD);
9099         if (FD->getType()->isReferenceType())
9100           ReferenceField = true;
9101         Base = ME->getBase()->IgnoreParenImpCasts();
9102       }
9103 
9104       // Keep checking only if the base Decl is the same.
9105       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
9106       if (!DRE || DRE->getDecl() != OrigDecl)
9107         return false;
9108 
9109       // A reference field can be bound to an unininitialized field.
9110       if (CheckReference && !ReferenceField)
9111         return true;
9112 
9113       // Convert FieldDecls to their index number.
9114       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
9115       for (const FieldDecl *I : llvm::reverse(Fields))
9116         UsedFieldIndex.push_back(I->getFieldIndex());
9117 
9118       // See if a warning is needed by checking the first difference in index
9119       // numbers.  If field being used has index less than the field being
9120       // initialized, then the use is safe.
9121       for (auto UsedIter = UsedFieldIndex.begin(),
9122                 UsedEnd = UsedFieldIndex.end(),
9123                 OrigIter = InitFieldIndex.begin(),
9124                 OrigEnd = InitFieldIndex.end();
9125            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
9126         if (*UsedIter < *OrigIter)
9127           return true;
9128         if (*UsedIter > *OrigIter)
9129           break;
9130       }
9131 
9132       // TODO: Add a different warning which will print the field names.
9133       HandleDeclRefExpr(DRE);
9134       return true;
9135     }
9136 
9137     // For most expressions, the cast is directly above the DeclRefExpr.
9138     // For conditional operators, the cast can be outside the conditional
9139     // operator if both expressions are DeclRefExpr's.
9140     void HandleValue(Expr *E) {
9141       E = E->IgnoreParens();
9142       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
9143         HandleDeclRefExpr(DRE);
9144         return;
9145       }
9146 
9147       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9148         Visit(CO->getCond());
9149         HandleValue(CO->getTrueExpr());
9150         HandleValue(CO->getFalseExpr());
9151         return;
9152       }
9153 
9154       if (BinaryConditionalOperator *BCO =
9155               dyn_cast<BinaryConditionalOperator>(E)) {
9156         Visit(BCO->getCond());
9157         HandleValue(BCO->getFalseExpr());
9158         return;
9159       }
9160 
9161       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
9162         HandleValue(OVE->getSourceExpr());
9163         return;
9164       }
9165 
9166       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
9167         if (BO->getOpcode() == BO_Comma) {
9168           Visit(BO->getLHS());
9169           HandleValue(BO->getRHS());
9170           return;
9171         }
9172       }
9173 
9174       if (isa<MemberExpr>(E)) {
9175         if (isInitList) {
9176           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
9177                                       false /*CheckReference*/))
9178             return;
9179         }
9180 
9181         Expr *Base = E->IgnoreParenImpCasts();
9182         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9183           // Check for static member variables and don't warn on them.
9184           if (!isa<FieldDecl>(ME->getMemberDecl()))
9185             return;
9186           Base = ME->getBase()->IgnoreParenImpCasts();
9187         }
9188         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
9189           HandleDeclRefExpr(DRE);
9190         return;
9191       }
9192 
9193       Visit(E);
9194     }
9195 
9196     // Reference types not handled in HandleValue are handled here since all
9197     // uses of references are bad, not just r-value uses.
9198     void VisitDeclRefExpr(DeclRefExpr *E) {
9199       if (isReferenceType)
9200         HandleDeclRefExpr(E);
9201     }
9202 
9203     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
9204       if (E->getCastKind() == CK_LValueToRValue) {
9205         HandleValue(E->getSubExpr());
9206         return;
9207       }
9208 
9209       Inherited::VisitImplicitCastExpr(E);
9210     }
9211 
9212     void VisitMemberExpr(MemberExpr *E) {
9213       if (isInitList) {
9214         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
9215           return;
9216       }
9217 
9218       // Don't warn on arrays since they can be treated as pointers.
9219       if (E->getType()->canDecayToPointerType()) return;
9220 
9221       // Warn when a non-static method call is followed by non-static member
9222       // field accesses, which is followed by a DeclRefExpr.
9223       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
9224       bool Warn = (MD && !MD->isStatic());
9225       Expr *Base = E->getBase()->IgnoreParenImpCasts();
9226       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
9227         if (!isa<FieldDecl>(ME->getMemberDecl()))
9228           Warn = false;
9229         Base = ME->getBase()->IgnoreParenImpCasts();
9230       }
9231 
9232       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
9233         if (Warn)
9234           HandleDeclRefExpr(DRE);
9235         return;
9236       }
9237 
9238       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
9239       // Visit that expression.
9240       Visit(Base);
9241     }
9242 
9243     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
9244       Expr *Callee = E->getCallee();
9245 
9246       if (isa<UnresolvedLookupExpr>(Callee))
9247         return Inherited::VisitCXXOperatorCallExpr(E);
9248 
9249       Visit(Callee);
9250       for (auto Arg: E->arguments())
9251         HandleValue(Arg->IgnoreParenImpCasts());
9252     }
9253 
9254     void VisitUnaryOperator(UnaryOperator *E) {
9255       // For POD record types, addresses of its own members are well-defined.
9256       if (E->getOpcode() == UO_AddrOf && isRecordType &&
9257           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
9258         if (!isPODType)
9259           HandleValue(E->getSubExpr());
9260         return;
9261       }
9262 
9263       if (E->isIncrementDecrementOp()) {
9264         HandleValue(E->getSubExpr());
9265         return;
9266       }
9267 
9268       Inherited::VisitUnaryOperator(E);
9269     }
9270 
9271     void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
9272 
9273     void VisitCXXConstructExpr(CXXConstructExpr *E) {
9274       if (E->getConstructor()->isCopyConstructor()) {
9275         Expr *ArgExpr = E->getArg(0);
9276         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
9277           if (ILE->getNumInits() == 1)
9278             ArgExpr = ILE->getInit(0);
9279         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
9280           if (ICE->getCastKind() == CK_NoOp)
9281             ArgExpr = ICE->getSubExpr();
9282         HandleValue(ArgExpr);
9283         return;
9284       }
9285       Inherited::VisitCXXConstructExpr(E);
9286     }
9287 
9288     void VisitCallExpr(CallExpr *E) {
9289       // Treat std::move as a use.
9290       if (E->getNumArgs() == 1) {
9291         if (FunctionDecl *FD = E->getDirectCallee()) {
9292           if (FD->isInStdNamespace() && FD->getIdentifier() &&
9293               FD->getIdentifier()->isStr("move")) {
9294             HandleValue(E->getArg(0));
9295             return;
9296           }
9297         }
9298       }
9299 
9300       Inherited::VisitCallExpr(E);
9301     }
9302 
9303     void VisitBinaryOperator(BinaryOperator *E) {
9304       if (E->isCompoundAssignmentOp()) {
9305         HandleValue(E->getLHS());
9306         Visit(E->getRHS());
9307         return;
9308       }
9309 
9310       Inherited::VisitBinaryOperator(E);
9311     }
9312 
9313     // A custom visitor for BinaryConditionalOperator is needed because the
9314     // regular visitor would check the condition and true expression separately
9315     // but both point to the same place giving duplicate diagnostics.
9316     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
9317       Visit(E->getCond());
9318       Visit(E->getFalseExpr());
9319     }
9320 
9321     void HandleDeclRefExpr(DeclRefExpr *DRE) {
9322       Decl* ReferenceDecl = DRE->getDecl();
9323       if (OrigDecl != ReferenceDecl) return;
9324       unsigned diag;
9325       if (isReferenceType) {
9326         diag = diag::warn_uninit_self_reference_in_reference_init;
9327       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9328         diag = diag::warn_static_self_reference_in_init;
9329       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9330                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9331                  DRE->getDecl()->getType()->isRecordType()) {
9332         diag = diag::warn_uninit_self_reference_in_init;
9333       } else {
9334         // Local variables will be handled by the CFG analysis.
9335         return;
9336       }
9337 
9338       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9339                             S.PDiag(diag)
9340                               << DRE->getNameInfo().getName()
9341                               << OrigDecl->getLocation()
9342                               << DRE->getSourceRange());
9343     }
9344   };
9345 
9346   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9347   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9348                                  bool DirectInit) {
9349     // Parameters arguments are occassionially constructed with itself,
9350     // for instance, in recursive functions.  Skip them.
9351     if (isa<ParmVarDecl>(OrigDecl))
9352       return;
9353 
9354     E = E->IgnoreParens();
9355 
9356     // Skip checking T a = a where T is not a record or reference type.
9357     // Doing so is a way to silence uninitialized warnings.
9358     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9359       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9360         if (ICE->getCastKind() == CK_LValueToRValue)
9361           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9362             if (DRE->getDecl() == OrigDecl)
9363               return;
9364 
9365     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9366   }
9367 } // end anonymous namespace
9368 
9369 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9370                                             DeclarationName Name, QualType Type,
9371                                             TypeSourceInfo *TSI,
9372                                             SourceRange Range, bool DirectInit,
9373                                             Expr *Init) {
9374   bool IsInitCapture = !VDecl;
9375   assert((!VDecl || !VDecl->isInitCapture()) &&
9376          "init captures are expected to be deduced prior to initialization");
9377 
9378   ArrayRef<Expr *> DeduceInits = Init;
9379   if (DirectInit) {
9380     if (auto *PL = dyn_cast<ParenListExpr>(Init))
9381       DeduceInits = PL->exprs();
9382     else if (auto *IL = dyn_cast<InitListExpr>(Init))
9383       DeduceInits = IL->inits();
9384   }
9385 
9386   // Deduction only works if we have exactly one source expression.
9387   if (DeduceInits.empty()) {
9388     // It isn't possible to write this directly, but it is possible to
9389     // end up in this situation with "auto x(some_pack...);"
9390     Diag(Init->getLocStart(), IsInitCapture
9391                                   ? diag::err_init_capture_no_expression
9392                                   : diag::err_auto_var_init_no_expression)
9393         << Name << Type << Range;
9394     return QualType();
9395   }
9396 
9397   if (DeduceInits.size() > 1) {
9398     Diag(DeduceInits[1]->getLocStart(),
9399          IsInitCapture ? diag::err_init_capture_multiple_expressions
9400                        : diag::err_auto_var_init_multiple_expressions)
9401         << Name << Type << Range;
9402     return QualType();
9403   }
9404 
9405   Expr *DeduceInit = DeduceInits[0];
9406   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9407     Diag(Init->getLocStart(), IsInitCapture
9408                                   ? diag::err_init_capture_paren_braces
9409                                   : diag::err_auto_var_init_paren_braces)
9410         << isa<InitListExpr>(Init) << Name << Type << Range;
9411     return QualType();
9412   }
9413 
9414   // Expressions default to 'id' when we're in a debugger.
9415   bool DefaultedAnyToId = false;
9416   if (getLangOpts().DebuggerCastResultToId &&
9417       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9418     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9419     if (Result.isInvalid()) {
9420       return QualType();
9421     }
9422     Init = Result.get();
9423     DefaultedAnyToId = true;
9424   }
9425 
9426   QualType DeducedType;
9427   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9428     if (!IsInitCapture)
9429       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9430     else if (isa<InitListExpr>(Init))
9431       Diag(Range.getBegin(),
9432            diag::err_init_capture_deduction_failure_from_init_list)
9433           << Name
9434           << (DeduceInit->getType().isNull() ? TSI->getType()
9435                                              : DeduceInit->getType())
9436           << DeduceInit->getSourceRange();
9437     else
9438       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9439           << Name << TSI->getType()
9440           << (DeduceInit->getType().isNull() ? TSI->getType()
9441                                              : DeduceInit->getType())
9442           << DeduceInit->getSourceRange();
9443   }
9444 
9445   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9446   // 'id' instead of a specific object type prevents most of our usual
9447   // checks.
9448   // We only want to warn outside of template instantiations, though:
9449   // inside a template, the 'id' could have come from a parameter.
9450   if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
9451       !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9452     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9453     Diag(Loc, diag::warn_auto_var_is_id) << Name << Range;
9454   }
9455 
9456   return DeducedType;
9457 }
9458 
9459 /// AddInitializerToDecl - Adds the initializer Init to the
9460 /// declaration dcl. If DirectInit is true, this is C++ direct
9461 /// initialization rather than copy initialization.
9462 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
9463                                 bool DirectInit, bool TypeMayContainAuto) {
9464   // If there is no declaration, there was an error parsing it.  Just ignore
9465   // the initializer.
9466   if (!RealDecl || RealDecl->isInvalidDecl()) {
9467     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
9468     return;
9469   }
9470 
9471   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
9472     // Pure-specifiers are handled in ActOnPureSpecifier.
9473     Diag(Method->getLocation(), diag::err_member_function_initialization)
9474       << Method->getDeclName() << Init->getSourceRange();
9475     Method->setInvalidDecl();
9476     return;
9477   }
9478 
9479   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9480   if (!VDecl) {
9481     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
9482     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9483     RealDecl->setInvalidDecl();
9484     return;
9485   }
9486 
9487   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9488   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
9489     // Attempt typo correction early so that the type of the init expression can
9490     // be deduced based on the chosen correction if the original init contains a
9491     // TypoExpr.
9492     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
9493     if (!Res.isUsable()) {
9494       RealDecl->setInvalidDecl();
9495       return;
9496     }
9497     Init = Res.get();
9498 
9499     QualType DeducedType = deduceVarTypeFromInitializer(
9500         VDecl, VDecl->getDeclName(), VDecl->getType(),
9501         VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
9502     if (DeducedType.isNull()) {
9503       RealDecl->setInvalidDecl();
9504       return;
9505     }
9506 
9507     VDecl->setType(DeducedType);
9508     assert(VDecl->isLinkageValid());
9509 
9510     // In ARC, infer lifetime.
9511     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9512       VDecl->setInvalidDecl();
9513 
9514     // If this is a redeclaration, check that the type we just deduced matches
9515     // the previously declared type.
9516     if (VarDecl *Old = VDecl->getPreviousDecl()) {
9517       // We never need to merge the type, because we cannot form an incomplete
9518       // array of auto, nor deduce such a type.
9519       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9520     }
9521 
9522     // Check the deduced type is valid for a variable declaration.
9523     CheckVariableDeclarationType(VDecl);
9524     if (VDecl->isInvalidDecl())
9525       return;
9526   }
9527 
9528   // dllimport cannot be used on variable definitions.
9529   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
9530     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
9531     VDecl->setInvalidDecl();
9532     return;
9533   }
9534 
9535   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
9536     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
9537     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
9538     VDecl->setInvalidDecl();
9539     return;
9540   }
9541 
9542   if (!VDecl->getType()->isDependentType()) {
9543     // A definition must end up with a complete type, which means it must be
9544     // complete with the restriction that an array type might be completed by
9545     // the initializer; note that later code assumes this restriction.
9546     QualType BaseDeclType = VDecl->getType();
9547     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
9548       BaseDeclType = Array->getElementType();
9549     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
9550                             diag::err_typecheck_decl_incomplete_type)) {
9551       RealDecl->setInvalidDecl();
9552       return;
9553     }
9554 
9555     // The variable can not have an abstract class type.
9556     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9557                                diag::err_abstract_type_in_decl,
9558                                AbstractVariableType))
9559       VDecl->setInvalidDecl();
9560   }
9561 
9562   VarDecl *Def;
9563   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
9564     NamedDecl *Hidden = nullptr;
9565     if (!hasVisibleDefinition(Def, &Hidden) &&
9566         (VDecl->getFormalLinkage() == InternalLinkage ||
9567          VDecl->getDescribedVarTemplate() ||
9568          VDecl->getNumTemplateParameterLists() ||
9569          VDecl->getDeclContext()->isDependentContext())) {
9570       // The previous definition is hidden, and multiple definitions are
9571       // permitted (in separate TUs). Form another definition of it.
9572     } else {
9573       Diag(VDecl->getLocation(), diag::err_redefinition)
9574         << VDecl->getDeclName();
9575       Diag(Def->getLocation(), diag::note_previous_definition);
9576       VDecl->setInvalidDecl();
9577       return;
9578     }
9579   }
9580 
9581   if (getLangOpts().CPlusPlus) {
9582     // C++ [class.static.data]p4
9583     //   If a static data member is of const integral or const
9584     //   enumeration type, its declaration in the class definition can
9585     //   specify a constant-initializer which shall be an integral
9586     //   constant expression (5.19). In that case, the member can appear
9587     //   in integral constant expressions. The member shall still be
9588     //   defined in a namespace scope if it is used in the program and the
9589     //   namespace scope definition shall not contain an initializer.
9590     //
9591     // We already performed a redefinition check above, but for static
9592     // data members we also need to check whether there was an in-class
9593     // declaration with an initializer.
9594     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9595       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9596           << VDecl->getDeclName();
9597       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9598            diag::note_previous_initializer)
9599           << 0;
9600       return;
9601     }
9602 
9603     if (VDecl->hasLocalStorage())
9604       getCurFunction()->setHasBranchProtectedScope();
9605 
9606     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9607       VDecl->setInvalidDecl();
9608       return;
9609     }
9610   }
9611 
9612   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9613   // a kernel function cannot be initialized."
9614   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
9615     Diag(VDecl->getLocation(), diag::err_local_cant_init);
9616     VDecl->setInvalidDecl();
9617     return;
9618   }
9619 
9620   // Get the decls type and save a reference for later, since
9621   // CheckInitializerTypes may change it.
9622   QualType DclT = VDecl->getType(), SavT = DclT;
9623 
9624   // Expressions default to 'id' when we're in a debugger
9625   // and we are assigning it to a variable of Objective-C pointer type.
9626   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9627       Init->getType() == Context.UnknownAnyTy) {
9628     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9629     if (Result.isInvalid()) {
9630       VDecl->setInvalidDecl();
9631       return;
9632     }
9633     Init = Result.get();
9634   }
9635 
9636   // Perform the initialization.
9637   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
9638   if (!VDecl->isInvalidDecl()) {
9639     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9640     InitializationKind Kind =
9641         DirectInit
9642             ? CXXDirectInit
9643                   ? InitializationKind::CreateDirect(VDecl->getLocation(),
9644                                                      Init->getLocStart(),
9645                                                      Init->getLocEnd())
9646                   : InitializationKind::CreateDirectList(VDecl->getLocation())
9647             : InitializationKind::CreateCopy(VDecl->getLocation(),
9648                                              Init->getLocStart());
9649 
9650     MultiExprArg Args = Init;
9651     if (CXXDirectInit)
9652       Args = MultiExprArg(CXXDirectInit->getExprs(),
9653                           CXXDirectInit->getNumExprs());
9654 
9655     // Try to correct any TypoExprs in the initialization arguments.
9656     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
9657       ExprResult Res = CorrectDelayedTyposInExpr(
9658           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
9659             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
9660             return Init.Failed() ? ExprError() : E;
9661           });
9662       if (Res.isInvalid()) {
9663         VDecl->setInvalidDecl();
9664       } else if (Res.get() != Args[Idx]) {
9665         Args[Idx] = Res.get();
9666       }
9667     }
9668     if (VDecl->isInvalidDecl())
9669       return;
9670 
9671     InitializationSequence InitSeq(*this, Entity, Kind, Args,
9672                                    /*TopLevelOfInitList=*/false,
9673                                    /*TreatUnavailableAsInvalid=*/false);
9674     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
9675     if (Result.isInvalid()) {
9676       VDecl->setInvalidDecl();
9677       return;
9678     }
9679 
9680     Init = Result.getAs<Expr>();
9681   }
9682 
9683   // Check for self-references within variable initializers.
9684   // Variables declared within a function/method body (except for references)
9685   // are handled by a dataflow analysis.
9686   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
9687       VDecl->getType()->isReferenceType()) {
9688     CheckSelfReference(*this, RealDecl, Init, DirectInit);
9689   }
9690 
9691   // If the type changed, it means we had an incomplete type that was
9692   // completed by the initializer. For example:
9693   //   int ary[] = { 1, 3, 5 };
9694   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
9695   if (!VDecl->isInvalidDecl() && (DclT != SavT))
9696     VDecl->setType(DclT);
9697 
9698   if (!VDecl->isInvalidDecl()) {
9699     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
9700 
9701     if (VDecl->hasAttr<BlocksAttr>())
9702       checkRetainCycles(VDecl, Init);
9703 
9704     // It is safe to assign a weak reference into a strong variable.
9705     // Although this code can still have problems:
9706     //   id x = self.weakProp;
9707     //   id y = self.weakProp;
9708     // we do not warn to warn spuriously when 'x' and 'y' are on separate
9709     // paths through the function. This should be revisited if
9710     // -Wrepeated-use-of-weak is made flow-sensitive.
9711     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
9712         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9713                          Init->getLocStart()))
9714       getCurFunction()->markSafeWeakUse(Init);
9715   }
9716 
9717   // The initialization is usually a full-expression.
9718   //
9719   // FIXME: If this is a braced initialization of an aggregate, it is not
9720   // an expression, and each individual field initializer is a separate
9721   // full-expression. For instance, in:
9722   //
9723   //   struct Temp { ~Temp(); };
9724   //   struct S { S(Temp); };
9725   //   struct T { S a, b; } t = { Temp(), Temp() }
9726   //
9727   // we should destroy the first Temp before constructing the second.
9728   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
9729                                           false,
9730                                           VDecl->isConstexpr());
9731   if (Result.isInvalid()) {
9732     VDecl->setInvalidDecl();
9733     return;
9734   }
9735   Init = Result.get();
9736 
9737   // Attach the initializer to the decl.
9738   VDecl->setInit(Init);
9739 
9740   if (VDecl->isLocalVarDecl()) {
9741     // C99 6.7.8p4: All the expressions in an initializer for an object that has
9742     // static storage duration shall be constant expressions or string literals.
9743     // C++ does not have this restriction.
9744     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
9745       const Expr *Culprit;
9746       if (VDecl->getStorageClass() == SC_Static)
9747         CheckForConstantInitializer(Init, DclT);
9748       // C89 is stricter than C99 for non-static aggregate types.
9749       // C89 6.5.7p3: All the expressions [...] in an initializer list
9750       // for an object that has aggregate or union type shall be
9751       // constant expressions.
9752       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
9753                isa<InitListExpr>(Init) &&
9754                !Init->isConstantInitializer(Context, false, &Culprit))
9755         Diag(Culprit->getExprLoc(),
9756              diag::ext_aggregate_init_not_constant)
9757           << Culprit->getSourceRange();
9758     }
9759   } else if (VDecl->isStaticDataMember() &&
9760              VDecl->getLexicalDeclContext()->isRecord()) {
9761     // This is an in-class initialization for a static data member, e.g.,
9762     //
9763     // struct S {
9764     //   static const int value = 17;
9765     // };
9766 
9767     // C++ [class.mem]p4:
9768     //   A member-declarator can contain a constant-initializer only
9769     //   if it declares a static member (9.4) of const integral or
9770     //   const enumeration type, see 9.4.2.
9771     //
9772     // C++11 [class.static.data]p3:
9773     //   If a non-volatile const static data member is of integral or
9774     //   enumeration type, its declaration in the class definition can
9775     //   specify a brace-or-equal-initializer in which every initalizer-clause
9776     //   that is an assignment-expression is a constant expression. A static
9777     //   data member of literal type can be declared in the class definition
9778     //   with the constexpr specifier; if so, its declaration shall specify a
9779     //   brace-or-equal-initializer in which every initializer-clause that is
9780     //   an assignment-expression is a constant expression.
9781 
9782     // Do nothing on dependent types.
9783     if (DclT->isDependentType()) {
9784 
9785     // Allow any 'static constexpr' members, whether or not they are of literal
9786     // type. We separately check that every constexpr variable is of literal
9787     // type.
9788     } else if (VDecl->isConstexpr()) {
9789 
9790     // Require constness.
9791     } else if (!DclT.isConstQualified()) {
9792       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
9793         << Init->getSourceRange();
9794       VDecl->setInvalidDecl();
9795 
9796     // We allow integer constant expressions in all cases.
9797     } else if (DclT->isIntegralOrEnumerationType()) {
9798       // Check whether the expression is a constant expression.
9799       SourceLocation Loc;
9800       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
9801         // In C++11, a non-constexpr const static data member with an
9802         // in-class initializer cannot be volatile.
9803         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
9804       else if (Init->isValueDependent())
9805         ; // Nothing to check.
9806       else if (Init->isIntegerConstantExpr(Context, &Loc))
9807         ; // Ok, it's an ICE!
9808       else if (Init->isEvaluatable(Context)) {
9809         // If we can constant fold the initializer through heroics, accept it,
9810         // but report this as a use of an extension for -pedantic.
9811         Diag(Loc, diag::ext_in_class_initializer_non_constant)
9812           << Init->getSourceRange();
9813       } else {
9814         // Otherwise, this is some crazy unknown case.  Report the issue at the
9815         // location provided by the isIntegerConstantExpr failed check.
9816         Diag(Loc, diag::err_in_class_initializer_non_constant)
9817           << Init->getSourceRange();
9818         VDecl->setInvalidDecl();
9819       }
9820 
9821     // We allow foldable floating-point constants as an extension.
9822     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
9823       // In C++98, this is a GNU extension. In C++11, it is not, but we support
9824       // it anyway and provide a fixit to add the 'constexpr'.
9825       if (getLangOpts().CPlusPlus11) {
9826         Diag(VDecl->getLocation(),
9827              diag::ext_in_class_initializer_float_type_cxx11)
9828             << DclT << Init->getSourceRange();
9829         Diag(VDecl->getLocStart(),
9830              diag::note_in_class_initializer_float_type_cxx11)
9831             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9832       } else {
9833         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
9834           << DclT << Init->getSourceRange();
9835 
9836         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
9837           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
9838             << Init->getSourceRange();
9839           VDecl->setInvalidDecl();
9840         }
9841       }
9842 
9843     // Suggest adding 'constexpr' in C++11 for literal types.
9844     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9845       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9846         << DclT << Init->getSourceRange()
9847         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9848       VDecl->setConstexpr(true);
9849 
9850     } else {
9851       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9852         << DclT << Init->getSourceRange();
9853       VDecl->setInvalidDecl();
9854     }
9855   } else if (VDecl->isFileVarDecl()) {
9856     if (VDecl->getStorageClass() == SC_Extern &&
9857         (!getLangOpts().CPlusPlus ||
9858          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
9859            VDecl->isExternC())) &&
9860         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
9861       Diag(VDecl->getLocation(), diag::warn_extern_init);
9862 
9863     // C99 6.7.8p4. All file scoped initializers need to be constant.
9864     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9865       CheckForConstantInitializer(Init, DclT);
9866   }
9867 
9868   // We will represent direct-initialization similarly to copy-initialization:
9869   //    int x(1);  -as-> int x = 1;
9870   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9871   //
9872   // Clients that want to distinguish between the two forms, can check for
9873   // direct initializer using VarDecl::getInitStyle().
9874   // A major benefit is that clients that don't particularly care about which
9875   // exactly form was it (like the CodeGen) can handle both cases without
9876   // special case code.
9877 
9878   // C++ 8.5p11:
9879   // The form of initialization (using parentheses or '=') is generally
9880   // insignificant, but does matter when the entity being initialized has a
9881   // class type.
9882   if (CXXDirectInit) {
9883     assert(DirectInit && "Call-style initializer must be direct init.");
9884     VDecl->setInitStyle(VarDecl::CallInit);
9885   } else if (DirectInit) {
9886     // This must be list-initialization. No other way is direct-initialization.
9887     VDecl->setInitStyle(VarDecl::ListInit);
9888   }
9889 
9890   CheckCompleteVariableDeclaration(VDecl);
9891 }
9892 
9893 /// ActOnInitializerError - Given that there was an error parsing an
9894 /// initializer for the given declaration, try to return to some form
9895 /// of sanity.
9896 void Sema::ActOnInitializerError(Decl *D) {
9897   // Our main concern here is re-establishing invariants like "a
9898   // variable's type is either dependent or complete".
9899   if (!D || D->isInvalidDecl()) return;
9900 
9901   VarDecl *VD = dyn_cast<VarDecl>(D);
9902   if (!VD) return;
9903 
9904   // Auto types are meaningless if we can't make sense of the initializer.
9905   if (ParsingInitForAutoVars.count(D)) {
9906     D->setInvalidDecl();
9907     return;
9908   }
9909 
9910   QualType Ty = VD->getType();
9911   if (Ty->isDependentType()) return;
9912 
9913   // Require a complete type.
9914   if (RequireCompleteType(VD->getLocation(),
9915                           Context.getBaseElementType(Ty),
9916                           diag::err_typecheck_decl_incomplete_type)) {
9917     VD->setInvalidDecl();
9918     return;
9919   }
9920 
9921   // Require a non-abstract type.
9922   if (RequireNonAbstractType(VD->getLocation(), Ty,
9923                              diag::err_abstract_type_in_decl,
9924                              AbstractVariableType)) {
9925     VD->setInvalidDecl();
9926     return;
9927   }
9928 
9929   // Don't bother complaining about constructors or destructors,
9930   // though.
9931 }
9932 
9933 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
9934                                   bool TypeMayContainAuto) {
9935   // If there is no declaration, there was an error parsing it. Just ignore it.
9936   if (!RealDecl)
9937     return;
9938 
9939   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9940     QualType Type = Var->getType();
9941 
9942     // C++11 [dcl.spec.auto]p3
9943     if (TypeMayContainAuto && Type->getContainedAutoType()) {
9944       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
9945         << Var->getDeclName() << Type;
9946       Var->setInvalidDecl();
9947       return;
9948     }
9949 
9950     // C++11 [class.static.data]p3: A static data member can be declared with
9951     // the constexpr specifier; if so, its declaration shall specify
9952     // a brace-or-equal-initializer.
9953     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
9954     // the definition of a variable [...] or the declaration of a static data
9955     // member.
9956     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
9957       if (Var->isStaticDataMember())
9958         Diag(Var->getLocation(),
9959              diag::err_constexpr_static_mem_var_requires_init)
9960           << Var->getDeclName();
9961       else
9962         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
9963       Var->setInvalidDecl();
9964       return;
9965     }
9966 
9967     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
9968     // definition having the concept specifier is called a variable concept. A
9969     // concept definition refers to [...] a variable concept and its initializer.
9970     if (VarTemplateDecl *VTD = Var->getDescribedVarTemplate()) {
9971       if (VTD->isConcept()) {
9972         Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
9973         Var->setInvalidDecl();
9974         return;
9975       }
9976     }
9977 
9978     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
9979     // be initialized.
9980     if (!Var->isInvalidDecl() &&
9981         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
9982         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
9983       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
9984       Var->setInvalidDecl();
9985       return;
9986     }
9987 
9988     switch (Var->isThisDeclarationADefinition()) {
9989     case VarDecl::Definition:
9990       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
9991         break;
9992 
9993       // We have an out-of-line definition of a static data member
9994       // that has an in-class initializer, so we type-check this like
9995       // a declaration.
9996       //
9997       // Fall through
9998 
9999     case VarDecl::DeclarationOnly:
10000       // It's only a declaration.
10001 
10002       // Block scope. C99 6.7p7: If an identifier for an object is
10003       // declared with no linkage (C99 6.2.2p6), the type for the
10004       // object shall be complete.
10005       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
10006           !Var->hasLinkage() && !Var->isInvalidDecl() &&
10007           RequireCompleteType(Var->getLocation(), Type,
10008                               diag::err_typecheck_decl_incomplete_type))
10009         Var->setInvalidDecl();
10010 
10011       // Make sure that the type is not abstract.
10012       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10013           RequireNonAbstractType(Var->getLocation(), Type,
10014                                  diag::err_abstract_type_in_decl,
10015                                  AbstractVariableType))
10016         Var->setInvalidDecl();
10017       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
10018           Var->getStorageClass() == SC_PrivateExtern) {
10019         Diag(Var->getLocation(), diag::warn_private_extern);
10020         Diag(Var->getLocation(), diag::note_private_extern);
10021       }
10022 
10023       return;
10024 
10025     case VarDecl::TentativeDefinition:
10026       // File scope. C99 6.9.2p2: A declaration of an identifier for an
10027       // object that has file scope without an initializer, and without a
10028       // storage-class specifier or with the storage-class specifier "static",
10029       // constitutes a tentative definition. Note: A tentative definition with
10030       // external linkage is valid (C99 6.2.2p5).
10031       if (!Var->isInvalidDecl()) {
10032         if (const IncompleteArrayType *ArrayT
10033                                     = Context.getAsIncompleteArrayType(Type)) {
10034           if (RequireCompleteType(Var->getLocation(),
10035                                   ArrayT->getElementType(),
10036                                   diag::err_illegal_decl_array_incomplete_type))
10037             Var->setInvalidDecl();
10038         } else if (Var->getStorageClass() == SC_Static) {
10039           // C99 6.9.2p3: If the declaration of an identifier for an object is
10040           // a tentative definition and has internal linkage (C99 6.2.2p3), the
10041           // declared type shall not be an incomplete type.
10042           // NOTE: code such as the following
10043           //     static struct s;
10044           //     struct s { int a; };
10045           // is accepted by gcc. Hence here we issue a warning instead of
10046           // an error and we do not invalidate the static declaration.
10047           // NOTE: to avoid multiple warnings, only check the first declaration.
10048           if (Var->isFirstDecl())
10049             RequireCompleteType(Var->getLocation(), Type,
10050                                 diag::ext_typecheck_decl_incomplete_type);
10051         }
10052       }
10053 
10054       // Record the tentative definition; we're done.
10055       if (!Var->isInvalidDecl())
10056         TentativeDefinitions.push_back(Var);
10057       return;
10058     }
10059 
10060     // Provide a specific diagnostic for uninitialized variable
10061     // definitions with incomplete array type.
10062     if (Type->isIncompleteArrayType()) {
10063       Diag(Var->getLocation(),
10064            diag::err_typecheck_incomplete_array_needs_initializer);
10065       Var->setInvalidDecl();
10066       return;
10067     }
10068 
10069     // Provide a specific diagnostic for uninitialized variable
10070     // definitions with reference type.
10071     if (Type->isReferenceType()) {
10072       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
10073         << Var->getDeclName()
10074         << SourceRange(Var->getLocation(), Var->getLocation());
10075       Var->setInvalidDecl();
10076       return;
10077     }
10078 
10079     // Do not attempt to type-check the default initializer for a
10080     // variable with dependent type.
10081     if (Type->isDependentType())
10082       return;
10083 
10084     if (Var->isInvalidDecl())
10085       return;
10086 
10087     if (!Var->hasAttr<AliasAttr>()) {
10088       if (RequireCompleteType(Var->getLocation(),
10089                               Context.getBaseElementType(Type),
10090                               diag::err_typecheck_decl_incomplete_type)) {
10091         Var->setInvalidDecl();
10092         return;
10093       }
10094     } else {
10095       return;
10096     }
10097 
10098     // The variable can not have an abstract class type.
10099     if (RequireNonAbstractType(Var->getLocation(), Type,
10100                                diag::err_abstract_type_in_decl,
10101                                AbstractVariableType)) {
10102       Var->setInvalidDecl();
10103       return;
10104     }
10105 
10106     // Check for jumps past the implicit initializer.  C++0x
10107     // clarifies that this applies to a "variable with automatic
10108     // storage duration", not a "local variable".
10109     // C++11 [stmt.dcl]p3
10110     //   A program that jumps from a point where a variable with automatic
10111     //   storage duration is not in scope to a point where it is in scope is
10112     //   ill-formed unless the variable has scalar type, class type with a
10113     //   trivial default constructor and a trivial destructor, a cv-qualified
10114     //   version of one of these types, or an array of one of the preceding
10115     //   types and is declared without an initializer.
10116     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
10117       if (const RecordType *Record
10118             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
10119         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
10120         // Mark the function for further checking even if the looser rules of
10121         // C++11 do not require such checks, so that we can diagnose
10122         // incompatibilities with C++98.
10123         if (!CXXRecord->isPOD())
10124           getCurFunction()->setHasBranchProtectedScope();
10125       }
10126     }
10127 
10128     // C++03 [dcl.init]p9:
10129     //   If no initializer is specified for an object, and the
10130     //   object is of (possibly cv-qualified) non-POD class type (or
10131     //   array thereof), the object shall be default-initialized; if
10132     //   the object is of const-qualified type, the underlying class
10133     //   type shall have a user-declared default
10134     //   constructor. Otherwise, if no initializer is specified for
10135     //   a non- static object, the object and its subobjects, if
10136     //   any, have an indeterminate initial value); if the object
10137     //   or any of its subobjects are of const-qualified type, the
10138     //   program is ill-formed.
10139     // C++0x [dcl.init]p11:
10140     //   If no initializer is specified for an object, the object is
10141     //   default-initialized; [...].
10142     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
10143     InitializationKind Kind
10144       = InitializationKind::CreateDefault(Var->getLocation());
10145 
10146     InitializationSequence InitSeq(*this, Entity, Kind, None);
10147     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
10148     if (Init.isInvalid())
10149       Var->setInvalidDecl();
10150     else if (Init.get()) {
10151       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
10152       // This is important for template substitution.
10153       Var->setInitStyle(VarDecl::CallInit);
10154     }
10155 
10156     CheckCompleteVariableDeclaration(Var);
10157   }
10158 }
10159 
10160 void Sema::ActOnCXXForRangeDecl(Decl *D) {
10161   // If there is no declaration, there was an error parsing it. Ignore it.
10162   if (!D)
10163     return;
10164 
10165   VarDecl *VD = dyn_cast<VarDecl>(D);
10166   if (!VD) {
10167     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
10168     D->setInvalidDecl();
10169     return;
10170   }
10171 
10172   VD->setCXXForRangeDecl(true);
10173 
10174   // for-range-declaration cannot be given a storage class specifier.
10175   int Error = -1;
10176   switch (VD->getStorageClass()) {
10177   case SC_None:
10178     break;
10179   case SC_Extern:
10180     Error = 0;
10181     break;
10182   case SC_Static:
10183     Error = 1;
10184     break;
10185   case SC_PrivateExtern:
10186     Error = 2;
10187     break;
10188   case SC_Auto:
10189     Error = 3;
10190     break;
10191   case SC_Register:
10192     Error = 4;
10193     break;
10194   }
10195   if (Error != -1) {
10196     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
10197       << VD->getDeclName() << Error;
10198     D->setInvalidDecl();
10199   }
10200 }
10201 
10202 StmtResult
10203 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
10204                                  IdentifierInfo *Ident,
10205                                  ParsedAttributes &Attrs,
10206                                  SourceLocation AttrEnd) {
10207   // C++1y [stmt.iter]p1:
10208   //   A range-based for statement of the form
10209   //      for ( for-range-identifier : for-range-initializer ) statement
10210   //   is equivalent to
10211   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
10212   DeclSpec DS(Attrs.getPool().getFactory());
10213 
10214   const char *PrevSpec;
10215   unsigned DiagID;
10216   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
10217                      getPrintingPolicy());
10218 
10219   Declarator D(DS, Declarator::ForContext);
10220   D.SetIdentifier(Ident, IdentLoc);
10221   D.takeAttributes(Attrs, AttrEnd);
10222 
10223   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
10224   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
10225                 EmptyAttrs, IdentLoc);
10226   Decl *Var = ActOnDeclarator(S, D);
10227   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
10228   FinalizeDeclaration(Var);
10229   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
10230                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
10231 }
10232 
10233 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
10234   if (var->isInvalidDecl()) return;
10235 
10236   if (getLangOpts().OpenCL) {
10237     // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
10238     // initialiser
10239     if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
10240         !var->hasInit()) {
10241       Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
10242           << 1 /*Init*/;
10243       var->setInvalidDecl();
10244       return;
10245     }
10246   }
10247 
10248   // In Objective-C, don't allow jumps past the implicit initialization of a
10249   // local retaining variable.
10250   if (getLangOpts().ObjC1 &&
10251       var->hasLocalStorage()) {
10252     switch (var->getType().getObjCLifetime()) {
10253     case Qualifiers::OCL_None:
10254     case Qualifiers::OCL_ExplicitNone:
10255     case Qualifiers::OCL_Autoreleasing:
10256       break;
10257 
10258     case Qualifiers::OCL_Weak:
10259     case Qualifiers::OCL_Strong:
10260       getCurFunction()->setHasBranchProtectedScope();
10261       break;
10262     }
10263   }
10264 
10265   // Warn about externally-visible variables being defined without a
10266   // prior declaration.  We only want to do this for global
10267   // declarations, but we also specifically need to avoid doing it for
10268   // class members because the linkage of an anonymous class can
10269   // change if it's later given a typedef name.
10270   if (var->isThisDeclarationADefinition() &&
10271       var->getDeclContext()->getRedeclContext()->isFileContext() &&
10272       var->isExternallyVisible() && var->hasLinkage() &&
10273       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
10274                                   var->getLocation())) {
10275     // Find a previous declaration that's not a definition.
10276     VarDecl *prev = var->getPreviousDecl();
10277     while (prev && prev->isThisDeclarationADefinition())
10278       prev = prev->getPreviousDecl();
10279 
10280     if (!prev)
10281       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
10282   }
10283 
10284   if (var->getTLSKind() == VarDecl::TLS_Static) {
10285     const Expr *Culprit;
10286     if (var->getType().isDestructedType()) {
10287       // GNU C++98 edits for __thread, [basic.start.term]p3:
10288       //   The type of an object with thread storage duration shall not
10289       //   have a non-trivial destructor.
10290       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
10291       if (getLangOpts().CPlusPlus11)
10292         Diag(var->getLocation(), diag::note_use_thread_local);
10293     } else if (getLangOpts().CPlusPlus && var->hasInit() &&
10294                !var->getInit()->isConstantInitializer(
10295                    Context, var->getType()->isReferenceType(), &Culprit)) {
10296       // GNU C++98 edits for __thread, [basic.start.init]p4:
10297       //   An object of thread storage duration shall not require dynamic
10298       //   initialization.
10299       // FIXME: Need strict checking here.
10300       Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
10301         << Culprit->getSourceRange();
10302       if (getLangOpts().CPlusPlus11)
10303         Diag(var->getLocation(), diag::note_use_thread_local);
10304     }
10305   }
10306 
10307   // Apply section attributes and pragmas to global variables.
10308   bool GlobalStorage = var->hasGlobalStorage();
10309   if (GlobalStorage && var->isThisDeclarationADefinition() &&
10310       ActiveTemplateInstantiations.empty()) {
10311     PragmaStack<StringLiteral *> *Stack = nullptr;
10312     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
10313     if (var->getType().isConstQualified())
10314       Stack = &ConstSegStack;
10315     else if (!var->getInit()) {
10316       Stack = &BSSSegStack;
10317       SectionFlags |= ASTContext::PSF_Write;
10318     } else {
10319       Stack = &DataSegStack;
10320       SectionFlags |= ASTContext::PSF_Write;
10321     }
10322     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
10323       var->addAttr(SectionAttr::CreateImplicit(
10324           Context, SectionAttr::Declspec_allocate,
10325           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
10326     }
10327     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
10328       if (UnifySection(SA->getName(), SectionFlags, var))
10329         var->dropAttr<SectionAttr>();
10330 
10331     // Apply the init_seg attribute if this has an initializer.  If the
10332     // initializer turns out to not be dynamic, we'll end up ignoring this
10333     // attribute.
10334     if (CurInitSeg && var->getInit())
10335       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
10336                                                CurInitSegLoc));
10337   }
10338 
10339   // All the following checks are C++ only.
10340   if (!getLangOpts().CPlusPlus) return;
10341 
10342   QualType type = var->getType();
10343   if (type->isDependentType()) return;
10344 
10345   // __block variables might require us to capture a copy-initializer.
10346   if (var->hasAttr<BlocksAttr>()) {
10347     // It's currently invalid to ever have a __block variable with an
10348     // array type; should we diagnose that here?
10349 
10350     // Regardless, we don't want to ignore array nesting when
10351     // constructing this copy.
10352     if (type->isStructureOrClassType()) {
10353       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10354       SourceLocation poi = var->getLocation();
10355       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10356       ExprResult result
10357         = PerformMoveOrCopyInitialization(
10358             InitializedEntity::InitializeBlock(poi, type, false),
10359             var, var->getType(), varRef, /*AllowNRVO=*/true);
10360       if (!result.isInvalid()) {
10361         result = MaybeCreateExprWithCleanups(result);
10362         Expr *init = result.getAs<Expr>();
10363         Context.setBlockVarCopyInits(var, init);
10364       }
10365     }
10366   }
10367 
10368   Expr *Init = var->getInit();
10369   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10370   QualType baseType = Context.getBaseElementType(type);
10371 
10372   if (!var->getDeclContext()->isDependentContext() &&
10373       Init && !Init->isValueDependent()) {
10374     if (IsGlobal && !var->isConstexpr() &&
10375         !getDiagnostics().isIgnored(diag::warn_global_constructor,
10376                                     var->getLocation())) {
10377       // Warn about globals which don't have a constant initializer.  Don't
10378       // warn about globals with a non-trivial destructor because we already
10379       // warned about them.
10380       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10381       if (!(RD && !RD->hasTrivialDestructor()) &&
10382           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
10383         Diag(var->getLocation(), diag::warn_global_constructor)
10384           << Init->getSourceRange();
10385     }
10386 
10387     if (var->isConstexpr()) {
10388       SmallVector<PartialDiagnosticAt, 8> Notes;
10389       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10390         SourceLocation DiagLoc = var->getLocation();
10391         // If the note doesn't add any useful information other than a source
10392         // location, fold it into the primary diagnostic.
10393         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10394               diag::note_invalid_subexpr_in_const_expr) {
10395           DiagLoc = Notes[0].first;
10396           Notes.clear();
10397         }
10398         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10399           << var << Init->getSourceRange();
10400         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10401           Diag(Notes[I].first, Notes[I].second);
10402       }
10403     } else if (var->isUsableInConstantExpressions(Context)) {
10404       // Check whether the initializer of a const variable of integral or
10405       // enumeration type is an ICE now, since we can't tell whether it was
10406       // initialized by a constant expression if we check later.
10407       var->checkInitIsICE();
10408     }
10409   }
10410 
10411   // Require the destructor.
10412   if (const RecordType *recordType = baseType->getAs<RecordType>())
10413     FinalizeVarWithDestructor(var, recordType);
10414 }
10415 
10416 /// \brief Determines if a variable's alignment is dependent.
10417 static bool hasDependentAlignment(VarDecl *VD) {
10418   if (VD->getType()->isDependentType())
10419     return true;
10420   for (auto *I : VD->specific_attrs<AlignedAttr>())
10421     if (I->isAlignmentDependent())
10422       return true;
10423   return false;
10424 }
10425 
10426 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10427 /// any semantic actions necessary after any initializer has been attached.
10428 void
10429 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10430   // Note that we are no longer parsing the initializer for this declaration.
10431   ParsingInitForAutoVars.erase(ThisDecl);
10432 
10433   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10434   if (!VD)
10435     return;
10436 
10437   checkAttributesAfterMerging(*this, *VD);
10438 
10439   // Perform TLS alignment check here after attributes attached to the variable
10440   // which may affect the alignment have been processed. Only perform the check
10441   // if the target has a maximum TLS alignment (zero means no constraints).
10442   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
10443     // Protect the check so that it's not performed on dependent types and
10444     // dependent alignments (we can't determine the alignment in that case).
10445     if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
10446       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
10447       if (Context.getDeclAlign(VD) > MaxAlignChars) {
10448         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
10449           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
10450           << (unsigned)MaxAlignChars.getQuantity();
10451       }
10452     }
10453   }
10454 
10455   if (VD->isStaticLocal()) {
10456     if (FunctionDecl *FD =
10457             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
10458       // Static locals inherit dll attributes from their function.
10459       if (Attr *A = getDLLAttr(FD)) {
10460         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
10461         NewAttr->setInherited(true);
10462         VD->addAttr(NewAttr);
10463       }
10464       // CUDA E.2.9.4: Within the body of a __device__ or __global__
10465       // function, only __shared__ variables may be declared with
10466       // static storage class.
10467       if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
10468           (FD->hasAttr<CUDADeviceAttr>() || FD->hasAttr<CUDAGlobalAttr>()) &&
10469           !VD->hasAttr<CUDASharedAttr>()) {
10470         Diag(VD->getLocation(), diag::err_device_static_local_var);
10471         VD->setInvalidDecl();
10472       }
10473     }
10474   }
10475 
10476   // Perform check for initializers of device-side global variables.
10477   // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
10478   // 7.5). We must also apply the same checks to all __shared__
10479   // variables whether they are local or not. CUDA also allows
10480   // constant initializers for __constant__ and __device__ variables.
10481   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
10482     const Expr *Init = VD->getInit();
10483     if (Init && VD->hasGlobalStorage() &&
10484         (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>() ||
10485          VD->hasAttr<CUDASharedAttr>())) {
10486       assert((!VD->isStaticLocal() || VD->hasAttr<CUDASharedAttr>()));
10487       bool AllowedInit = false;
10488       if (const CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(Init))
10489         AllowedInit =
10490             isEmptyCudaConstructor(VD->getLocation(), CE->getConstructor());
10491       // We'll allow constant initializers even if it's a non-empty
10492       // constructor according to CUDA rules. This deviates from NVCC,
10493       // but allows us to handle things like constexpr constructors.
10494       if (!AllowedInit &&
10495           (VD->hasAttr<CUDADeviceAttr>() || VD->hasAttr<CUDAConstantAttr>()))
10496         AllowedInit = VD->getInit()->isConstantInitializer(
10497             Context, VD->getType()->isReferenceType());
10498 
10499       // Also make sure that destructor, if there is one, is empty.
10500       if (AllowedInit)
10501         if (CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl())
10502           AllowedInit =
10503               isEmptyCudaDestructor(VD->getLocation(), RD->getDestructor());
10504 
10505       if (!AllowedInit) {
10506         Diag(VD->getLocation(), VD->hasAttr<CUDASharedAttr>()
10507                                     ? diag::err_shared_var_init
10508                                     : diag::err_dynamic_var_init)
10509             << Init->getSourceRange();
10510         VD->setInvalidDecl();
10511       }
10512     }
10513   }
10514 
10515   // Grab the dllimport or dllexport attribute off of the VarDecl.
10516   const InheritableAttr *DLLAttr = getDLLAttr(VD);
10517 
10518   // Imported static data members cannot be defined out-of-line.
10519   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
10520     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
10521         VD->isThisDeclarationADefinition()) {
10522       // We allow definitions of dllimport class template static data members
10523       // with a warning.
10524       CXXRecordDecl *Context =
10525         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
10526       bool IsClassTemplateMember =
10527           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
10528           Context->getDescribedClassTemplate();
10529 
10530       Diag(VD->getLocation(),
10531            IsClassTemplateMember
10532                ? diag::warn_attribute_dllimport_static_field_definition
10533                : diag::err_attribute_dllimport_static_field_definition);
10534       Diag(IA->getLocation(), diag::note_attribute);
10535       if (!IsClassTemplateMember)
10536         VD->setInvalidDecl();
10537     }
10538   }
10539 
10540   // dllimport/dllexport variables cannot be thread local, their TLS index
10541   // isn't exported with the variable.
10542   if (DLLAttr && VD->getTLSKind()) {
10543     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
10544     if (F && getDLLAttr(F)) {
10545       assert(VD->isStaticLocal());
10546       // But if this is a static local in a dlimport/dllexport function, the
10547       // function will never be inlined, which means the var would never be
10548       // imported, so having it marked import/export is safe.
10549     } else {
10550       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
10551                                                                     << DLLAttr;
10552       VD->setInvalidDecl();
10553     }
10554   }
10555 
10556   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
10557     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
10558       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
10559       VD->dropAttr<UsedAttr>();
10560     }
10561   }
10562 
10563   const DeclContext *DC = VD->getDeclContext();
10564   // If there's a #pragma GCC visibility in scope, and this isn't a class
10565   // member, set the visibility of this variable.
10566   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
10567     AddPushedVisibilityAttribute(VD);
10568 
10569   // FIXME: Warn on unused templates.
10570   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
10571       !isa<VarTemplatePartialSpecializationDecl>(VD))
10572     MarkUnusedFileScopedDecl(VD);
10573 
10574   // Now we have parsed the initializer and can update the table of magic
10575   // tag values.
10576   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
10577       !VD->getType()->isIntegralOrEnumerationType())
10578     return;
10579 
10580   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
10581     const Expr *MagicValueExpr = VD->getInit();
10582     if (!MagicValueExpr) {
10583       continue;
10584     }
10585     llvm::APSInt MagicValueInt;
10586     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
10587       Diag(I->getRange().getBegin(),
10588            diag::err_type_tag_for_datatype_not_ice)
10589         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10590       continue;
10591     }
10592     if (MagicValueInt.getActiveBits() > 64) {
10593       Diag(I->getRange().getBegin(),
10594            diag::err_type_tag_for_datatype_too_large)
10595         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10596       continue;
10597     }
10598     uint64_t MagicValue = MagicValueInt.getZExtValue();
10599     RegisterTypeTagForDatatype(I->getArgumentKind(),
10600                                MagicValue,
10601                                I->getMatchingCType(),
10602                                I->getLayoutCompatible(),
10603                                I->getMustBeNull());
10604   }
10605 }
10606 
10607 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
10608                                                    ArrayRef<Decl *> Group) {
10609   SmallVector<Decl*, 8> Decls;
10610 
10611   if (DS.isTypeSpecOwned())
10612     Decls.push_back(DS.getRepAsDecl());
10613 
10614   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
10615   for (unsigned i = 0, e = Group.size(); i != e; ++i)
10616     if (Decl *D = Group[i]) {
10617       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
10618         if (!FirstDeclaratorInGroup)
10619           FirstDeclaratorInGroup = DD;
10620       Decls.push_back(D);
10621     }
10622 
10623   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
10624     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
10625       handleTagNumbering(Tag, S);
10626       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
10627           getLangOpts().CPlusPlus)
10628         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
10629     }
10630   }
10631 
10632   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
10633 }
10634 
10635 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
10636 /// group, performing any necessary semantic checking.
10637 Sema::DeclGroupPtrTy
10638 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
10639                            bool TypeMayContainAuto) {
10640   // C++0x [dcl.spec.auto]p7:
10641   //   If the type deduced for the template parameter U is not the same in each
10642   //   deduction, the program is ill-formed.
10643   // FIXME: When initializer-list support is added, a distinction is needed
10644   // between the deduced type U and the deduced type which 'auto' stands for.
10645   //   auto a = 0, b = { 1, 2, 3 };
10646   // is legal because the deduced type U is 'int' in both cases.
10647   if (TypeMayContainAuto && Group.size() > 1) {
10648     QualType Deduced;
10649     CanQualType DeducedCanon;
10650     VarDecl *DeducedDecl = nullptr;
10651     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
10652       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
10653         AutoType *AT = D->getType()->getContainedAutoType();
10654         // Don't reissue diagnostics when instantiating a template.
10655         if (AT && D->isInvalidDecl())
10656           break;
10657         QualType U = AT ? AT->getDeducedType() : QualType();
10658         if (!U.isNull()) {
10659           CanQualType UCanon = Context.getCanonicalType(U);
10660           if (Deduced.isNull()) {
10661             Deduced = U;
10662             DeducedCanon = UCanon;
10663             DeducedDecl = D;
10664           } else if (DeducedCanon != UCanon) {
10665             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
10666                  diag::err_auto_different_deductions)
10667               << (unsigned)AT->getKeyword()
10668               << Deduced << DeducedDecl->getDeclName()
10669               << U << D->getDeclName()
10670               << DeducedDecl->getInit()->getSourceRange()
10671               << D->getInit()->getSourceRange();
10672             D->setInvalidDecl();
10673             break;
10674           }
10675         }
10676       }
10677     }
10678   }
10679 
10680   ActOnDocumentableDecls(Group);
10681 
10682   return DeclGroupPtrTy::make(
10683       DeclGroupRef::Create(Context, Group.data(), Group.size()));
10684 }
10685 
10686 void Sema::ActOnDocumentableDecl(Decl *D) {
10687   ActOnDocumentableDecls(D);
10688 }
10689 
10690 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
10691   // Don't parse the comment if Doxygen diagnostics are ignored.
10692   if (Group.empty() || !Group[0])
10693     return;
10694 
10695   if (Diags.isIgnored(diag::warn_doc_param_not_found,
10696                       Group[0]->getLocation()) &&
10697       Diags.isIgnored(diag::warn_unknown_comment_command_name,
10698                       Group[0]->getLocation()))
10699     return;
10700 
10701   if (Group.size() >= 2) {
10702     // This is a decl group.  Normally it will contain only declarations
10703     // produced from declarator list.  But in case we have any definitions or
10704     // additional declaration references:
10705     //   'typedef struct S {} S;'
10706     //   'typedef struct S *S;'
10707     //   'struct S *pS;'
10708     // FinalizeDeclaratorGroup adds these as separate declarations.
10709     Decl *MaybeTagDecl = Group[0];
10710     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
10711       Group = Group.slice(1);
10712     }
10713   }
10714 
10715   // See if there are any new comments that are not attached to a decl.
10716   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
10717   if (!Comments.empty() &&
10718       !Comments.back()->isAttached()) {
10719     // There is at least one comment that not attached to a decl.
10720     // Maybe it should be attached to one of these decls?
10721     //
10722     // Note that this way we pick up not only comments that precede the
10723     // declaration, but also comments that *follow* the declaration -- thanks to
10724     // the lookahead in the lexer: we've consumed the semicolon and looked
10725     // ahead through comments.
10726     for (unsigned i = 0, e = Group.size(); i != e; ++i)
10727       Context.getCommentForDecl(Group[i], &PP);
10728   }
10729 }
10730 
10731 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
10732 /// to introduce parameters into function prototype scope.
10733 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
10734   const DeclSpec &DS = D.getDeclSpec();
10735 
10736   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
10737 
10738   // C++03 [dcl.stc]p2 also permits 'auto'.
10739   StorageClass SC = SC_None;
10740   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
10741     SC = SC_Register;
10742   } else if (getLangOpts().CPlusPlus &&
10743              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
10744     SC = SC_Auto;
10745   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
10746     Diag(DS.getStorageClassSpecLoc(),
10747          diag::err_invalid_storage_class_in_func_decl);
10748     D.getMutableDeclSpec().ClearStorageClassSpecs();
10749   }
10750 
10751   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
10752     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
10753       << DeclSpec::getSpecifierName(TSCS);
10754   if (DS.isConstexprSpecified())
10755     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
10756       << 0;
10757   if (DS.isConceptSpecified())
10758     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
10759 
10760   DiagnoseFunctionSpecifiers(DS);
10761 
10762   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10763   QualType parmDeclType = TInfo->getType();
10764 
10765   if (getLangOpts().CPlusPlus) {
10766     // Check that there are no default arguments inside the type of this
10767     // parameter.
10768     CheckExtraCXXDefaultArguments(D);
10769 
10770     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
10771     if (D.getCXXScopeSpec().isSet()) {
10772       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
10773         << D.getCXXScopeSpec().getRange();
10774       D.getCXXScopeSpec().clear();
10775     }
10776   }
10777 
10778   // Ensure we have a valid name
10779   IdentifierInfo *II = nullptr;
10780   if (D.hasName()) {
10781     II = D.getIdentifier();
10782     if (!II) {
10783       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
10784         << GetNameForDeclarator(D).getName();
10785       D.setInvalidType(true);
10786     }
10787   }
10788 
10789   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
10790   if (II) {
10791     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
10792                    ForRedeclaration);
10793     LookupName(R, S);
10794     if (R.isSingleResult()) {
10795       NamedDecl *PrevDecl = R.getFoundDecl();
10796       if (PrevDecl->isTemplateParameter()) {
10797         // Maybe we will complain about the shadowed template parameter.
10798         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10799         // Just pretend that we didn't see the previous declaration.
10800         PrevDecl = nullptr;
10801       } else if (S->isDeclScope(PrevDecl)) {
10802         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
10803         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10804 
10805         // Recover by removing the name
10806         II = nullptr;
10807         D.SetIdentifier(nullptr, D.getIdentifierLoc());
10808         D.setInvalidType(true);
10809       }
10810     }
10811   }
10812 
10813   // Temporarily put parameter variables in the translation unit, not
10814   // the enclosing context.  This prevents them from accidentally
10815   // looking like class members in C++.
10816   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
10817                                     D.getLocStart(),
10818                                     D.getIdentifierLoc(), II,
10819                                     parmDeclType, TInfo,
10820                                     SC);
10821 
10822   if (D.isInvalidType())
10823     New->setInvalidDecl();
10824 
10825   assert(S->isFunctionPrototypeScope());
10826   assert(S->getFunctionPrototypeDepth() >= 1);
10827   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
10828                     S->getNextFunctionPrototypeIndex());
10829 
10830   // Add the parameter declaration into this scope.
10831   S->AddDecl(New);
10832   if (II)
10833     IdResolver.AddDecl(New);
10834 
10835   ProcessDeclAttributes(S, New, D);
10836 
10837   if (D.getDeclSpec().isModulePrivateSpecified())
10838     Diag(New->getLocation(), diag::err_module_private_local)
10839       << 1 << New->getDeclName()
10840       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10841       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10842 
10843   if (New->hasAttr<BlocksAttr>()) {
10844     Diag(New->getLocation(), diag::err_block_on_nonlocal);
10845   }
10846   return New;
10847 }
10848 
10849 /// \brief Synthesizes a variable for a parameter arising from a
10850 /// typedef.
10851 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
10852                                               SourceLocation Loc,
10853                                               QualType T) {
10854   /* FIXME: setting StartLoc == Loc.
10855      Would it be worth to modify callers so as to provide proper source
10856      location for the unnamed parameters, embedding the parameter's type? */
10857   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
10858                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
10859                                            SC_None, nullptr);
10860   Param->setImplicit();
10861   return Param;
10862 }
10863 
10864 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
10865                                     ParmVarDecl * const *ParamEnd) {
10866   // Don't diagnose unused-parameter errors in template instantiations; we
10867   // will already have done so in the template itself.
10868   if (!ActiveTemplateInstantiations.empty())
10869     return;
10870 
10871   for (; Param != ParamEnd; ++Param) {
10872     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
10873         !(*Param)->hasAttr<UnusedAttr>()) {
10874       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
10875         << (*Param)->getDeclName();
10876     }
10877   }
10878 }
10879 
10880 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
10881                                                   ParmVarDecl * const *ParamEnd,
10882                                                   QualType ReturnTy,
10883                                                   NamedDecl *D) {
10884   if (LangOpts.NumLargeByValueCopy == 0) // No check.
10885     return;
10886 
10887   // Warn if the return value is pass-by-value and larger than the specified
10888   // threshold.
10889   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
10890     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
10891     if (Size > LangOpts.NumLargeByValueCopy)
10892       Diag(D->getLocation(), diag::warn_return_value_size)
10893           << D->getDeclName() << Size;
10894   }
10895 
10896   // Warn if any parameter is pass-by-value and larger than the specified
10897   // threshold.
10898   for (; Param != ParamEnd; ++Param) {
10899     QualType T = (*Param)->getType();
10900     if (T->isDependentType() || !T.isPODType(Context))
10901       continue;
10902     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
10903     if (Size > LangOpts.NumLargeByValueCopy)
10904       Diag((*Param)->getLocation(), diag::warn_parameter_size)
10905           << (*Param)->getDeclName() << Size;
10906   }
10907 }
10908 
10909 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
10910                                   SourceLocation NameLoc, IdentifierInfo *Name,
10911                                   QualType T, TypeSourceInfo *TSInfo,
10912                                   StorageClass SC) {
10913   // In ARC, infer a lifetime qualifier for appropriate parameter types.
10914   if (getLangOpts().ObjCAutoRefCount &&
10915       T.getObjCLifetime() == Qualifiers::OCL_None &&
10916       T->isObjCLifetimeType()) {
10917 
10918     Qualifiers::ObjCLifetime lifetime;
10919 
10920     // Special cases for arrays:
10921     //   - if it's const, use __unsafe_unretained
10922     //   - otherwise, it's an error
10923     if (T->isArrayType()) {
10924       if (!T.isConstQualified()) {
10925         DelayedDiagnostics.add(
10926             sema::DelayedDiagnostic::makeForbiddenType(
10927             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
10928       }
10929       lifetime = Qualifiers::OCL_ExplicitNone;
10930     } else {
10931       lifetime = T->getObjCARCImplicitLifetime();
10932     }
10933     T = Context.getLifetimeQualifiedType(T, lifetime);
10934   }
10935 
10936   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
10937                                          Context.getAdjustedParameterType(T),
10938                                          TSInfo, SC, nullptr);
10939 
10940   // Parameters can not be abstract class types.
10941   // For record types, this is done by the AbstractClassUsageDiagnoser once
10942   // the class has been completely parsed.
10943   if (!CurContext->isRecord() &&
10944       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
10945                              AbstractParamType))
10946     New->setInvalidDecl();
10947 
10948   // Parameter declarators cannot be interface types. All ObjC objects are
10949   // passed by reference.
10950   if (T->isObjCObjectType()) {
10951     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
10952     Diag(NameLoc,
10953          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
10954       << FixItHint::CreateInsertion(TypeEndLoc, "*");
10955     T = Context.getObjCObjectPointerType(T);
10956     New->setType(T);
10957   }
10958 
10959   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
10960   // duration shall not be qualified by an address-space qualifier."
10961   // Since all parameters have automatic store duration, they can not have
10962   // an address space.
10963   if (T.getAddressSpace() != 0) {
10964     // OpenCL allows function arguments declared to be an array of a type
10965     // to be qualified with an address space.
10966     if (!(getLangOpts().OpenCL && T->isArrayType())) {
10967       Diag(NameLoc, diag::err_arg_with_address_space);
10968       New->setInvalidDecl();
10969     }
10970   }
10971 
10972   // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
10973   // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
10974   if (getLangOpts().OpenCL && T->isPointerType()) {
10975     const QualType PTy = T->getPointeeType();
10976     if (PTy->isImageType() || PTy->isSamplerT() || PTy->isPipeType()) {
10977       Diag(NameLoc, diag::err_opencl_pointer_to_type) << PTy;
10978       New->setInvalidDecl();
10979     }
10980   }
10981 
10982   return New;
10983 }
10984 
10985 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
10986                                            SourceLocation LocAfterDecls) {
10987   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10988 
10989   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
10990   // for a K&R function.
10991   if (!FTI.hasPrototype) {
10992     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
10993       --i;
10994       if (FTI.Params[i].Param == nullptr) {
10995         SmallString<256> Code;
10996         llvm::raw_svector_ostream(Code)
10997             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
10998         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
10999             << FTI.Params[i].Ident
11000             << FixItHint::CreateInsertion(LocAfterDecls, Code);
11001 
11002         // Implicitly declare the argument as type 'int' for lack of a better
11003         // type.
11004         AttributeFactory attrs;
11005         DeclSpec DS(attrs);
11006         const char* PrevSpec; // unused
11007         unsigned DiagID; // unused
11008         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
11009                            DiagID, Context.getPrintingPolicy());
11010         // Use the identifier location for the type source range.
11011         DS.SetRangeStart(FTI.Params[i].IdentLoc);
11012         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
11013         Declarator ParamD(DS, Declarator::KNRTypeListContext);
11014         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
11015         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
11016       }
11017     }
11018   }
11019 }
11020 
11021 Decl *
11022 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
11023                               MultiTemplateParamsArg TemplateParameterLists,
11024                               SkipBodyInfo *SkipBody) {
11025   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
11026   assert(D.isFunctionDeclarator() && "Not a function declarator!");
11027   Scope *ParentScope = FnBodyScope->getParent();
11028 
11029   D.setFunctionDefinitionKind(FDK_Definition);
11030   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
11031   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
11032 }
11033 
11034 void Sema::ActOnFinishInlineFunctionDef(FunctionDecl *D) {
11035   Consumer.HandleInlineFunctionDefinition(D);
11036 }
11037 
11038 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
11039                              const FunctionDecl*& PossibleZeroParamPrototype) {
11040   // Don't warn about invalid declarations.
11041   if (FD->isInvalidDecl())
11042     return false;
11043 
11044   // Or declarations that aren't global.
11045   if (!FD->isGlobal())
11046     return false;
11047 
11048   // Don't warn about C++ member functions.
11049   if (isa<CXXMethodDecl>(FD))
11050     return false;
11051 
11052   // Don't warn about 'main'.
11053   if (FD->isMain())
11054     return false;
11055 
11056   // Don't warn about inline functions.
11057   if (FD->isInlined())
11058     return false;
11059 
11060   // Don't warn about function templates.
11061   if (FD->getDescribedFunctionTemplate())
11062     return false;
11063 
11064   // Don't warn about function template specializations.
11065   if (FD->isFunctionTemplateSpecialization())
11066     return false;
11067 
11068   // Don't warn for OpenCL kernels.
11069   if (FD->hasAttr<OpenCLKernelAttr>())
11070     return false;
11071 
11072   // Don't warn on explicitly deleted functions.
11073   if (FD->isDeleted())
11074     return false;
11075 
11076   bool MissingPrototype = true;
11077   for (const FunctionDecl *Prev = FD->getPreviousDecl();
11078        Prev; Prev = Prev->getPreviousDecl()) {
11079     // Ignore any declarations that occur in function or method
11080     // scope, because they aren't visible from the header.
11081     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
11082       continue;
11083 
11084     MissingPrototype = !Prev->getType()->isFunctionProtoType();
11085     if (FD->getNumParams() == 0)
11086       PossibleZeroParamPrototype = Prev;
11087     break;
11088   }
11089 
11090   return MissingPrototype;
11091 }
11092 
11093 void
11094 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
11095                                    const FunctionDecl *EffectiveDefinition,
11096                                    SkipBodyInfo *SkipBody) {
11097   // Don't complain if we're in GNU89 mode and the previous definition
11098   // was an extern inline function.
11099   const FunctionDecl *Definition = EffectiveDefinition;
11100   if (!Definition)
11101     if (!FD->isDefined(Definition))
11102       return;
11103 
11104   if (canRedefineFunction(Definition, getLangOpts()))
11105     return;
11106 
11107   // If we don't have a visible definition of the function, and it's inline or
11108   // a template, skip the new definition.
11109   if (SkipBody && !hasVisibleDefinition(Definition) &&
11110       (Definition->getFormalLinkage() == InternalLinkage ||
11111        Definition->isInlined() ||
11112        Definition->getDescribedFunctionTemplate() ||
11113        Definition->getNumTemplateParameterLists())) {
11114     SkipBody->ShouldSkip = true;
11115     if (auto *TD = Definition->getDescribedFunctionTemplate())
11116       makeMergedDefinitionVisible(TD, FD->getLocation());
11117     else
11118       makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
11119                                   FD->getLocation());
11120     return;
11121   }
11122 
11123   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
11124       Definition->getStorageClass() == SC_Extern)
11125     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
11126         << FD->getDeclName() << getLangOpts().CPlusPlus;
11127   else
11128     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
11129 
11130   Diag(Definition->getLocation(), diag::note_previous_definition);
11131   FD->setInvalidDecl();
11132 }
11133 
11134 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
11135                                    Sema &S) {
11136   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
11137 
11138   LambdaScopeInfo *LSI = S.PushLambdaScope();
11139   LSI->CallOperator = CallOperator;
11140   LSI->Lambda = LambdaClass;
11141   LSI->ReturnType = CallOperator->getReturnType();
11142   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
11143 
11144   if (LCD == LCD_None)
11145     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
11146   else if (LCD == LCD_ByCopy)
11147     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
11148   else if (LCD == LCD_ByRef)
11149     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
11150   DeclarationNameInfo DNI = CallOperator->getNameInfo();
11151 
11152   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
11153   LSI->Mutable = !CallOperator->isConst();
11154 
11155   // Add the captures to the LSI so they can be noted as already
11156   // captured within tryCaptureVar.
11157   auto I = LambdaClass->field_begin();
11158   for (const auto &C : LambdaClass->captures()) {
11159     if (C.capturesVariable()) {
11160       VarDecl *VD = C.getCapturedVar();
11161       if (VD->isInitCapture())
11162         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
11163       QualType CaptureType = VD->getType();
11164       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
11165       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
11166           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
11167           /*EllipsisLoc*/C.isPackExpansion()
11168                          ? C.getEllipsisLoc() : SourceLocation(),
11169           CaptureType, /*Expr*/ nullptr);
11170 
11171     } else if (C.capturesThis()) {
11172       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
11173                               S.getCurrentThisType(), /*Expr*/ nullptr,
11174                               C.getCaptureKind() == LCK_StarThis);
11175     } else {
11176       LSI->addVLATypeCapture(C.getLocation(), I->getType());
11177     }
11178     ++I;
11179   }
11180 }
11181 
11182 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
11183                                     SkipBodyInfo *SkipBody) {
11184   // Clear the last template instantiation error context.
11185   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
11186 
11187   if (!D)
11188     return D;
11189   FunctionDecl *FD = nullptr;
11190 
11191   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
11192     FD = FunTmpl->getTemplatedDecl();
11193   else
11194     FD = cast<FunctionDecl>(D);
11195 
11196   // See if this is a redefinition.
11197   if (!FD->isLateTemplateParsed()) {
11198     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
11199 
11200     // If we're skipping the body, we're done. Don't enter the scope.
11201     if (SkipBody && SkipBody->ShouldSkip)
11202       return D;
11203   }
11204 
11205   // If we are instantiating a generic lambda call operator, push
11206   // a LambdaScopeInfo onto the function stack.  But use the information
11207   // that's already been calculated (ActOnLambdaExpr) to prime the current
11208   // LambdaScopeInfo.
11209   // When the template operator is being specialized, the LambdaScopeInfo,
11210   // has to be properly restored so that tryCaptureVariable doesn't try
11211   // and capture any new variables. In addition when calculating potential
11212   // captures during transformation of nested lambdas, it is necessary to
11213   // have the LSI properly restored.
11214   if (isGenericLambdaCallOperatorSpecialization(FD)) {
11215     assert(ActiveTemplateInstantiations.size() &&
11216       "There should be an active template instantiation on the stack "
11217       "when instantiating a generic lambda!");
11218     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
11219   }
11220   else
11221     // Enter a new function scope
11222     PushFunctionScope();
11223 
11224   // Builtin functions cannot be defined.
11225   if (unsigned BuiltinID = FD->getBuiltinID()) {
11226     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
11227         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
11228       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
11229       FD->setInvalidDecl();
11230     }
11231   }
11232 
11233   // The return type of a function definition must be complete
11234   // (C99 6.9.1p3, C++ [dcl.fct]p6).
11235   QualType ResultType = FD->getReturnType();
11236   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
11237       !FD->isInvalidDecl() &&
11238       RequireCompleteType(FD->getLocation(), ResultType,
11239                           diag::err_func_def_incomplete_result))
11240     FD->setInvalidDecl();
11241 
11242   if (FnBodyScope)
11243     PushDeclContext(FnBodyScope, FD);
11244 
11245   // Check the validity of our function parameters
11246   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
11247                            /*CheckParameterNames=*/true);
11248 
11249   // Introduce our parameters into the function scope
11250   for (auto Param : FD->params()) {
11251     Param->setOwningFunction(FD);
11252 
11253     // If this has an identifier, add it to the scope stack.
11254     if (Param->getIdentifier() && FnBodyScope) {
11255       CheckShadow(FnBodyScope, Param);
11256 
11257       PushOnScopeChains(Param, FnBodyScope);
11258     }
11259   }
11260 
11261   // If we had any tags defined in the function prototype,
11262   // introduce them into the function scope.
11263   if (FnBodyScope) {
11264     for (ArrayRef<NamedDecl *>::iterator
11265              I = FD->getDeclsInPrototypeScope().begin(),
11266              E = FD->getDeclsInPrototypeScope().end();
11267          I != E; ++I) {
11268       NamedDecl *D = *I;
11269 
11270       // Some of these decls (like enums) may have been pinned to the
11271       // translation unit for lack of a real context earlier. If so, remove
11272       // from the translation unit and reattach to the current context.
11273       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
11274         // Is the decl actually in the context?
11275         if (Context.getTranslationUnitDecl()->containsDecl(D))
11276           Context.getTranslationUnitDecl()->removeDecl(D);
11277         // Either way, reassign the lexical decl context to our FunctionDecl.
11278         D->setLexicalDeclContext(CurContext);
11279       }
11280 
11281       // If the decl has a non-null name, make accessible in the current scope.
11282       if (!D->getName().empty())
11283         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
11284 
11285       // Similarly, dive into enums and fish their constants out, making them
11286       // accessible in this scope.
11287       if (auto *ED = dyn_cast<EnumDecl>(D)) {
11288         for (auto *EI : ED->enumerators())
11289           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
11290       }
11291     }
11292   }
11293 
11294   // Ensure that the function's exception specification is instantiated.
11295   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
11296     ResolveExceptionSpec(D->getLocation(), FPT);
11297 
11298   // dllimport cannot be applied to non-inline function definitions.
11299   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
11300       !FD->isTemplateInstantiation()) {
11301     assert(!FD->hasAttr<DLLExportAttr>());
11302     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
11303     FD->setInvalidDecl();
11304     return D;
11305   }
11306   // We want to attach documentation to original Decl (which might be
11307   // a function template).
11308   ActOnDocumentableDecl(D);
11309   if (getCurLexicalContext()->isObjCContainer() &&
11310       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
11311       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
11312     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
11313 
11314   return D;
11315 }
11316 
11317 /// \brief Given the set of return statements within a function body,
11318 /// compute the variables that are subject to the named return value
11319 /// optimization.
11320 ///
11321 /// Each of the variables that is subject to the named return value
11322 /// optimization will be marked as NRVO variables in the AST, and any
11323 /// return statement that has a marked NRVO variable as its NRVO candidate can
11324 /// use the named return value optimization.
11325 ///
11326 /// This function applies a very simplistic algorithm for NRVO: if every return
11327 /// statement in the scope of a variable has the same NRVO candidate, that
11328 /// candidate is an NRVO variable.
11329 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
11330   ReturnStmt **Returns = Scope->Returns.data();
11331 
11332   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
11333     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
11334       if (!NRVOCandidate->isNRVOVariable())
11335         Returns[I]->setNRVOCandidate(nullptr);
11336     }
11337   }
11338 }
11339 
11340 bool Sema::canDelayFunctionBody(const Declarator &D) {
11341   // We can't delay parsing the body of a constexpr function template (yet).
11342   if (D.getDeclSpec().isConstexprSpecified())
11343     return false;
11344 
11345   // We can't delay parsing the body of a function template with a deduced
11346   // return type (yet).
11347   if (D.getDeclSpec().containsPlaceholderType()) {
11348     // If the placeholder introduces a non-deduced trailing return type,
11349     // we can still delay parsing it.
11350     if (D.getNumTypeObjects()) {
11351       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
11352       if (Outer.Kind == DeclaratorChunk::Function &&
11353           Outer.Fun.hasTrailingReturnType()) {
11354         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
11355         return Ty.isNull() || !Ty->isUndeducedType();
11356       }
11357     }
11358     return false;
11359   }
11360 
11361   return true;
11362 }
11363 
11364 bool Sema::canSkipFunctionBody(Decl *D) {
11365   // We cannot skip the body of a function (or function template) which is
11366   // constexpr, since we may need to evaluate its body in order to parse the
11367   // rest of the file.
11368   // We cannot skip the body of a function with an undeduced return type,
11369   // because any callers of that function need to know the type.
11370   if (const FunctionDecl *FD = D->getAsFunction())
11371     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
11372       return false;
11373   return Consumer.shouldSkipFunctionBody(D);
11374 }
11375 
11376 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
11377   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
11378     FD->setHasSkippedBody();
11379   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
11380     MD->setHasSkippedBody();
11381   return ActOnFinishFunctionBody(Decl, nullptr);
11382 }
11383 
11384 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
11385   return ActOnFinishFunctionBody(D, BodyArg, false);
11386 }
11387 
11388 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
11389                                     bool IsInstantiation) {
11390   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
11391 
11392   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
11393   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
11394 
11395   if (getLangOpts().Coroutines && !getCurFunction()->CoroutineStmts.empty())
11396     CheckCompletedCoroutineBody(FD, Body);
11397 
11398   if (FD) {
11399     FD->setBody(Body);
11400 
11401     if (getLangOpts().CPlusPlus14) {
11402       if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
11403           FD->getReturnType()->isUndeducedType()) {
11404         // If the function has a deduced result type but contains no 'return'
11405         // statements, the result type as written must be exactly 'auto', and
11406         // the deduced result type is 'void'.
11407         if (!FD->getReturnType()->getAs<AutoType>()) {
11408           Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
11409               << FD->getReturnType();
11410           FD->setInvalidDecl();
11411         } else {
11412           // Substitute 'void' for the 'auto' in the type.
11413           TypeLoc ResultType = getReturnTypeLoc(FD);
11414           Context.adjustDeducedFunctionResultType(
11415               FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
11416         }
11417       }
11418     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
11419       // In C++11, we don't use 'auto' deduction rules for lambda call
11420       // operators because we don't support return type deduction.
11421       auto *LSI = getCurLambda();
11422       if (LSI->HasImplicitReturnType) {
11423         deduceClosureReturnType(*LSI);
11424 
11425         // C++11 [expr.prim.lambda]p4:
11426         //   [...] if there are no return statements in the compound-statement
11427         //   [the deduced type is] the type void
11428         QualType RetType =
11429             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
11430 
11431         // Update the return type to the deduced type.
11432         const FunctionProtoType *Proto =
11433             FD->getType()->getAs<FunctionProtoType>();
11434         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
11435                                             Proto->getExtProtoInfo()));
11436       }
11437     }
11438 
11439     // The only way to be included in UndefinedButUsed is if there is an
11440     // ODR use before the definition. Avoid the expensive map lookup if this
11441     // is the first declaration.
11442     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
11443       if (!FD->isExternallyVisible())
11444         UndefinedButUsed.erase(FD);
11445       else if (FD->isInlined() &&
11446                !LangOpts.GNUInline &&
11447                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
11448         UndefinedButUsed.erase(FD);
11449     }
11450 
11451     // If the function implicitly returns zero (like 'main') or is naked,
11452     // don't complain about missing return statements.
11453     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
11454       WP.disableCheckFallThrough();
11455 
11456     // MSVC permits the use of pure specifier (=0) on function definition,
11457     // defined at class scope, warn about this non-standard construct.
11458     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
11459       Diag(FD->getLocation(), diag::ext_pure_function_definition);
11460 
11461     if (!FD->isInvalidDecl()) {
11462       // Don't diagnose unused parameters of defaulted or deleted functions.
11463       if (!FD->isDeleted() && !FD->isDefaulted())
11464         DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
11465       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
11466                                              FD->getReturnType(), FD);
11467 
11468       // If this is a structor, we need a vtable.
11469       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
11470         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
11471       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
11472         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
11473 
11474       // Try to apply the named return value optimization. We have to check
11475       // if we can do this here because lambdas keep return statements around
11476       // to deduce an implicit return type.
11477       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
11478           !FD->isDependentContext())
11479         computeNRVO(Body, getCurFunction());
11480     }
11481 
11482     // GNU warning -Wmissing-prototypes:
11483     //   Warn if a global function is defined without a previous
11484     //   prototype declaration. This warning is issued even if the
11485     //   definition itself provides a prototype. The aim is to detect
11486     //   global functions that fail to be declared in header files.
11487     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
11488     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
11489       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
11490 
11491       if (PossibleZeroParamPrototype) {
11492         // We found a declaration that is not a prototype,
11493         // but that could be a zero-parameter prototype
11494         if (TypeSourceInfo *TI =
11495                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
11496           TypeLoc TL = TI->getTypeLoc();
11497           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
11498             Diag(PossibleZeroParamPrototype->getLocation(),
11499                  diag::note_declaration_not_a_prototype)
11500                 << PossibleZeroParamPrototype
11501                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
11502         }
11503       }
11504     }
11505 
11506     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11507       const CXXMethodDecl *KeyFunction;
11508       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
11509           MD->isVirtual() &&
11510           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
11511           MD == KeyFunction->getCanonicalDecl()) {
11512         // Update the key-function state if necessary for this ABI.
11513         if (FD->isInlined() &&
11514             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11515           Context.setNonKeyFunction(MD);
11516 
11517           // If the newly-chosen key function is already defined, then we
11518           // need to mark the vtable as used retroactively.
11519           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
11520           const FunctionDecl *Definition;
11521           if (KeyFunction && KeyFunction->isDefined(Definition))
11522             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
11523         } else {
11524           // We just defined they key function; mark the vtable as used.
11525           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
11526         }
11527       }
11528     }
11529 
11530     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
11531            "Function parsing confused");
11532   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
11533     assert(MD == getCurMethodDecl() && "Method parsing confused");
11534     MD->setBody(Body);
11535     if (!MD->isInvalidDecl()) {
11536       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
11537       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
11538                                              MD->getReturnType(), MD);
11539 
11540       if (Body)
11541         computeNRVO(Body, getCurFunction());
11542     }
11543     if (getCurFunction()->ObjCShouldCallSuper) {
11544       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
11545         << MD->getSelector().getAsString();
11546       getCurFunction()->ObjCShouldCallSuper = false;
11547     }
11548     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
11549       const ObjCMethodDecl *InitMethod = nullptr;
11550       bool isDesignated =
11551           MD->isDesignatedInitializerForTheInterface(&InitMethod);
11552       assert(isDesignated && InitMethod);
11553       (void)isDesignated;
11554 
11555       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
11556         auto IFace = MD->getClassInterface();
11557         if (!IFace)
11558           return false;
11559         auto SuperD = IFace->getSuperClass();
11560         if (!SuperD)
11561           return false;
11562         return SuperD->getIdentifier() ==
11563             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
11564       };
11565       // Don't issue this warning for unavailable inits or direct subclasses
11566       // of NSObject.
11567       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
11568         Diag(MD->getLocation(),
11569              diag::warn_objc_designated_init_missing_super_call);
11570         Diag(InitMethod->getLocation(),
11571              diag::note_objc_designated_init_marked_here);
11572       }
11573       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
11574     }
11575     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
11576       // Don't issue this warning for unavaialable inits.
11577       if (!MD->isUnavailable())
11578         Diag(MD->getLocation(),
11579              diag::warn_objc_secondary_init_missing_init_call);
11580       getCurFunction()->ObjCWarnForNoInitDelegation = false;
11581     }
11582   } else {
11583     return nullptr;
11584   }
11585 
11586   assert(!getCurFunction()->ObjCShouldCallSuper &&
11587          "This should only be set for ObjC methods, which should have been "
11588          "handled in the block above.");
11589 
11590   // Verify and clean out per-function state.
11591   if (Body && (!FD || !FD->isDefaulted())) {
11592     // C++ constructors that have function-try-blocks can't have return
11593     // statements in the handlers of that block. (C++ [except.handle]p14)
11594     // Verify this.
11595     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
11596       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
11597 
11598     // Verify that gotos and switch cases don't jump into scopes illegally.
11599     if (getCurFunction()->NeedsScopeChecking() &&
11600         !PP.isCodeCompletionEnabled())
11601       DiagnoseInvalidJumps(Body);
11602 
11603     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
11604       if (!Destructor->getParent()->isDependentType())
11605         CheckDestructor(Destructor);
11606 
11607       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11608                                              Destructor->getParent());
11609     }
11610 
11611     // If any errors have occurred, clear out any temporaries that may have
11612     // been leftover. This ensures that these temporaries won't be picked up for
11613     // deletion in some later function.
11614     if (getDiagnostics().hasErrorOccurred() ||
11615         getDiagnostics().getSuppressAllDiagnostics()) {
11616       DiscardCleanupsInEvaluationContext();
11617     }
11618     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
11619         !isa<FunctionTemplateDecl>(dcl)) {
11620       // Since the body is valid, issue any analysis-based warnings that are
11621       // enabled.
11622       ActivePolicy = &WP;
11623     }
11624 
11625     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
11626         (!CheckConstexprFunctionDecl(FD) ||
11627          !CheckConstexprFunctionBody(FD, Body)))
11628       FD->setInvalidDecl();
11629 
11630     if (FD && FD->hasAttr<NakedAttr>()) {
11631       for (const Stmt *S : Body->children()) {
11632         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
11633           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
11634           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
11635           FD->setInvalidDecl();
11636           break;
11637         }
11638       }
11639     }
11640 
11641     assert(ExprCleanupObjects.size() ==
11642                ExprEvalContexts.back().NumCleanupObjects &&
11643            "Leftover temporaries in function");
11644     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
11645     assert(MaybeODRUseExprs.empty() &&
11646            "Leftover expressions for odr-use checking");
11647   }
11648 
11649   if (!IsInstantiation)
11650     PopDeclContext();
11651 
11652   PopFunctionScopeInfo(ActivePolicy, dcl);
11653   // If any errors have occurred, clear out any temporaries that may have
11654   // been leftover. This ensures that these temporaries won't be picked up for
11655   // deletion in some later function.
11656   if (getDiagnostics().hasErrorOccurred()) {
11657     DiscardCleanupsInEvaluationContext();
11658   }
11659 
11660   return dcl;
11661 }
11662 
11663 /// When we finish delayed parsing of an attribute, we must attach it to the
11664 /// relevant Decl.
11665 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
11666                                        ParsedAttributes &Attrs) {
11667   // Always attach attributes to the underlying decl.
11668   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
11669     D = TD->getTemplatedDecl();
11670   ProcessDeclAttributeList(S, D, Attrs.getList());
11671 
11672   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
11673     if (Method->isStatic())
11674       checkThisInStaticMemberFunctionAttributes(Method);
11675 }
11676 
11677 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
11678 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
11679 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
11680                                           IdentifierInfo &II, Scope *S) {
11681   // Before we produce a declaration for an implicitly defined
11682   // function, see whether there was a locally-scoped declaration of
11683   // this name as a function or variable. If so, use that
11684   // (non-visible) declaration, and complain about it.
11685   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
11686     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
11687     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
11688     return ExternCPrev;
11689   }
11690 
11691   // Extension in C99.  Legal in C90, but warn about it.
11692   unsigned diag_id;
11693   if (II.getName().startswith("__builtin_"))
11694     diag_id = diag::warn_builtin_unknown;
11695   else if (getLangOpts().C99)
11696     diag_id = diag::ext_implicit_function_decl;
11697   else
11698     diag_id = diag::warn_implicit_function_decl;
11699   Diag(Loc, diag_id) << &II;
11700 
11701   // Because typo correction is expensive, only do it if the implicit
11702   // function declaration is going to be treated as an error.
11703   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
11704     TypoCorrection Corrected;
11705     if (S &&
11706         (Corrected = CorrectTypo(
11707              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
11708              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
11709       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
11710                    /*ErrorRecovery*/false);
11711   }
11712 
11713   // Set a Declarator for the implicit definition: int foo();
11714   const char *Dummy;
11715   AttributeFactory attrFactory;
11716   DeclSpec DS(attrFactory);
11717   unsigned DiagID;
11718   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
11719                                   Context.getPrintingPolicy());
11720   (void)Error; // Silence warning.
11721   assert(!Error && "Error setting up implicit decl!");
11722   SourceLocation NoLoc;
11723   Declarator D(DS, Declarator::BlockContext);
11724   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
11725                                              /*IsAmbiguous=*/false,
11726                                              /*LParenLoc=*/NoLoc,
11727                                              /*Params=*/nullptr,
11728                                              /*NumParams=*/0,
11729                                              /*EllipsisLoc=*/NoLoc,
11730                                              /*RParenLoc=*/NoLoc,
11731                                              /*TypeQuals=*/0,
11732                                              /*RefQualifierIsLvalueRef=*/true,
11733                                              /*RefQualifierLoc=*/NoLoc,
11734                                              /*ConstQualifierLoc=*/NoLoc,
11735                                              /*VolatileQualifierLoc=*/NoLoc,
11736                                              /*RestrictQualifierLoc=*/NoLoc,
11737                                              /*MutableLoc=*/NoLoc,
11738                                              EST_None,
11739                                              /*ESpecRange=*/SourceRange(),
11740                                              /*Exceptions=*/nullptr,
11741                                              /*ExceptionRanges=*/nullptr,
11742                                              /*NumExceptions=*/0,
11743                                              /*NoexceptExpr=*/nullptr,
11744                                              /*ExceptionSpecTokens=*/nullptr,
11745                                              Loc, Loc, D),
11746                 DS.getAttributes(),
11747                 SourceLocation());
11748   D.SetIdentifier(&II, Loc);
11749 
11750   // Insert this function into translation-unit scope.
11751 
11752   DeclContext *PrevDC = CurContext;
11753   CurContext = Context.getTranslationUnitDecl();
11754 
11755   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
11756   FD->setImplicit();
11757 
11758   CurContext = PrevDC;
11759 
11760   AddKnownFunctionAttributes(FD);
11761 
11762   return FD;
11763 }
11764 
11765 /// \brief Adds any function attributes that we know a priori based on
11766 /// the declaration of this function.
11767 ///
11768 /// These attributes can apply both to implicitly-declared builtins
11769 /// (like __builtin___printf_chk) or to library-declared functions
11770 /// like NSLog or printf.
11771 ///
11772 /// We need to check for duplicate attributes both here and where user-written
11773 /// attributes are applied to declarations.
11774 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
11775   if (FD->isInvalidDecl())
11776     return;
11777 
11778   // If this is a built-in function, map its builtin attributes to
11779   // actual attributes.
11780   if (unsigned BuiltinID = FD->getBuiltinID()) {
11781     // Handle printf-formatting attributes.
11782     unsigned FormatIdx;
11783     bool HasVAListArg;
11784     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
11785       if (!FD->hasAttr<FormatAttr>()) {
11786         const char *fmt = "printf";
11787         unsigned int NumParams = FD->getNumParams();
11788         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
11789             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
11790           fmt = "NSString";
11791         FD->addAttr(FormatAttr::CreateImplicit(Context,
11792                                                &Context.Idents.get(fmt),
11793                                                FormatIdx+1,
11794                                                HasVAListArg ? 0 : FormatIdx+2,
11795                                                FD->getLocation()));
11796       }
11797     }
11798     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
11799                                              HasVAListArg)) {
11800      if (!FD->hasAttr<FormatAttr>())
11801        FD->addAttr(FormatAttr::CreateImplicit(Context,
11802                                               &Context.Idents.get("scanf"),
11803                                               FormatIdx+1,
11804                                               HasVAListArg ? 0 : FormatIdx+2,
11805                                               FD->getLocation()));
11806     }
11807 
11808     // Mark const if we don't care about errno and that is the only
11809     // thing preventing the function from being const. This allows
11810     // IRgen to use LLVM intrinsics for such functions.
11811     if (!getLangOpts().MathErrno &&
11812         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
11813       if (!FD->hasAttr<ConstAttr>())
11814         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11815     }
11816 
11817     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
11818         !FD->hasAttr<ReturnsTwiceAttr>())
11819       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
11820                                          FD->getLocation()));
11821     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
11822       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11823     if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
11824       FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
11825     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
11826       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11827     if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
11828         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
11829       // Add the appropriate attribute, depending on the CUDA compilation mode
11830       // and which target the builtin belongs to. For example, during host
11831       // compilation, aux builtins are __device__, while the rest are __host__.
11832       if (getLangOpts().CUDAIsDevice !=
11833           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
11834         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
11835       else
11836         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
11837     }
11838   }
11839 
11840   // If C++ exceptions are enabled but we are told extern "C" functions cannot
11841   // throw, add an implicit nothrow attribute to any extern "C" function we come
11842   // across.
11843   if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
11844       FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
11845     const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
11846     if (!FPT || FPT->getExceptionSpecType() == EST_None)
11847       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11848   }
11849 
11850   IdentifierInfo *Name = FD->getIdentifier();
11851   if (!Name)
11852     return;
11853   if ((!getLangOpts().CPlusPlus &&
11854        FD->getDeclContext()->isTranslationUnit()) ||
11855       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
11856        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
11857        LinkageSpecDecl::lang_c)) {
11858     // Okay: this could be a libc/libm/Objective-C function we know
11859     // about.
11860   } else
11861     return;
11862 
11863   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
11864     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
11865     // target-specific builtins, perhaps?
11866     if (!FD->hasAttr<FormatAttr>())
11867       FD->addAttr(FormatAttr::CreateImplicit(Context,
11868                                              &Context.Idents.get("printf"), 2,
11869                                              Name->isStr("vasprintf") ? 0 : 3,
11870                                              FD->getLocation()));
11871   }
11872 
11873   if (Name->isStr("__CFStringMakeConstantString")) {
11874     // We already have a __builtin___CFStringMakeConstantString,
11875     // but builds that use -fno-constant-cfstrings don't go through that.
11876     if (!FD->hasAttr<FormatArgAttr>())
11877       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
11878                                                 FD->getLocation()));
11879   }
11880 }
11881 
11882 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
11883                                     TypeSourceInfo *TInfo) {
11884   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
11885   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
11886 
11887   if (!TInfo) {
11888     assert(D.isInvalidType() && "no declarator info for valid type");
11889     TInfo = Context.getTrivialTypeSourceInfo(T);
11890   }
11891 
11892   // Scope manipulation handled by caller.
11893   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
11894                                            D.getLocStart(),
11895                                            D.getIdentifierLoc(),
11896                                            D.getIdentifier(),
11897                                            TInfo);
11898 
11899   // Bail out immediately if we have an invalid declaration.
11900   if (D.isInvalidType()) {
11901     NewTD->setInvalidDecl();
11902     return NewTD;
11903   }
11904 
11905   if (D.getDeclSpec().isModulePrivateSpecified()) {
11906     if (CurContext->isFunctionOrMethod())
11907       Diag(NewTD->getLocation(), diag::err_module_private_local)
11908         << 2 << NewTD->getDeclName()
11909         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11910         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11911     else
11912       NewTD->setModulePrivate();
11913   }
11914 
11915   // C++ [dcl.typedef]p8:
11916   //   If the typedef declaration defines an unnamed class (or
11917   //   enum), the first typedef-name declared by the declaration
11918   //   to be that class type (or enum type) is used to denote the
11919   //   class type (or enum type) for linkage purposes only.
11920   // We need to check whether the type was declared in the declaration.
11921   switch (D.getDeclSpec().getTypeSpecType()) {
11922   case TST_enum:
11923   case TST_struct:
11924   case TST_interface:
11925   case TST_union:
11926   case TST_class: {
11927     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
11928     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
11929     break;
11930   }
11931 
11932   default:
11933     break;
11934   }
11935 
11936   return NewTD;
11937 }
11938 
11939 /// \brief Check that this is a valid underlying type for an enum declaration.
11940 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
11941   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
11942   QualType T = TI->getType();
11943 
11944   if (T->isDependentType())
11945     return false;
11946 
11947   if (const BuiltinType *BT = T->getAs<BuiltinType>())
11948     if (BT->isInteger())
11949       return false;
11950 
11951   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
11952   return true;
11953 }
11954 
11955 /// Check whether this is a valid redeclaration of a previous enumeration.
11956 /// \return true if the redeclaration was invalid.
11957 bool Sema::CheckEnumRedeclaration(
11958     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
11959     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
11960   bool IsFixed = !EnumUnderlyingTy.isNull();
11961 
11962   if (IsScoped != Prev->isScoped()) {
11963     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
11964       << Prev->isScoped();
11965     Diag(Prev->getLocation(), diag::note_previous_declaration);
11966     return true;
11967   }
11968 
11969   if (IsFixed && Prev->isFixed()) {
11970     if (!EnumUnderlyingTy->isDependentType() &&
11971         !Prev->getIntegerType()->isDependentType() &&
11972         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
11973                                         Prev->getIntegerType())) {
11974       // TODO: Highlight the underlying type of the redeclaration.
11975       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
11976         << EnumUnderlyingTy << Prev->getIntegerType();
11977       Diag(Prev->getLocation(), diag::note_previous_declaration)
11978           << Prev->getIntegerTypeRange();
11979       return true;
11980     }
11981   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
11982     ;
11983   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
11984     ;
11985   } else if (IsFixed != Prev->isFixed()) {
11986     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
11987       << Prev->isFixed();
11988     Diag(Prev->getLocation(), diag::note_previous_declaration);
11989     return true;
11990   }
11991 
11992   return false;
11993 }
11994 
11995 /// \brief Get diagnostic %select index for tag kind for
11996 /// redeclaration diagnostic message.
11997 /// WARNING: Indexes apply to particular diagnostics only!
11998 ///
11999 /// \returns diagnostic %select index.
12000 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
12001   switch (Tag) {
12002   case TTK_Struct: return 0;
12003   case TTK_Interface: return 1;
12004   case TTK_Class:  return 2;
12005   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
12006   }
12007 }
12008 
12009 /// \brief Determine if tag kind is a class-key compatible with
12010 /// class for redeclaration (class, struct, or __interface).
12011 ///
12012 /// \returns true iff the tag kind is compatible.
12013 static bool isClassCompatTagKind(TagTypeKind Tag)
12014 {
12015   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
12016 }
12017 
12018 /// \brief Determine whether a tag with a given kind is acceptable
12019 /// as a redeclaration of the given tag declaration.
12020 ///
12021 /// \returns true if the new tag kind is acceptable, false otherwise.
12022 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
12023                                         TagTypeKind NewTag, bool isDefinition,
12024                                         SourceLocation NewTagLoc,
12025                                         const IdentifierInfo *Name) {
12026   // C++ [dcl.type.elab]p3:
12027   //   The class-key or enum keyword present in the
12028   //   elaborated-type-specifier shall agree in kind with the
12029   //   declaration to which the name in the elaborated-type-specifier
12030   //   refers. This rule also applies to the form of
12031   //   elaborated-type-specifier that declares a class-name or
12032   //   friend class since it can be construed as referring to the
12033   //   definition of the class. Thus, in any
12034   //   elaborated-type-specifier, the enum keyword shall be used to
12035   //   refer to an enumeration (7.2), the union class-key shall be
12036   //   used to refer to a union (clause 9), and either the class or
12037   //   struct class-key shall be used to refer to a class (clause 9)
12038   //   declared using the class or struct class-key.
12039   TagTypeKind OldTag = Previous->getTagKind();
12040   if (!isDefinition || !isClassCompatTagKind(NewTag))
12041     if (OldTag == NewTag)
12042       return true;
12043 
12044   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
12045     // Warn about the struct/class tag mismatch.
12046     bool isTemplate = false;
12047     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
12048       isTemplate = Record->getDescribedClassTemplate();
12049 
12050     if (!ActiveTemplateInstantiations.empty()) {
12051       // In a template instantiation, do not offer fix-its for tag mismatches
12052       // since they usually mess up the template instead of fixing the problem.
12053       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12054         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12055         << getRedeclDiagFromTagKind(OldTag);
12056       return true;
12057     }
12058 
12059     if (isDefinition) {
12060       // On definitions, check previous tags and issue a fix-it for each
12061       // one that doesn't match the current tag.
12062       if (Previous->getDefinition()) {
12063         // Don't suggest fix-its for redefinitions.
12064         return true;
12065       }
12066 
12067       bool previousMismatch = false;
12068       for (auto I : Previous->redecls()) {
12069         if (I->getTagKind() != NewTag) {
12070           if (!previousMismatch) {
12071             previousMismatch = true;
12072             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
12073               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12074               << getRedeclDiagFromTagKind(I->getTagKind());
12075           }
12076           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
12077             << getRedeclDiagFromTagKind(NewTag)
12078             << FixItHint::CreateReplacement(I->getInnerLocStart(),
12079                  TypeWithKeyword::getTagTypeKindName(NewTag));
12080         }
12081       }
12082       return true;
12083     }
12084 
12085     // Check for a previous definition.  If current tag and definition
12086     // are same type, do nothing.  If no definition, but disagree with
12087     // with previous tag type, give a warning, but no fix-it.
12088     const TagDecl *Redecl = Previous->getDefinition() ?
12089                             Previous->getDefinition() : Previous;
12090     if (Redecl->getTagKind() == NewTag) {
12091       return true;
12092     }
12093 
12094     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
12095       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
12096       << getRedeclDiagFromTagKind(OldTag);
12097     Diag(Redecl->getLocation(), diag::note_previous_use);
12098 
12099     // If there is a previous definition, suggest a fix-it.
12100     if (Previous->getDefinition()) {
12101         Diag(NewTagLoc, diag::note_struct_class_suggestion)
12102           << getRedeclDiagFromTagKind(Redecl->getTagKind())
12103           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
12104                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
12105     }
12106 
12107     return true;
12108   }
12109   return false;
12110 }
12111 
12112 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
12113 /// from an outer enclosing namespace or file scope inside a friend declaration.
12114 /// This should provide the commented out code in the following snippet:
12115 ///   namespace N {
12116 ///     struct X;
12117 ///     namespace M {
12118 ///       struct Y { friend struct /*N::*/ X; };
12119 ///     }
12120 ///   }
12121 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
12122                                          SourceLocation NameLoc) {
12123   // While the decl is in a namespace, do repeated lookup of that name and see
12124   // if we get the same namespace back.  If we do not, continue until
12125   // translation unit scope, at which point we have a fully qualified NNS.
12126   SmallVector<IdentifierInfo *, 4> Namespaces;
12127   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12128   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
12129     // This tag should be declared in a namespace, which can only be enclosed by
12130     // other namespaces.  Bail if there's an anonymous namespace in the chain.
12131     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
12132     if (!Namespace || Namespace->isAnonymousNamespace())
12133       return FixItHint();
12134     IdentifierInfo *II = Namespace->getIdentifier();
12135     Namespaces.push_back(II);
12136     NamedDecl *Lookup = SemaRef.LookupSingleName(
12137         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
12138     if (Lookup == Namespace)
12139       break;
12140   }
12141 
12142   // Once we have all the namespaces, reverse them to go outermost first, and
12143   // build an NNS.
12144   SmallString<64> Insertion;
12145   llvm::raw_svector_ostream OS(Insertion);
12146   if (DC->isTranslationUnit())
12147     OS << "::";
12148   std::reverse(Namespaces.begin(), Namespaces.end());
12149   for (auto *II : Namespaces)
12150     OS << II->getName() << "::";
12151   return FixItHint::CreateInsertion(NameLoc, Insertion);
12152 }
12153 
12154 /// \brief Determine whether a tag originally declared in context \p OldDC can
12155 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
12156 /// found a declaration in \p OldDC as a previous decl, perhaps through a
12157 /// using-declaration).
12158 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
12159                                          DeclContext *NewDC) {
12160   OldDC = OldDC->getRedeclContext();
12161   NewDC = NewDC->getRedeclContext();
12162 
12163   if (OldDC->Equals(NewDC))
12164     return true;
12165 
12166   // In MSVC mode, we allow a redeclaration if the contexts are related (either
12167   // encloses the other).
12168   if (S.getLangOpts().MSVCCompat &&
12169       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
12170     return true;
12171 
12172   return false;
12173 }
12174 
12175 /// Find the DeclContext in which a tag is implicitly declared if we see an
12176 /// elaborated type specifier in the specified context, and lookup finds
12177 /// nothing.
12178 static DeclContext *getTagInjectionContext(DeclContext *DC) {
12179   while (!DC->isFileContext() && !DC->isFunctionOrMethod())
12180     DC = DC->getParent();
12181   return DC;
12182 }
12183 
12184 /// Find the Scope in which a tag is implicitly declared if we see an
12185 /// elaborated type specifier in the specified context, and lookup finds
12186 /// nothing.
12187 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
12188   while (S->isClassScope() ||
12189          (LangOpts.CPlusPlus &&
12190           S->isFunctionPrototypeScope()) ||
12191          ((S->getFlags() & Scope::DeclScope) == 0) ||
12192          (S->getEntity() && S->getEntity()->isTransparentContext()))
12193     S = S->getParent();
12194   return S;
12195 }
12196 
12197 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
12198 /// former case, Name will be non-null.  In the later case, Name will be null.
12199 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
12200 /// reference/declaration/definition of a tag.
12201 ///
12202 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
12203 /// trailing-type-specifier) other than one in an alias-declaration.
12204 ///
12205 /// \param SkipBody If non-null, will be set to indicate if the caller should
12206 /// skip the definition of this tag and treat it as if it were a declaration.
12207 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
12208                      SourceLocation KWLoc, CXXScopeSpec &SS,
12209                      IdentifierInfo *Name, SourceLocation NameLoc,
12210                      AttributeList *Attr, AccessSpecifier AS,
12211                      SourceLocation ModulePrivateLoc,
12212                      MultiTemplateParamsArg TemplateParameterLists,
12213                      bool &OwnedDecl, bool &IsDependent,
12214                      SourceLocation ScopedEnumKWLoc,
12215                      bool ScopedEnumUsesClassTag,
12216                      TypeResult UnderlyingType,
12217                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
12218   // If this is not a definition, it must have a name.
12219   IdentifierInfo *OrigName = Name;
12220   assert((Name != nullptr || TUK == TUK_Definition) &&
12221          "Nameless record must be a definition!");
12222   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
12223 
12224   OwnedDecl = false;
12225   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
12226   bool ScopedEnum = ScopedEnumKWLoc.isValid();
12227 
12228   // FIXME: Check explicit specializations more carefully.
12229   bool isExplicitSpecialization = false;
12230   bool Invalid = false;
12231 
12232   // We only need to do this matching if we have template parameters
12233   // or a scope specifier, which also conveniently avoids this work
12234   // for non-C++ cases.
12235   if (TemplateParameterLists.size() > 0 ||
12236       (SS.isNotEmpty() && TUK != TUK_Reference)) {
12237     if (TemplateParameterList *TemplateParams =
12238             MatchTemplateParametersToScopeSpecifier(
12239                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
12240                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
12241       if (Kind == TTK_Enum) {
12242         Diag(KWLoc, diag::err_enum_template);
12243         return nullptr;
12244       }
12245 
12246       if (TemplateParams->size() > 0) {
12247         // This is a declaration or definition of a class template (which may
12248         // be a member of another template).
12249 
12250         if (Invalid)
12251           return nullptr;
12252 
12253         OwnedDecl = false;
12254         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
12255                                                SS, Name, NameLoc, Attr,
12256                                                TemplateParams, AS,
12257                                                ModulePrivateLoc,
12258                                                /*FriendLoc*/SourceLocation(),
12259                                                TemplateParameterLists.size()-1,
12260                                                TemplateParameterLists.data(),
12261                                                SkipBody);
12262         return Result.get();
12263       } else {
12264         // The "template<>" header is extraneous.
12265         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
12266           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
12267         isExplicitSpecialization = true;
12268       }
12269     }
12270   }
12271 
12272   // Figure out the underlying type if this a enum declaration. We need to do
12273   // this early, because it's needed to detect if this is an incompatible
12274   // redeclaration.
12275   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
12276   bool EnumUnderlyingIsImplicit = false;
12277 
12278   if (Kind == TTK_Enum) {
12279     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
12280       // No underlying type explicitly specified, or we failed to parse the
12281       // type, default to int.
12282       EnumUnderlying = Context.IntTy.getTypePtr();
12283     else if (UnderlyingType.get()) {
12284       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
12285       // integral type; any cv-qualification is ignored.
12286       TypeSourceInfo *TI = nullptr;
12287       GetTypeFromParser(UnderlyingType.get(), &TI);
12288       EnumUnderlying = TI;
12289 
12290       if (CheckEnumUnderlyingType(TI))
12291         // Recover by falling back to int.
12292         EnumUnderlying = Context.IntTy.getTypePtr();
12293 
12294       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
12295                                           UPPC_FixedUnderlyingType))
12296         EnumUnderlying = Context.IntTy.getTypePtr();
12297 
12298     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12299       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
12300         // Microsoft enums are always of int type.
12301         EnumUnderlying = Context.IntTy.getTypePtr();
12302         EnumUnderlyingIsImplicit = true;
12303       }
12304     }
12305   }
12306 
12307   DeclContext *SearchDC = CurContext;
12308   DeclContext *DC = CurContext;
12309   bool isStdBadAlloc = false;
12310 
12311   RedeclarationKind Redecl = ForRedeclaration;
12312   if (TUK == TUK_Friend || TUK == TUK_Reference)
12313     Redecl = NotForRedeclaration;
12314 
12315   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
12316   if (Name && SS.isNotEmpty()) {
12317     // We have a nested-name tag ('struct foo::bar').
12318 
12319     // Check for invalid 'foo::'.
12320     if (SS.isInvalid()) {
12321       Name = nullptr;
12322       goto CreateNewDecl;
12323     }
12324 
12325     // If this is a friend or a reference to a class in a dependent
12326     // context, don't try to make a decl for it.
12327     if (TUK == TUK_Friend || TUK == TUK_Reference) {
12328       DC = computeDeclContext(SS, false);
12329       if (!DC) {
12330         IsDependent = true;
12331         return nullptr;
12332       }
12333     } else {
12334       DC = computeDeclContext(SS, true);
12335       if (!DC) {
12336         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
12337           << SS.getRange();
12338         return nullptr;
12339       }
12340     }
12341 
12342     if (RequireCompleteDeclContext(SS, DC))
12343       return nullptr;
12344 
12345     SearchDC = DC;
12346     // Look-up name inside 'foo::'.
12347     LookupQualifiedName(Previous, DC);
12348 
12349     if (Previous.isAmbiguous())
12350       return nullptr;
12351 
12352     if (Previous.empty()) {
12353       // Name lookup did not find anything. However, if the
12354       // nested-name-specifier refers to the current instantiation,
12355       // and that current instantiation has any dependent base
12356       // classes, we might find something at instantiation time: treat
12357       // this as a dependent elaborated-type-specifier.
12358       // But this only makes any sense for reference-like lookups.
12359       if (Previous.wasNotFoundInCurrentInstantiation() &&
12360           (TUK == TUK_Reference || TUK == TUK_Friend)) {
12361         IsDependent = true;
12362         return nullptr;
12363       }
12364 
12365       // A tag 'foo::bar' must already exist.
12366       Diag(NameLoc, diag::err_not_tag_in_scope)
12367         << Kind << Name << DC << SS.getRange();
12368       Name = nullptr;
12369       Invalid = true;
12370       goto CreateNewDecl;
12371     }
12372   } else if (Name) {
12373     // C++14 [class.mem]p14:
12374     //   If T is the name of a class, then each of the following shall have a
12375     //   name different from T:
12376     //    -- every member of class T that is itself a type
12377     if (TUK != TUK_Reference && TUK != TUK_Friend &&
12378         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
12379       return nullptr;
12380 
12381     // If this is a named struct, check to see if there was a previous forward
12382     // declaration or definition.
12383     // FIXME: We're looking into outer scopes here, even when we
12384     // shouldn't be. Doing so can result in ambiguities that we
12385     // shouldn't be diagnosing.
12386     LookupName(Previous, S);
12387 
12388     // When declaring or defining a tag, ignore ambiguities introduced
12389     // by types using'ed into this scope.
12390     if (Previous.isAmbiguous() &&
12391         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
12392       LookupResult::Filter F = Previous.makeFilter();
12393       while (F.hasNext()) {
12394         NamedDecl *ND = F.next();
12395         if (!ND->getDeclContext()->getRedeclContext()->Equals(
12396                 SearchDC->getRedeclContext()))
12397           F.erase();
12398       }
12399       F.done();
12400     }
12401 
12402     // C++11 [namespace.memdef]p3:
12403     //   If the name in a friend declaration is neither qualified nor
12404     //   a template-id and the declaration is a function or an
12405     //   elaborated-type-specifier, the lookup to determine whether
12406     //   the entity has been previously declared shall not consider
12407     //   any scopes outside the innermost enclosing namespace.
12408     //
12409     // MSVC doesn't implement the above rule for types, so a friend tag
12410     // declaration may be a redeclaration of a type declared in an enclosing
12411     // scope.  They do implement this rule for friend functions.
12412     //
12413     // Does it matter that this should be by scope instead of by
12414     // semantic context?
12415     if (!Previous.empty() && TUK == TUK_Friend) {
12416       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
12417       LookupResult::Filter F = Previous.makeFilter();
12418       bool FriendSawTagOutsideEnclosingNamespace = false;
12419       while (F.hasNext()) {
12420         NamedDecl *ND = F.next();
12421         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
12422         if (DC->isFileContext() &&
12423             !EnclosingNS->Encloses(ND->getDeclContext())) {
12424           if (getLangOpts().MSVCCompat)
12425             FriendSawTagOutsideEnclosingNamespace = true;
12426           else
12427             F.erase();
12428         }
12429       }
12430       F.done();
12431 
12432       // Diagnose this MSVC extension in the easy case where lookup would have
12433       // unambiguously found something outside the enclosing namespace.
12434       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
12435         NamedDecl *ND = Previous.getFoundDecl();
12436         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
12437             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
12438       }
12439     }
12440 
12441     // Note:  there used to be some attempt at recovery here.
12442     if (Previous.isAmbiguous())
12443       return nullptr;
12444 
12445     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
12446       // FIXME: This makes sure that we ignore the contexts associated
12447       // with C structs, unions, and enums when looking for a matching
12448       // tag declaration or definition. See the similar lookup tweak
12449       // in Sema::LookupName; is there a better way to deal with this?
12450       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
12451         SearchDC = SearchDC->getParent();
12452     }
12453   }
12454 
12455   if (Previous.isSingleResult() &&
12456       Previous.getFoundDecl()->isTemplateParameter()) {
12457     // Maybe we will complain about the shadowed template parameter.
12458     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
12459     // Just pretend that we didn't see the previous declaration.
12460     Previous.clear();
12461   }
12462 
12463   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
12464       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
12465     // This is a declaration of or a reference to "std::bad_alloc".
12466     isStdBadAlloc = true;
12467 
12468     if (Previous.empty() && StdBadAlloc) {
12469       // std::bad_alloc has been implicitly declared (but made invisible to
12470       // name lookup). Fill in this implicit declaration as the previous
12471       // declaration, so that the declarations get chained appropriately.
12472       Previous.addDecl(getStdBadAlloc());
12473     }
12474   }
12475 
12476   // If we didn't find a previous declaration, and this is a reference
12477   // (or friend reference), move to the correct scope.  In C++, we
12478   // also need to do a redeclaration lookup there, just in case
12479   // there's a shadow friend decl.
12480   if (Name && Previous.empty() &&
12481       (TUK == TUK_Reference || TUK == TUK_Friend)) {
12482     if (Invalid) goto CreateNewDecl;
12483     assert(SS.isEmpty());
12484 
12485     if (TUK == TUK_Reference) {
12486       // C++ [basic.scope.pdecl]p5:
12487       //   -- for an elaborated-type-specifier of the form
12488       //
12489       //          class-key identifier
12490       //
12491       //      if the elaborated-type-specifier is used in the
12492       //      decl-specifier-seq or parameter-declaration-clause of a
12493       //      function defined in namespace scope, the identifier is
12494       //      declared as a class-name in the namespace that contains
12495       //      the declaration; otherwise, except as a friend
12496       //      declaration, the identifier is declared in the smallest
12497       //      non-class, non-function-prototype scope that contains the
12498       //      declaration.
12499       //
12500       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
12501       // C structs and unions.
12502       //
12503       // It is an error in C++ to declare (rather than define) an enum
12504       // type, including via an elaborated type specifier.  We'll
12505       // diagnose that later; for now, declare the enum in the same
12506       // scope as we would have picked for any other tag type.
12507       //
12508       // GNU C also supports this behavior as part of its incomplete
12509       // enum types extension, while GNU C++ does not.
12510       //
12511       // Find the context where we'll be declaring the tag.
12512       // FIXME: We would like to maintain the current DeclContext as the
12513       // lexical context,
12514       SearchDC = getTagInjectionContext(SearchDC);
12515 
12516       // Find the scope where we'll be declaring the tag.
12517       S = getTagInjectionScope(S, getLangOpts());
12518     } else {
12519       assert(TUK == TUK_Friend);
12520       // C++ [namespace.memdef]p3:
12521       //   If a friend declaration in a non-local class first declares a
12522       //   class or function, the friend class or function is a member of
12523       //   the innermost enclosing namespace.
12524       SearchDC = SearchDC->getEnclosingNamespaceContext();
12525     }
12526 
12527     // In C++, we need to do a redeclaration lookup to properly
12528     // diagnose some problems.
12529     // FIXME: redeclaration lookup is also used (with and without C++) to find a
12530     // hidden declaration so that we don't get ambiguity errors when using a
12531     // type declared by an elaborated-type-specifier.  In C that is not correct
12532     // and we should instead merge compatible types found by lookup.
12533     if (getLangOpts().CPlusPlus) {
12534       Previous.setRedeclarationKind(ForRedeclaration);
12535       LookupQualifiedName(Previous, SearchDC);
12536     } else {
12537       Previous.setRedeclarationKind(ForRedeclaration);
12538       LookupName(Previous, S);
12539     }
12540   }
12541 
12542   // If we have a known previous declaration to use, then use it.
12543   if (Previous.empty() && SkipBody && SkipBody->Previous)
12544     Previous.addDecl(SkipBody->Previous);
12545 
12546   if (!Previous.empty()) {
12547     NamedDecl *PrevDecl = Previous.getFoundDecl();
12548     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
12549 
12550     // It's okay to have a tag decl in the same scope as a typedef
12551     // which hides a tag decl in the same scope.  Finding this
12552     // insanity with a redeclaration lookup can only actually happen
12553     // in C++.
12554     //
12555     // This is also okay for elaborated-type-specifiers, which is
12556     // technically forbidden by the current standard but which is
12557     // okay according to the likely resolution of an open issue;
12558     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
12559     if (getLangOpts().CPlusPlus) {
12560       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12561         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
12562           TagDecl *Tag = TT->getDecl();
12563           if (Tag->getDeclName() == Name &&
12564               Tag->getDeclContext()->getRedeclContext()
12565                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
12566             PrevDecl = Tag;
12567             Previous.clear();
12568             Previous.addDecl(Tag);
12569             Previous.resolveKind();
12570           }
12571         }
12572       }
12573     }
12574 
12575     // If this is a redeclaration of a using shadow declaration, it must
12576     // declare a tag in the same context. In MSVC mode, we allow a
12577     // redefinition if either context is within the other.
12578     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
12579       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
12580       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
12581           isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
12582           !(OldTag && isAcceptableTagRedeclContext(
12583                           *this, OldTag->getDeclContext(), SearchDC))) {
12584         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
12585         Diag(Shadow->getTargetDecl()->getLocation(),
12586              diag::note_using_decl_target);
12587         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
12588             << 0;
12589         // Recover by ignoring the old declaration.
12590         Previous.clear();
12591         goto CreateNewDecl;
12592       }
12593     }
12594 
12595     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
12596       // If this is a use of a previous tag, or if the tag is already declared
12597       // in the same scope (so that the definition/declaration completes or
12598       // rementions the tag), reuse the decl.
12599       if (TUK == TUK_Reference || TUK == TUK_Friend ||
12600           isDeclInScope(DirectPrevDecl, SearchDC, S,
12601                         SS.isNotEmpty() || isExplicitSpecialization)) {
12602         // Make sure that this wasn't declared as an enum and now used as a
12603         // struct or something similar.
12604         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
12605                                           TUK == TUK_Definition, KWLoc,
12606                                           Name)) {
12607           bool SafeToContinue
12608             = (PrevTagDecl->getTagKind() != TTK_Enum &&
12609                Kind != TTK_Enum);
12610           if (SafeToContinue)
12611             Diag(KWLoc, diag::err_use_with_wrong_tag)
12612               << Name
12613               << FixItHint::CreateReplacement(SourceRange(KWLoc),
12614                                               PrevTagDecl->getKindName());
12615           else
12616             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
12617           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
12618 
12619           if (SafeToContinue)
12620             Kind = PrevTagDecl->getTagKind();
12621           else {
12622             // Recover by making this an anonymous redefinition.
12623             Name = nullptr;
12624             Previous.clear();
12625             Invalid = true;
12626           }
12627         }
12628 
12629         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
12630           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
12631 
12632           // If this is an elaborated-type-specifier for a scoped enumeration,
12633           // the 'class' keyword is not necessary and not permitted.
12634           if (TUK == TUK_Reference || TUK == TUK_Friend) {
12635             if (ScopedEnum)
12636               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
12637                 << PrevEnum->isScoped()
12638                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
12639             return PrevTagDecl;
12640           }
12641 
12642           QualType EnumUnderlyingTy;
12643           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12644             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
12645           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
12646             EnumUnderlyingTy = QualType(T, 0);
12647 
12648           // All conflicts with previous declarations are recovered by
12649           // returning the previous declaration, unless this is a definition,
12650           // in which case we want the caller to bail out.
12651           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
12652                                      ScopedEnum, EnumUnderlyingTy,
12653                                      EnumUnderlyingIsImplicit, PrevEnum))
12654             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
12655         }
12656 
12657         // C++11 [class.mem]p1:
12658         //   A member shall not be declared twice in the member-specification,
12659         //   except that a nested class or member class template can be declared
12660         //   and then later defined.
12661         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
12662             S->isDeclScope(PrevDecl)) {
12663           Diag(NameLoc, diag::ext_member_redeclared);
12664           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
12665         }
12666 
12667         if (!Invalid) {
12668           // If this is a use, just return the declaration we found, unless
12669           // we have attributes.
12670           if (TUK == TUK_Reference || TUK == TUK_Friend) {
12671             if (Attr) {
12672               // FIXME: Diagnose these attributes. For now, we create a new
12673               // declaration to hold them.
12674             } else if (TUK == TUK_Reference &&
12675                        (PrevTagDecl->getFriendObjectKind() ==
12676                             Decl::FOK_Undeclared ||
12677                         PP.getModuleContainingLocation(
12678                             PrevDecl->getLocation()) !=
12679                             PP.getModuleContainingLocation(KWLoc)) &&
12680                        SS.isEmpty()) {
12681               // This declaration is a reference to an existing entity, but
12682               // has different visibility from that entity: it either makes
12683               // a friend visible or it makes a type visible in a new module.
12684               // In either case, create a new declaration. We only do this if
12685               // the declaration would have meant the same thing if no prior
12686               // declaration were found, that is, if it was found in the same
12687               // scope where we would have injected a declaration.
12688               if (!getTagInjectionContext(CurContext)->getRedeclContext()
12689                        ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
12690                 return PrevTagDecl;
12691               // This is in the injected scope, create a new declaration in
12692               // that scope.
12693               S = getTagInjectionScope(S, getLangOpts());
12694             } else {
12695               return PrevTagDecl;
12696             }
12697           }
12698 
12699           // Diagnose attempts to redefine a tag.
12700           if (TUK == TUK_Definition) {
12701             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
12702               // If we're defining a specialization and the previous definition
12703               // is from an implicit instantiation, don't emit an error
12704               // here; we'll catch this in the general case below.
12705               bool IsExplicitSpecializationAfterInstantiation = false;
12706               if (isExplicitSpecialization) {
12707                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
12708                   IsExplicitSpecializationAfterInstantiation =
12709                     RD->getTemplateSpecializationKind() !=
12710                     TSK_ExplicitSpecialization;
12711                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
12712                   IsExplicitSpecializationAfterInstantiation =
12713                     ED->getTemplateSpecializationKind() !=
12714                     TSK_ExplicitSpecialization;
12715               }
12716 
12717               NamedDecl *Hidden = nullptr;
12718               if (SkipBody && getLangOpts().CPlusPlus &&
12719                   !hasVisibleDefinition(Def, &Hidden)) {
12720                 // There is a definition of this tag, but it is not visible. We
12721                 // explicitly make use of C++'s one definition rule here, and
12722                 // assume that this definition is identical to the hidden one
12723                 // we already have. Make the existing definition visible and
12724                 // use it in place of this one.
12725                 SkipBody->ShouldSkip = true;
12726                 makeMergedDefinitionVisible(Hidden, KWLoc);
12727                 return Def;
12728               } else if (!IsExplicitSpecializationAfterInstantiation) {
12729                 // A redeclaration in function prototype scope in C isn't
12730                 // visible elsewhere, so merely issue a warning.
12731                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
12732                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
12733                 else
12734                   Diag(NameLoc, diag::err_redefinition) << Name;
12735                 Diag(Def->getLocation(), diag::note_previous_definition);
12736                 // If this is a redefinition, recover by making this
12737                 // struct be anonymous, which will make any later
12738                 // references get the previous definition.
12739                 Name = nullptr;
12740                 Previous.clear();
12741                 Invalid = true;
12742               }
12743             } else {
12744               // If the type is currently being defined, complain
12745               // about a nested redefinition.
12746               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
12747               if (TD->isBeingDefined()) {
12748                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
12749                 Diag(PrevTagDecl->getLocation(),
12750                      diag::note_previous_definition);
12751                 Name = nullptr;
12752                 Previous.clear();
12753                 Invalid = true;
12754               }
12755             }
12756 
12757             // Okay, this is definition of a previously declared or referenced
12758             // tag. We're going to create a new Decl for it.
12759           }
12760 
12761           // Okay, we're going to make a redeclaration.  If this is some kind
12762           // of reference, make sure we build the redeclaration in the same DC
12763           // as the original, and ignore the current access specifier.
12764           if (TUK == TUK_Friend || TUK == TUK_Reference) {
12765             SearchDC = PrevTagDecl->getDeclContext();
12766             AS = AS_none;
12767           }
12768         }
12769         // If we get here we have (another) forward declaration or we
12770         // have a definition.  Just create a new decl.
12771 
12772       } else {
12773         // If we get here, this is a definition of a new tag type in a nested
12774         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
12775         // new decl/type.  We set PrevDecl to NULL so that the entities
12776         // have distinct types.
12777         Previous.clear();
12778       }
12779       // If we get here, we're going to create a new Decl. If PrevDecl
12780       // is non-NULL, it's a definition of the tag declared by
12781       // PrevDecl. If it's NULL, we have a new definition.
12782 
12783     // Otherwise, PrevDecl is not a tag, but was found with tag
12784     // lookup.  This is only actually possible in C++, where a few
12785     // things like templates still live in the tag namespace.
12786     } else {
12787       // Use a better diagnostic if an elaborated-type-specifier
12788       // found the wrong kind of type on the first
12789       // (non-redeclaration) lookup.
12790       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
12791           !Previous.isForRedeclaration()) {
12792         unsigned Kind = 0;
12793         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12794         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12795         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12796         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
12797         Diag(PrevDecl->getLocation(), diag::note_declared_at);
12798         Invalid = true;
12799 
12800       // Otherwise, only diagnose if the declaration is in scope.
12801       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
12802                                 SS.isNotEmpty() || isExplicitSpecialization)) {
12803         // do nothing
12804 
12805       // Diagnose implicit declarations introduced by elaborated types.
12806       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
12807         unsigned Kind = 0;
12808         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12809         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12810         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12811         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
12812         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12813         Invalid = true;
12814 
12815       // Otherwise it's a declaration.  Call out a particularly common
12816       // case here.
12817       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12818         unsigned Kind = 0;
12819         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
12820         Diag(NameLoc, diag::err_tag_definition_of_typedef)
12821           << Name << Kind << TND->getUnderlyingType();
12822         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12823         Invalid = true;
12824 
12825       // Otherwise, diagnose.
12826       } else {
12827         // The tag name clashes with something else in the target scope,
12828         // issue an error and recover by making this tag be anonymous.
12829         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
12830         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12831         Name = nullptr;
12832         Invalid = true;
12833       }
12834 
12835       // The existing declaration isn't relevant to us; we're in a
12836       // new scope, so clear out the previous declaration.
12837       Previous.clear();
12838     }
12839   }
12840 
12841 CreateNewDecl:
12842 
12843   TagDecl *PrevDecl = nullptr;
12844   if (Previous.isSingleResult())
12845     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
12846 
12847   // If there is an identifier, use the location of the identifier as the
12848   // location of the decl, otherwise use the location of the struct/union
12849   // keyword.
12850   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
12851 
12852   // Otherwise, create a new declaration. If there is a previous
12853   // declaration of the same entity, the two will be linked via
12854   // PrevDecl.
12855   TagDecl *New;
12856 
12857   bool IsForwardReference = false;
12858   if (Kind == TTK_Enum) {
12859     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12860     // enum X { A, B, C } D;    D should chain to X.
12861     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
12862                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
12863                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
12864     // If this is an undefined enum, warn.
12865     if (TUK != TUK_Definition && !Invalid) {
12866       TagDecl *Def;
12867       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
12868           cast<EnumDecl>(New)->isFixed()) {
12869         // C++0x: 7.2p2: opaque-enum-declaration.
12870         // Conflicts are diagnosed above. Do nothing.
12871       }
12872       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
12873         Diag(Loc, diag::ext_forward_ref_enum_def)
12874           << New;
12875         Diag(Def->getLocation(), diag::note_previous_definition);
12876       } else {
12877         unsigned DiagID = diag::ext_forward_ref_enum;
12878         if (getLangOpts().MSVCCompat)
12879           DiagID = diag::ext_ms_forward_ref_enum;
12880         else if (getLangOpts().CPlusPlus)
12881           DiagID = diag::err_forward_ref_enum;
12882         Diag(Loc, DiagID);
12883 
12884         // If this is a forward-declared reference to an enumeration, make a
12885         // note of it; we won't actually be introducing the declaration into
12886         // the declaration context.
12887         if (TUK == TUK_Reference)
12888           IsForwardReference = true;
12889       }
12890     }
12891 
12892     if (EnumUnderlying) {
12893       EnumDecl *ED = cast<EnumDecl>(New);
12894       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12895         ED->setIntegerTypeSourceInfo(TI);
12896       else
12897         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
12898       ED->setPromotionType(ED->getIntegerType());
12899     }
12900   } else {
12901     // struct/union/class
12902 
12903     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12904     // struct X { int A; } D;    D should chain to X.
12905     if (getLangOpts().CPlusPlus) {
12906       // FIXME: Look for a way to use RecordDecl for simple structs.
12907       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12908                                   cast_or_null<CXXRecordDecl>(PrevDecl));
12909 
12910       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
12911         StdBadAlloc = cast<CXXRecordDecl>(New);
12912     } else
12913       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12914                                cast_or_null<RecordDecl>(PrevDecl));
12915   }
12916 
12917   // C++11 [dcl.type]p3:
12918   //   A type-specifier-seq shall not define a class or enumeration [...].
12919   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
12920     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
12921       << Context.getTagDeclType(New);
12922     Invalid = true;
12923   }
12924 
12925   // Maybe add qualifier info.
12926   if (SS.isNotEmpty()) {
12927     if (SS.isSet()) {
12928       // If this is either a declaration or a definition, check the
12929       // nested-name-specifier against the current context. We don't do this
12930       // for explicit specializations, because they have similar checking
12931       // (with more specific diagnostics) in the call to
12932       // CheckMemberSpecialization, below.
12933       if (!isExplicitSpecialization &&
12934           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
12935           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
12936         Invalid = true;
12937 
12938       New->setQualifierInfo(SS.getWithLocInContext(Context));
12939       if (TemplateParameterLists.size() > 0) {
12940         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
12941       }
12942     }
12943     else
12944       Invalid = true;
12945   }
12946 
12947   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
12948     // Add alignment attributes if necessary; these attributes are checked when
12949     // the ASTContext lays out the structure.
12950     //
12951     // It is important for implementing the correct semantics that this
12952     // happen here (in act on tag decl). The #pragma pack stack is
12953     // maintained as a result of parser callbacks which can occur at
12954     // many points during the parsing of a struct declaration (because
12955     // the #pragma tokens are effectively skipped over during the
12956     // parsing of the struct).
12957     if (TUK == TUK_Definition) {
12958       AddAlignmentAttributesForRecord(RD);
12959       AddMsStructLayoutForRecord(RD);
12960     }
12961   }
12962 
12963   if (ModulePrivateLoc.isValid()) {
12964     if (isExplicitSpecialization)
12965       Diag(New->getLocation(), diag::err_module_private_specialization)
12966         << 2
12967         << FixItHint::CreateRemoval(ModulePrivateLoc);
12968     // __module_private__ does not apply to local classes. However, we only
12969     // diagnose this as an error when the declaration specifiers are
12970     // freestanding. Here, we just ignore the __module_private__.
12971     else if (!SearchDC->isFunctionOrMethod())
12972       New->setModulePrivate();
12973   }
12974 
12975   // If this is a specialization of a member class (of a class template),
12976   // check the specialization.
12977   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
12978     Invalid = true;
12979 
12980   // If we're declaring or defining a tag in function prototype scope in C,
12981   // note that this type can only be used within the function and add it to
12982   // the list of decls to inject into the function definition scope.
12983   if ((Name || Kind == TTK_Enum) &&
12984       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
12985     if (getLangOpts().CPlusPlus) {
12986       // C++ [dcl.fct]p6:
12987       //   Types shall not be defined in return or parameter types.
12988       if (TUK == TUK_Definition && !IsTypeSpecifier) {
12989         Diag(Loc, diag::err_type_defined_in_param_type)
12990             << Name;
12991         Invalid = true;
12992       }
12993     } else if (!PrevDecl) {
12994       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
12995     }
12996     DeclsInPrototypeScope.push_back(New);
12997   }
12998 
12999   if (Invalid)
13000     New->setInvalidDecl();
13001 
13002   if (Attr)
13003     ProcessDeclAttributeList(S, New, Attr);
13004 
13005   // Set the lexical context. If the tag has a C++ scope specifier, the
13006   // lexical context will be different from the semantic context.
13007   New->setLexicalDeclContext(CurContext);
13008 
13009   // Mark this as a friend decl if applicable.
13010   // In Microsoft mode, a friend declaration also acts as a forward
13011   // declaration so we always pass true to setObjectOfFriendDecl to make
13012   // the tag name visible.
13013   if (TUK == TUK_Friend)
13014     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
13015 
13016   // Set the access specifier.
13017   if (!Invalid && SearchDC->isRecord())
13018     SetMemberAccessSpecifier(New, PrevDecl, AS);
13019 
13020   if (TUK == TUK_Definition)
13021     New->startDefinition();
13022 
13023   // If this has an identifier, add it to the scope stack.
13024   if (TUK == TUK_Friend) {
13025     // We might be replacing an existing declaration in the lookup tables;
13026     // if so, borrow its access specifier.
13027     if (PrevDecl)
13028       New->setAccess(PrevDecl->getAccess());
13029 
13030     DeclContext *DC = New->getDeclContext()->getRedeclContext();
13031     DC->makeDeclVisibleInContext(New);
13032     if (Name) // can be null along some error paths
13033       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13034         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
13035   } else if (Name) {
13036     S = getNonFieldDeclScope(S);
13037     PushOnScopeChains(New, S, !IsForwardReference);
13038     if (IsForwardReference)
13039       SearchDC->makeDeclVisibleInContext(New);
13040   } else {
13041     CurContext->addDecl(New);
13042   }
13043 
13044   // If this is the C FILE type, notify the AST context.
13045   if (IdentifierInfo *II = New->getIdentifier())
13046     if (!New->isInvalidDecl() &&
13047         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
13048         II->isStr("FILE"))
13049       Context.setFILEDecl(New);
13050 
13051   if (PrevDecl)
13052     mergeDeclAttributes(New, PrevDecl);
13053 
13054   // If there's a #pragma GCC visibility in scope, set the visibility of this
13055   // record.
13056   AddPushedVisibilityAttribute(New);
13057 
13058   OwnedDecl = true;
13059   // In C++, don't return an invalid declaration. We can't recover well from
13060   // the cases where we make the type anonymous.
13061   return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
13062 }
13063 
13064 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
13065   AdjustDeclIfTemplate(TagD);
13066   TagDecl *Tag = cast<TagDecl>(TagD);
13067 
13068   // Enter the tag context.
13069   PushDeclContext(S, Tag);
13070 
13071   ActOnDocumentableDecl(TagD);
13072 
13073   // If there's a #pragma GCC visibility in scope, set the visibility of this
13074   // record.
13075   AddPushedVisibilityAttribute(Tag);
13076 }
13077 
13078 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
13079   assert(isa<ObjCContainerDecl>(IDecl) &&
13080          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
13081   DeclContext *OCD = cast<DeclContext>(IDecl);
13082   assert(getContainingDC(OCD) == CurContext &&
13083       "The next DeclContext should be lexically contained in the current one.");
13084   CurContext = OCD;
13085   return IDecl;
13086 }
13087 
13088 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
13089                                            SourceLocation FinalLoc,
13090                                            bool IsFinalSpelledSealed,
13091                                            SourceLocation LBraceLoc) {
13092   AdjustDeclIfTemplate(TagD);
13093   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
13094 
13095   FieldCollector->StartClass();
13096 
13097   if (!Record->getIdentifier())
13098     return;
13099 
13100   if (FinalLoc.isValid())
13101     Record->addAttr(new (Context)
13102                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
13103 
13104   // C++ [class]p2:
13105   //   [...] The class-name is also inserted into the scope of the
13106   //   class itself; this is known as the injected-class-name. For
13107   //   purposes of access checking, the injected-class-name is treated
13108   //   as if it were a public member name.
13109   CXXRecordDecl *InjectedClassName
13110     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
13111                             Record->getLocStart(), Record->getLocation(),
13112                             Record->getIdentifier(),
13113                             /*PrevDecl=*/nullptr,
13114                             /*DelayTypeCreation=*/true);
13115   Context.getTypeDeclType(InjectedClassName, Record);
13116   InjectedClassName->setImplicit();
13117   InjectedClassName->setAccess(AS_public);
13118   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
13119       InjectedClassName->setDescribedClassTemplate(Template);
13120   PushOnScopeChains(InjectedClassName, S);
13121   assert(InjectedClassName->isInjectedClassName() &&
13122          "Broken injected-class-name");
13123 }
13124 
13125 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
13126                                     SourceLocation RBraceLoc) {
13127   AdjustDeclIfTemplate(TagD);
13128   TagDecl *Tag = cast<TagDecl>(TagD);
13129   Tag->setRBraceLoc(RBraceLoc);
13130 
13131   // Make sure we "complete" the definition even it is invalid.
13132   if (Tag->isBeingDefined()) {
13133     assert(Tag->isInvalidDecl() && "We should already have completed it");
13134     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13135       RD->completeDefinition();
13136   }
13137 
13138   if (isa<CXXRecordDecl>(Tag))
13139     FieldCollector->FinishClass();
13140 
13141   // Exit this scope of this tag's definition.
13142   PopDeclContext();
13143 
13144   if (getCurLexicalContext()->isObjCContainer() &&
13145       Tag->getDeclContext()->isFileContext())
13146     Tag->setTopLevelDeclInObjCContainer();
13147 
13148   // Notify the consumer that we've defined a tag.
13149   if (!Tag->isInvalidDecl())
13150     Consumer.HandleTagDeclDefinition(Tag);
13151 }
13152 
13153 void Sema::ActOnObjCContainerFinishDefinition() {
13154   // Exit this scope of this interface definition.
13155   PopDeclContext();
13156 }
13157 
13158 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
13159   assert(DC == CurContext && "Mismatch of container contexts");
13160   OriginalLexicalContext = DC;
13161   ActOnObjCContainerFinishDefinition();
13162 }
13163 
13164 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
13165   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
13166   OriginalLexicalContext = nullptr;
13167 }
13168 
13169 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
13170   AdjustDeclIfTemplate(TagD);
13171   TagDecl *Tag = cast<TagDecl>(TagD);
13172   Tag->setInvalidDecl();
13173 
13174   // Make sure we "complete" the definition even it is invalid.
13175   if (Tag->isBeingDefined()) {
13176     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
13177       RD->completeDefinition();
13178   }
13179 
13180   // We're undoing ActOnTagStartDefinition here, not
13181   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
13182   // the FieldCollector.
13183 
13184   PopDeclContext();
13185 }
13186 
13187 // Note that FieldName may be null for anonymous bitfields.
13188 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
13189                                 IdentifierInfo *FieldName,
13190                                 QualType FieldTy, bool IsMsStruct,
13191                                 Expr *BitWidth, bool *ZeroWidth) {
13192   // Default to true; that shouldn't confuse checks for emptiness
13193   if (ZeroWidth)
13194     *ZeroWidth = true;
13195 
13196   // C99 6.7.2.1p4 - verify the field type.
13197   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
13198   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
13199     // Handle incomplete types with specific error.
13200     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
13201       return ExprError();
13202     if (FieldName)
13203       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
13204         << FieldName << FieldTy << BitWidth->getSourceRange();
13205     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
13206       << FieldTy << BitWidth->getSourceRange();
13207   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
13208                                              UPPC_BitFieldWidth))
13209     return ExprError();
13210 
13211   // If the bit-width is type- or value-dependent, don't try to check
13212   // it now.
13213   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
13214     return BitWidth;
13215 
13216   llvm::APSInt Value;
13217   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
13218   if (ICE.isInvalid())
13219     return ICE;
13220   BitWidth = ICE.get();
13221 
13222   if (Value != 0 && ZeroWidth)
13223     *ZeroWidth = false;
13224 
13225   // Zero-width bitfield is ok for anonymous field.
13226   if (Value == 0 && FieldName)
13227     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
13228 
13229   if (Value.isSigned() && Value.isNegative()) {
13230     if (FieldName)
13231       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
13232                << FieldName << Value.toString(10);
13233     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
13234       << Value.toString(10);
13235   }
13236 
13237   if (!FieldTy->isDependentType()) {
13238     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
13239     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
13240     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
13241 
13242     // Over-wide bitfields are an error in C or when using the MSVC bitfield
13243     // ABI.
13244     bool CStdConstraintViolation =
13245         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
13246     bool MSBitfieldViolation =
13247         Value.ugt(TypeStorageSize) &&
13248         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
13249     if (CStdConstraintViolation || MSBitfieldViolation) {
13250       unsigned DiagWidth =
13251           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
13252       if (FieldName)
13253         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
13254                << FieldName << (unsigned)Value.getZExtValue()
13255                << !CStdConstraintViolation << DiagWidth;
13256 
13257       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
13258              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
13259              << DiagWidth;
13260     }
13261 
13262     // Warn on types where the user might conceivably expect to get all
13263     // specified bits as value bits: that's all integral types other than
13264     // 'bool'.
13265     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
13266       if (FieldName)
13267         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
13268             << FieldName << (unsigned)Value.getZExtValue()
13269             << (unsigned)TypeWidth;
13270       else
13271         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
13272             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
13273     }
13274   }
13275 
13276   return BitWidth;
13277 }
13278 
13279 /// ActOnField - Each field of a C struct/union is passed into this in order
13280 /// to create a FieldDecl object for it.
13281 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
13282                        Declarator &D, Expr *BitfieldWidth) {
13283   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
13284                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
13285                                /*InitStyle=*/ICIS_NoInit, AS_public);
13286   return Res;
13287 }
13288 
13289 /// HandleField - Analyze a field of a C struct or a C++ data member.
13290 ///
13291 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
13292                              SourceLocation DeclStart,
13293                              Declarator &D, Expr *BitWidth,
13294                              InClassInitStyle InitStyle,
13295                              AccessSpecifier AS) {
13296   IdentifierInfo *II = D.getIdentifier();
13297   SourceLocation Loc = DeclStart;
13298   if (II) Loc = D.getIdentifierLoc();
13299 
13300   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13301   QualType T = TInfo->getType();
13302   if (getLangOpts().CPlusPlus) {
13303     CheckExtraCXXDefaultArguments(D);
13304 
13305     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13306                                         UPPC_DataMemberType)) {
13307       D.setInvalidType();
13308       T = Context.IntTy;
13309       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
13310     }
13311   }
13312 
13313   // TR 18037 does not allow fields to be declared with address spaces.
13314   if (T.getQualifiers().hasAddressSpace()) {
13315     Diag(Loc, diag::err_field_with_address_space);
13316     D.setInvalidType();
13317   }
13318 
13319   // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
13320   // used as structure or union field: image, sampler, event or block types.
13321   if (LangOpts.OpenCL && (T->isEventT() || T->isImageType() ||
13322                           T->isSamplerT() || T->isBlockPointerType())) {
13323     Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
13324     D.setInvalidType();
13325   }
13326 
13327   DiagnoseFunctionSpecifiers(D.getDeclSpec());
13328 
13329   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
13330     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
13331          diag::err_invalid_thread)
13332       << DeclSpec::getSpecifierName(TSCS);
13333 
13334   // Check to see if this name was declared as a member previously
13335   NamedDecl *PrevDecl = nullptr;
13336   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
13337   LookupName(Previous, S);
13338   switch (Previous.getResultKind()) {
13339     case LookupResult::Found:
13340     case LookupResult::FoundUnresolvedValue:
13341       PrevDecl = Previous.getAsSingle<NamedDecl>();
13342       break;
13343 
13344     case LookupResult::FoundOverloaded:
13345       PrevDecl = Previous.getRepresentativeDecl();
13346       break;
13347 
13348     case LookupResult::NotFound:
13349     case LookupResult::NotFoundInCurrentInstantiation:
13350     case LookupResult::Ambiguous:
13351       break;
13352   }
13353   Previous.suppressDiagnostics();
13354 
13355   if (PrevDecl && PrevDecl->isTemplateParameter()) {
13356     // Maybe we will complain about the shadowed template parameter.
13357     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13358     // Just pretend that we didn't see the previous declaration.
13359     PrevDecl = nullptr;
13360   }
13361 
13362   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
13363     PrevDecl = nullptr;
13364 
13365   bool Mutable
13366     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
13367   SourceLocation TSSL = D.getLocStart();
13368   FieldDecl *NewFD
13369     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
13370                      TSSL, AS, PrevDecl, &D);
13371 
13372   if (NewFD->isInvalidDecl())
13373     Record->setInvalidDecl();
13374 
13375   if (D.getDeclSpec().isModulePrivateSpecified())
13376     NewFD->setModulePrivate();
13377 
13378   if (NewFD->isInvalidDecl() && PrevDecl) {
13379     // Don't introduce NewFD into scope; there's already something
13380     // with the same name in the same scope.
13381   } else if (II) {
13382     PushOnScopeChains(NewFD, S);
13383   } else
13384     Record->addDecl(NewFD);
13385 
13386   return NewFD;
13387 }
13388 
13389 /// \brief Build a new FieldDecl and check its well-formedness.
13390 ///
13391 /// This routine builds a new FieldDecl given the fields name, type,
13392 /// record, etc. \p PrevDecl should refer to any previous declaration
13393 /// with the same name and in the same scope as the field to be
13394 /// created.
13395 ///
13396 /// \returns a new FieldDecl.
13397 ///
13398 /// \todo The Declarator argument is a hack. It will be removed once
13399 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
13400                                 TypeSourceInfo *TInfo,
13401                                 RecordDecl *Record, SourceLocation Loc,
13402                                 bool Mutable, Expr *BitWidth,
13403                                 InClassInitStyle InitStyle,
13404                                 SourceLocation TSSL,
13405                                 AccessSpecifier AS, NamedDecl *PrevDecl,
13406                                 Declarator *D) {
13407   IdentifierInfo *II = Name.getAsIdentifierInfo();
13408   bool InvalidDecl = false;
13409   if (D) InvalidDecl = D->isInvalidType();
13410 
13411   // If we receive a broken type, recover by assuming 'int' and
13412   // marking this declaration as invalid.
13413   if (T.isNull()) {
13414     InvalidDecl = true;
13415     T = Context.IntTy;
13416   }
13417 
13418   QualType EltTy = Context.getBaseElementType(T);
13419   if (!EltTy->isDependentType()) {
13420     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
13421       // Fields of incomplete type force their record to be invalid.
13422       Record->setInvalidDecl();
13423       InvalidDecl = true;
13424     } else {
13425       NamedDecl *Def;
13426       EltTy->isIncompleteType(&Def);
13427       if (Def && Def->isInvalidDecl()) {
13428         Record->setInvalidDecl();
13429         InvalidDecl = true;
13430       }
13431     }
13432   }
13433 
13434   // OpenCL v1.2 s6.9.c: bitfields are not supported.
13435   if (BitWidth && getLangOpts().OpenCL) {
13436     Diag(Loc, diag::err_opencl_bitfields);
13437     InvalidDecl = true;
13438   }
13439 
13440   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13441   // than a variably modified type.
13442   if (!InvalidDecl && T->isVariablyModifiedType()) {
13443     bool SizeIsNegative;
13444     llvm::APSInt Oversized;
13445 
13446     TypeSourceInfo *FixedTInfo =
13447       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
13448                                                     SizeIsNegative,
13449                                                     Oversized);
13450     if (FixedTInfo) {
13451       Diag(Loc, diag::warn_illegal_constant_array_size);
13452       TInfo = FixedTInfo;
13453       T = FixedTInfo->getType();
13454     } else {
13455       if (SizeIsNegative)
13456         Diag(Loc, diag::err_typecheck_negative_array_size);
13457       else if (Oversized.getBoolValue())
13458         Diag(Loc, diag::err_array_too_large)
13459           << Oversized.toString(10);
13460       else
13461         Diag(Loc, diag::err_typecheck_field_variable_size);
13462       InvalidDecl = true;
13463     }
13464   }
13465 
13466   // Fields can not have abstract class types
13467   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
13468                                              diag::err_abstract_type_in_decl,
13469                                              AbstractFieldType))
13470     InvalidDecl = true;
13471 
13472   bool ZeroWidth = false;
13473   if (InvalidDecl)
13474     BitWidth = nullptr;
13475   // If this is declared as a bit-field, check the bit-field.
13476   if (BitWidth) {
13477     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
13478                               &ZeroWidth).get();
13479     if (!BitWidth) {
13480       InvalidDecl = true;
13481       BitWidth = nullptr;
13482       ZeroWidth = false;
13483     }
13484   }
13485 
13486   // Check that 'mutable' is consistent with the type of the declaration.
13487   if (!InvalidDecl && Mutable) {
13488     unsigned DiagID = 0;
13489     if (T->isReferenceType())
13490       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
13491                                         : diag::err_mutable_reference;
13492     else if (T.isConstQualified())
13493       DiagID = diag::err_mutable_const;
13494 
13495     if (DiagID) {
13496       SourceLocation ErrLoc = Loc;
13497       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
13498         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
13499       Diag(ErrLoc, DiagID);
13500       if (DiagID != diag::ext_mutable_reference) {
13501         Mutable = false;
13502         InvalidDecl = true;
13503       }
13504     }
13505   }
13506 
13507   // C++11 [class.union]p8 (DR1460):
13508   //   At most one variant member of a union may have a
13509   //   brace-or-equal-initializer.
13510   if (InitStyle != ICIS_NoInit)
13511     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
13512 
13513   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
13514                                        BitWidth, Mutable, InitStyle);
13515   if (InvalidDecl)
13516     NewFD->setInvalidDecl();
13517 
13518   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
13519     Diag(Loc, diag::err_duplicate_member) << II;
13520     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13521     NewFD->setInvalidDecl();
13522   }
13523 
13524   if (!InvalidDecl && getLangOpts().CPlusPlus) {
13525     if (Record->isUnion()) {
13526       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13527         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
13528         if (RDecl->getDefinition()) {
13529           // C++ [class.union]p1: An object of a class with a non-trivial
13530           // constructor, a non-trivial copy constructor, a non-trivial
13531           // destructor, or a non-trivial copy assignment operator
13532           // cannot be a member of a union, nor can an array of such
13533           // objects.
13534           if (CheckNontrivialField(NewFD))
13535             NewFD->setInvalidDecl();
13536         }
13537       }
13538 
13539       // C++ [class.union]p1: If a union contains a member of reference type,
13540       // the program is ill-formed, except when compiling with MSVC extensions
13541       // enabled.
13542       if (EltTy->isReferenceType()) {
13543         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
13544                                     diag::ext_union_member_of_reference_type :
13545                                     diag::err_union_member_of_reference_type)
13546           << NewFD->getDeclName() << EltTy;
13547         if (!getLangOpts().MicrosoftExt)
13548           NewFD->setInvalidDecl();
13549       }
13550     }
13551   }
13552 
13553   // FIXME: We need to pass in the attributes given an AST
13554   // representation, not a parser representation.
13555   if (D) {
13556     // FIXME: The current scope is almost... but not entirely... correct here.
13557     ProcessDeclAttributes(getCurScope(), NewFD, *D);
13558 
13559     if (NewFD->hasAttrs())
13560       CheckAlignasUnderalignment(NewFD);
13561   }
13562 
13563   // In auto-retain/release, infer strong retension for fields of
13564   // retainable type.
13565   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
13566     NewFD->setInvalidDecl();
13567 
13568   if (T.isObjCGCWeak())
13569     Diag(Loc, diag::warn_attribute_weak_on_field);
13570 
13571   NewFD->setAccess(AS);
13572   return NewFD;
13573 }
13574 
13575 bool Sema::CheckNontrivialField(FieldDecl *FD) {
13576   assert(FD);
13577   assert(getLangOpts().CPlusPlus && "valid check only for C++");
13578 
13579   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
13580     return false;
13581 
13582   QualType EltTy = Context.getBaseElementType(FD->getType());
13583   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13584     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
13585     if (RDecl->getDefinition()) {
13586       // We check for copy constructors before constructors
13587       // because otherwise we'll never get complaints about
13588       // copy constructors.
13589 
13590       CXXSpecialMember member = CXXInvalid;
13591       // We're required to check for any non-trivial constructors. Since the
13592       // implicit default constructor is suppressed if there are any
13593       // user-declared constructors, we just need to check that there is a
13594       // trivial default constructor and a trivial copy constructor. (We don't
13595       // worry about move constructors here, since this is a C++98 check.)
13596       if (RDecl->hasNonTrivialCopyConstructor())
13597         member = CXXCopyConstructor;
13598       else if (!RDecl->hasTrivialDefaultConstructor())
13599         member = CXXDefaultConstructor;
13600       else if (RDecl->hasNonTrivialCopyAssignment())
13601         member = CXXCopyAssignment;
13602       else if (RDecl->hasNonTrivialDestructor())
13603         member = CXXDestructor;
13604 
13605       if (member != CXXInvalid) {
13606         if (!getLangOpts().CPlusPlus11 &&
13607             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
13608           // Objective-C++ ARC: it is an error to have a non-trivial field of
13609           // a union. However, system headers in Objective-C programs
13610           // occasionally have Objective-C lifetime objects within unions,
13611           // and rather than cause the program to fail, we make those
13612           // members unavailable.
13613           SourceLocation Loc = FD->getLocation();
13614           if (getSourceManager().isInSystemHeader(Loc)) {
13615             if (!FD->hasAttr<UnavailableAttr>())
13616               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13617                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
13618             return false;
13619           }
13620         }
13621 
13622         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
13623                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
13624                diag::err_illegal_union_or_anon_struct_member)
13625           << FD->getParent()->isUnion() << FD->getDeclName() << member;
13626         DiagnoseNontrivial(RDecl, member);
13627         return !getLangOpts().CPlusPlus11;
13628       }
13629     }
13630   }
13631 
13632   return false;
13633 }
13634 
13635 /// TranslateIvarVisibility - Translate visibility from a token ID to an
13636 ///  AST enum value.
13637 static ObjCIvarDecl::AccessControl
13638 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
13639   switch (ivarVisibility) {
13640   default: llvm_unreachable("Unknown visitibility kind");
13641   case tok::objc_private: return ObjCIvarDecl::Private;
13642   case tok::objc_public: return ObjCIvarDecl::Public;
13643   case tok::objc_protected: return ObjCIvarDecl::Protected;
13644   case tok::objc_package: return ObjCIvarDecl::Package;
13645   }
13646 }
13647 
13648 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
13649 /// in order to create an IvarDecl object for it.
13650 Decl *Sema::ActOnIvar(Scope *S,
13651                                 SourceLocation DeclStart,
13652                                 Declarator &D, Expr *BitfieldWidth,
13653                                 tok::ObjCKeywordKind Visibility) {
13654 
13655   IdentifierInfo *II = D.getIdentifier();
13656   Expr *BitWidth = (Expr*)BitfieldWidth;
13657   SourceLocation Loc = DeclStart;
13658   if (II) Loc = D.getIdentifierLoc();
13659 
13660   // FIXME: Unnamed fields can be handled in various different ways, for
13661   // example, unnamed unions inject all members into the struct namespace!
13662 
13663   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13664   QualType T = TInfo->getType();
13665 
13666   if (BitWidth) {
13667     // 6.7.2.1p3, 6.7.2.1p4
13668     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
13669     if (!BitWidth)
13670       D.setInvalidType();
13671   } else {
13672     // Not a bitfield.
13673 
13674     // validate II.
13675 
13676   }
13677   if (T->isReferenceType()) {
13678     Diag(Loc, diag::err_ivar_reference_type);
13679     D.setInvalidType();
13680   }
13681   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13682   // than a variably modified type.
13683   else if (T->isVariablyModifiedType()) {
13684     Diag(Loc, diag::err_typecheck_ivar_variable_size);
13685     D.setInvalidType();
13686   }
13687 
13688   // Get the visibility (access control) for this ivar.
13689   ObjCIvarDecl::AccessControl ac =
13690     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
13691                                         : ObjCIvarDecl::None;
13692   // Must set ivar's DeclContext to its enclosing interface.
13693   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
13694   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
13695     return nullptr;
13696   ObjCContainerDecl *EnclosingContext;
13697   if (ObjCImplementationDecl *IMPDecl =
13698       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13699     if (LangOpts.ObjCRuntime.isFragile()) {
13700     // Case of ivar declared in an implementation. Context is that of its class.
13701       EnclosingContext = IMPDecl->getClassInterface();
13702       assert(EnclosingContext && "Implementation has no class interface!");
13703     }
13704     else
13705       EnclosingContext = EnclosingDecl;
13706   } else {
13707     if (ObjCCategoryDecl *CDecl =
13708         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13709       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
13710         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
13711         return nullptr;
13712       }
13713     }
13714     EnclosingContext = EnclosingDecl;
13715   }
13716 
13717   // Construct the decl.
13718   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
13719                                              DeclStart, Loc, II, T,
13720                                              TInfo, ac, (Expr *)BitfieldWidth);
13721 
13722   if (II) {
13723     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
13724                                            ForRedeclaration);
13725     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
13726         && !isa<TagDecl>(PrevDecl)) {
13727       Diag(Loc, diag::err_duplicate_member) << II;
13728       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13729       NewID->setInvalidDecl();
13730     }
13731   }
13732 
13733   // Process attributes attached to the ivar.
13734   ProcessDeclAttributes(S, NewID, D);
13735 
13736   if (D.isInvalidType())
13737     NewID->setInvalidDecl();
13738 
13739   // In ARC, infer 'retaining' for ivars of retainable type.
13740   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
13741     NewID->setInvalidDecl();
13742 
13743   if (D.getDeclSpec().isModulePrivateSpecified())
13744     NewID->setModulePrivate();
13745 
13746   if (II) {
13747     // FIXME: When interfaces are DeclContexts, we'll need to add
13748     // these to the interface.
13749     S->AddDecl(NewID);
13750     IdResolver.AddDecl(NewID);
13751   }
13752 
13753   if (LangOpts.ObjCRuntime.isNonFragile() &&
13754       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
13755     Diag(Loc, diag::warn_ivars_in_interface);
13756 
13757   return NewID;
13758 }
13759 
13760 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
13761 /// class and class extensions. For every class \@interface and class
13762 /// extension \@interface, if the last ivar is a bitfield of any type,
13763 /// then add an implicit `char :0` ivar to the end of that interface.
13764 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
13765                              SmallVectorImpl<Decl *> &AllIvarDecls) {
13766   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
13767     return;
13768 
13769   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
13770   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
13771 
13772   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
13773     return;
13774   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
13775   if (!ID) {
13776     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
13777       if (!CD->IsClassExtension())
13778         return;
13779     }
13780     // No need to add this to end of @implementation.
13781     else
13782       return;
13783   }
13784   // All conditions are met. Add a new bitfield to the tail end of ivars.
13785   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
13786   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
13787 
13788   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
13789                               DeclLoc, DeclLoc, nullptr,
13790                               Context.CharTy,
13791                               Context.getTrivialTypeSourceInfo(Context.CharTy,
13792                                                                DeclLoc),
13793                               ObjCIvarDecl::Private, BW,
13794                               true);
13795   AllIvarDecls.push_back(Ivar);
13796 }
13797 
13798 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
13799                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
13800                        SourceLocation RBrac, AttributeList *Attr) {
13801   assert(EnclosingDecl && "missing record or interface decl");
13802 
13803   // If this is an Objective-C @implementation or category and we have
13804   // new fields here we should reset the layout of the interface since
13805   // it will now change.
13806   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
13807     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
13808     switch (DC->getKind()) {
13809     default: break;
13810     case Decl::ObjCCategory:
13811       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
13812       break;
13813     case Decl::ObjCImplementation:
13814       Context.
13815         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
13816       break;
13817     }
13818   }
13819 
13820   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
13821 
13822   // Start counting up the number of named members; make sure to include
13823   // members of anonymous structs and unions in the total.
13824   unsigned NumNamedMembers = 0;
13825   if (Record) {
13826     for (const auto *I : Record->decls()) {
13827       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
13828         if (IFD->getDeclName())
13829           ++NumNamedMembers;
13830     }
13831   }
13832 
13833   // Verify that all the fields are okay.
13834   SmallVector<FieldDecl*, 32> RecFields;
13835 
13836   bool ARCErrReported = false;
13837   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
13838        i != end; ++i) {
13839     FieldDecl *FD = cast<FieldDecl>(*i);
13840 
13841     // Get the type for the field.
13842     const Type *FDTy = FD->getType().getTypePtr();
13843 
13844     if (!FD->isAnonymousStructOrUnion()) {
13845       // Remember all fields written by the user.
13846       RecFields.push_back(FD);
13847     }
13848 
13849     // If the field is already invalid for some reason, don't emit more
13850     // diagnostics about it.
13851     if (FD->isInvalidDecl()) {
13852       EnclosingDecl->setInvalidDecl();
13853       continue;
13854     }
13855 
13856     // C99 6.7.2.1p2:
13857     //   A structure or union shall not contain a member with
13858     //   incomplete or function type (hence, a structure shall not
13859     //   contain an instance of itself, but may contain a pointer to
13860     //   an instance of itself), except that the last member of a
13861     //   structure with more than one named member may have incomplete
13862     //   array type; such a structure (and any union containing,
13863     //   possibly recursively, a member that is such a structure)
13864     //   shall not be a member of a structure or an element of an
13865     //   array.
13866     if (FDTy->isFunctionType()) {
13867       // Field declared as a function.
13868       Diag(FD->getLocation(), diag::err_field_declared_as_function)
13869         << FD->getDeclName();
13870       FD->setInvalidDecl();
13871       EnclosingDecl->setInvalidDecl();
13872       continue;
13873     } else if (FDTy->isIncompleteArrayType() && Record &&
13874                ((i + 1 == Fields.end() && !Record->isUnion()) ||
13875                 ((getLangOpts().MicrosoftExt ||
13876                   getLangOpts().CPlusPlus) &&
13877                  (i + 1 == Fields.end() || Record->isUnion())))) {
13878       // Flexible array member.
13879       // Microsoft and g++ is more permissive regarding flexible array.
13880       // It will accept flexible array in union and also
13881       // as the sole element of a struct/class.
13882       unsigned DiagID = 0;
13883       if (Record->isUnion())
13884         DiagID = getLangOpts().MicrosoftExt
13885                      ? diag::ext_flexible_array_union_ms
13886                      : getLangOpts().CPlusPlus
13887                            ? diag::ext_flexible_array_union_gnu
13888                            : diag::err_flexible_array_union;
13889       else if (Fields.size() == 1)
13890         DiagID = getLangOpts().MicrosoftExt
13891                      ? diag::ext_flexible_array_empty_aggregate_ms
13892                      : getLangOpts().CPlusPlus
13893                            ? diag::ext_flexible_array_empty_aggregate_gnu
13894                            : NumNamedMembers < 1
13895                                  ? diag::err_flexible_array_empty_aggregate
13896                                  : 0;
13897 
13898       if (DiagID)
13899         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
13900                                         << Record->getTagKind();
13901       // While the layout of types that contain virtual bases is not specified
13902       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
13903       // virtual bases after the derived members.  This would make a flexible
13904       // array member declared at the end of an object not adjacent to the end
13905       // of the type.
13906       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
13907         if (RD->getNumVBases() != 0)
13908           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
13909             << FD->getDeclName() << Record->getTagKind();
13910       if (!getLangOpts().C99)
13911         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
13912           << FD->getDeclName() << Record->getTagKind();
13913 
13914       // If the element type has a non-trivial destructor, we would not
13915       // implicitly destroy the elements, so disallow it for now.
13916       //
13917       // FIXME: GCC allows this. We should probably either implicitly delete
13918       // the destructor of the containing class, or just allow this.
13919       QualType BaseElem = Context.getBaseElementType(FD->getType());
13920       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
13921         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
13922           << FD->getDeclName() << FD->getType();
13923         FD->setInvalidDecl();
13924         EnclosingDecl->setInvalidDecl();
13925         continue;
13926       }
13927       // Okay, we have a legal flexible array member at the end of the struct.
13928       Record->setHasFlexibleArrayMember(true);
13929     } else if (!FDTy->isDependentType() &&
13930                RequireCompleteType(FD->getLocation(), FD->getType(),
13931                                    diag::err_field_incomplete)) {
13932       // Incomplete type
13933       FD->setInvalidDecl();
13934       EnclosingDecl->setInvalidDecl();
13935       continue;
13936     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
13937       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
13938         // A type which contains a flexible array member is considered to be a
13939         // flexible array member.
13940         Record->setHasFlexibleArrayMember(true);
13941         if (!Record->isUnion()) {
13942           // If this is a struct/class and this is not the last element, reject
13943           // it.  Note that GCC supports variable sized arrays in the middle of
13944           // structures.
13945           if (i + 1 != Fields.end())
13946             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
13947               << FD->getDeclName() << FD->getType();
13948           else {
13949             // We support flexible arrays at the end of structs in
13950             // other structs as an extension.
13951             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
13952               << FD->getDeclName();
13953           }
13954         }
13955       }
13956       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
13957           RequireNonAbstractType(FD->getLocation(), FD->getType(),
13958                                  diag::err_abstract_type_in_decl,
13959                                  AbstractIvarType)) {
13960         // Ivars can not have abstract class types
13961         FD->setInvalidDecl();
13962       }
13963       if (Record && FDTTy->getDecl()->hasObjectMember())
13964         Record->setHasObjectMember(true);
13965       if (Record && FDTTy->getDecl()->hasVolatileMember())
13966         Record->setHasVolatileMember(true);
13967     } else if (FDTy->isObjCObjectType()) {
13968       /// A field cannot be an Objective-c object
13969       Diag(FD->getLocation(), diag::err_statically_allocated_object)
13970         << FixItHint::CreateInsertion(FD->getLocation(), "*");
13971       QualType T = Context.getObjCObjectPointerType(FD->getType());
13972       FD->setType(T);
13973     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
13974                (!getLangOpts().CPlusPlus || Record->isUnion())) {
13975       // It's an error in ARC if a field has lifetime.
13976       // We don't want to report this in a system header, though,
13977       // so we just make the field unavailable.
13978       // FIXME: that's really not sufficient; we need to make the type
13979       // itself invalid to, say, initialize or copy.
13980       QualType T = FD->getType();
13981       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
13982       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
13983         SourceLocation loc = FD->getLocation();
13984         if (getSourceManager().isInSystemHeader(loc)) {
13985           if (!FD->hasAttr<UnavailableAttr>()) {
13986             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13987                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
13988           }
13989         } else {
13990           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
13991             << T->isBlockPointerType() << Record->getTagKind();
13992         }
13993         ARCErrReported = true;
13994       }
13995     } else if (getLangOpts().ObjC1 &&
13996                getLangOpts().getGC() != LangOptions::NonGC &&
13997                Record && !Record->hasObjectMember()) {
13998       if (FD->getType()->isObjCObjectPointerType() ||
13999           FD->getType().isObjCGCStrong())
14000         Record->setHasObjectMember(true);
14001       else if (Context.getAsArrayType(FD->getType())) {
14002         QualType BaseType = Context.getBaseElementType(FD->getType());
14003         if (BaseType->isRecordType() &&
14004             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
14005           Record->setHasObjectMember(true);
14006         else if (BaseType->isObjCObjectPointerType() ||
14007                  BaseType.isObjCGCStrong())
14008                Record->setHasObjectMember(true);
14009       }
14010     }
14011     if (Record && FD->getType().isVolatileQualified())
14012       Record->setHasVolatileMember(true);
14013     // Keep track of the number of named members.
14014     if (FD->getIdentifier())
14015       ++NumNamedMembers;
14016   }
14017 
14018   // Okay, we successfully defined 'Record'.
14019   if (Record) {
14020     bool Completed = false;
14021     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
14022       if (!CXXRecord->isInvalidDecl()) {
14023         // Set access bits correctly on the directly-declared conversions.
14024         for (CXXRecordDecl::conversion_iterator
14025                I = CXXRecord->conversion_begin(),
14026                E = CXXRecord->conversion_end(); I != E; ++I)
14027           I.setAccess((*I)->getAccess());
14028       }
14029 
14030       if (!CXXRecord->isDependentType()) {
14031         if (CXXRecord->hasUserDeclaredDestructor()) {
14032           // Adjust user-defined destructor exception spec.
14033           if (getLangOpts().CPlusPlus11)
14034             AdjustDestructorExceptionSpec(CXXRecord,
14035                                           CXXRecord->getDestructor());
14036         }
14037 
14038         if (!CXXRecord->isInvalidDecl()) {
14039           // Add any implicitly-declared members to this class.
14040           AddImplicitlyDeclaredMembersToClass(CXXRecord);
14041 
14042           // If we have virtual base classes, we may end up finding multiple
14043           // final overriders for a given virtual function. Check for this
14044           // problem now.
14045           if (CXXRecord->getNumVBases()) {
14046             CXXFinalOverriderMap FinalOverriders;
14047             CXXRecord->getFinalOverriders(FinalOverriders);
14048 
14049             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
14050                                              MEnd = FinalOverriders.end();
14051                  M != MEnd; ++M) {
14052               for (OverridingMethods::iterator SO = M->second.begin(),
14053                                             SOEnd = M->second.end();
14054                    SO != SOEnd; ++SO) {
14055                 assert(SO->second.size() > 0 &&
14056                        "Virtual function without overridding functions?");
14057                 if (SO->second.size() == 1)
14058                   continue;
14059 
14060                 // C++ [class.virtual]p2:
14061                 //   In a derived class, if a virtual member function of a base
14062                 //   class subobject has more than one final overrider the
14063                 //   program is ill-formed.
14064                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
14065                   << (const NamedDecl *)M->first << Record;
14066                 Diag(M->first->getLocation(),
14067                      diag::note_overridden_virtual_function);
14068                 for (OverridingMethods::overriding_iterator
14069                           OM = SO->second.begin(),
14070                        OMEnd = SO->second.end();
14071                      OM != OMEnd; ++OM)
14072                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
14073                     << (const NamedDecl *)M->first << OM->Method->getParent();
14074 
14075                 Record->setInvalidDecl();
14076               }
14077             }
14078             CXXRecord->completeDefinition(&FinalOverriders);
14079             Completed = true;
14080           }
14081         }
14082       }
14083     }
14084 
14085     if (!Completed)
14086       Record->completeDefinition();
14087 
14088     if (Record->hasAttrs()) {
14089       CheckAlignasUnderalignment(Record);
14090 
14091       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
14092         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
14093                                            IA->getRange(), IA->getBestCase(),
14094                                            IA->getSemanticSpelling());
14095     }
14096 
14097     // Check if the structure/union declaration is a type that can have zero
14098     // size in C. For C this is a language extension, for C++ it may cause
14099     // compatibility problems.
14100     bool CheckForZeroSize;
14101     if (!getLangOpts().CPlusPlus) {
14102       CheckForZeroSize = true;
14103     } else {
14104       // For C++ filter out types that cannot be referenced in C code.
14105       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
14106       CheckForZeroSize =
14107           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
14108           !CXXRecord->isDependentType() &&
14109           CXXRecord->isCLike();
14110     }
14111     if (CheckForZeroSize) {
14112       bool ZeroSize = true;
14113       bool IsEmpty = true;
14114       unsigned NonBitFields = 0;
14115       for (RecordDecl::field_iterator I = Record->field_begin(),
14116                                       E = Record->field_end();
14117            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
14118         IsEmpty = false;
14119         if (I->isUnnamedBitfield()) {
14120           if (I->getBitWidthValue(Context) > 0)
14121             ZeroSize = false;
14122         } else {
14123           ++NonBitFields;
14124           QualType FieldType = I->getType();
14125           if (FieldType->isIncompleteType() ||
14126               !Context.getTypeSizeInChars(FieldType).isZero())
14127             ZeroSize = false;
14128         }
14129       }
14130 
14131       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
14132       // allowed in C++, but warn if its declaration is inside
14133       // extern "C" block.
14134       if (ZeroSize) {
14135         Diag(RecLoc, getLangOpts().CPlusPlus ?
14136                          diag::warn_zero_size_struct_union_in_extern_c :
14137                          diag::warn_zero_size_struct_union_compat)
14138           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
14139       }
14140 
14141       // Structs without named members are extension in C (C99 6.7.2.1p7),
14142       // but are accepted by GCC.
14143       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
14144         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
14145                                diag::ext_no_named_members_in_struct_union)
14146           << Record->isUnion();
14147       }
14148     }
14149   } else {
14150     ObjCIvarDecl **ClsFields =
14151       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
14152     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
14153       ID->setEndOfDefinitionLoc(RBrac);
14154       // Add ivar's to class's DeclContext.
14155       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14156         ClsFields[i]->setLexicalDeclContext(ID);
14157         ID->addDecl(ClsFields[i]);
14158       }
14159       // Must enforce the rule that ivars in the base classes may not be
14160       // duplicates.
14161       if (ID->getSuperClass())
14162         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
14163     } else if (ObjCImplementationDecl *IMPDecl =
14164                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
14165       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
14166       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
14167         // Ivar declared in @implementation never belongs to the implementation.
14168         // Only it is in implementation's lexical context.
14169         ClsFields[I]->setLexicalDeclContext(IMPDecl);
14170       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
14171       IMPDecl->setIvarLBraceLoc(LBrac);
14172       IMPDecl->setIvarRBraceLoc(RBrac);
14173     } else if (ObjCCategoryDecl *CDecl =
14174                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
14175       // case of ivars in class extension; all other cases have been
14176       // reported as errors elsewhere.
14177       // FIXME. Class extension does not have a LocEnd field.
14178       // CDecl->setLocEnd(RBrac);
14179       // Add ivar's to class extension's DeclContext.
14180       // Diagnose redeclaration of private ivars.
14181       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
14182       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
14183         if (IDecl) {
14184           if (const ObjCIvarDecl *ClsIvar =
14185               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
14186             Diag(ClsFields[i]->getLocation(),
14187                  diag::err_duplicate_ivar_declaration);
14188             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
14189             continue;
14190           }
14191           for (const auto *Ext : IDecl->known_extensions()) {
14192             if (const ObjCIvarDecl *ClsExtIvar
14193                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
14194               Diag(ClsFields[i]->getLocation(),
14195                    diag::err_duplicate_ivar_declaration);
14196               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
14197               continue;
14198             }
14199           }
14200         }
14201         ClsFields[i]->setLexicalDeclContext(CDecl);
14202         CDecl->addDecl(ClsFields[i]);
14203       }
14204       CDecl->setIvarLBraceLoc(LBrac);
14205       CDecl->setIvarRBraceLoc(RBrac);
14206     }
14207   }
14208 
14209   if (Attr)
14210     ProcessDeclAttributeList(S, Record, Attr);
14211 }
14212 
14213 /// \brief Determine whether the given integral value is representable within
14214 /// the given type T.
14215 static bool isRepresentableIntegerValue(ASTContext &Context,
14216                                         llvm::APSInt &Value,
14217                                         QualType T) {
14218   assert(T->isIntegralType(Context) && "Integral type required!");
14219   unsigned BitWidth = Context.getIntWidth(T);
14220 
14221   if (Value.isUnsigned() || Value.isNonNegative()) {
14222     if (T->isSignedIntegerOrEnumerationType())
14223       --BitWidth;
14224     return Value.getActiveBits() <= BitWidth;
14225   }
14226   return Value.getMinSignedBits() <= BitWidth;
14227 }
14228 
14229 // \brief Given an integral type, return the next larger integral type
14230 // (or a NULL type of no such type exists).
14231 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
14232   // FIXME: Int128/UInt128 support, which also needs to be introduced into
14233   // enum checking below.
14234   assert(T->isIntegralType(Context) && "Integral type required!");
14235   const unsigned NumTypes = 4;
14236   QualType SignedIntegralTypes[NumTypes] = {
14237     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
14238   };
14239   QualType UnsignedIntegralTypes[NumTypes] = {
14240     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
14241     Context.UnsignedLongLongTy
14242   };
14243 
14244   unsigned BitWidth = Context.getTypeSize(T);
14245   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
14246                                                         : UnsignedIntegralTypes;
14247   for (unsigned I = 0; I != NumTypes; ++I)
14248     if (Context.getTypeSize(Types[I]) > BitWidth)
14249       return Types[I];
14250 
14251   return QualType();
14252 }
14253 
14254 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
14255                                           EnumConstantDecl *LastEnumConst,
14256                                           SourceLocation IdLoc,
14257                                           IdentifierInfo *Id,
14258                                           Expr *Val) {
14259   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14260   llvm::APSInt EnumVal(IntWidth);
14261   QualType EltTy;
14262 
14263   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
14264     Val = nullptr;
14265 
14266   if (Val)
14267     Val = DefaultLvalueConversion(Val).get();
14268 
14269   if (Val) {
14270     if (Enum->isDependentType() || Val->isTypeDependent())
14271       EltTy = Context.DependentTy;
14272     else {
14273       SourceLocation ExpLoc;
14274       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
14275           !getLangOpts().MSVCCompat) {
14276         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
14277         // constant-expression in the enumerator-definition shall be a converted
14278         // constant expression of the underlying type.
14279         EltTy = Enum->getIntegerType();
14280         ExprResult Converted =
14281           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
14282                                            CCEK_Enumerator);
14283         if (Converted.isInvalid())
14284           Val = nullptr;
14285         else
14286           Val = Converted.get();
14287       } else if (!Val->isValueDependent() &&
14288                  !(Val = VerifyIntegerConstantExpression(Val,
14289                                                          &EnumVal).get())) {
14290         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
14291       } else {
14292         if (Enum->isFixed()) {
14293           EltTy = Enum->getIntegerType();
14294 
14295           // In Obj-C and Microsoft mode, require the enumeration value to be
14296           // representable in the underlying type of the enumeration. In C++11,
14297           // we perform a non-narrowing conversion as part of converted constant
14298           // expression checking.
14299           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14300             if (getLangOpts().MSVCCompat) {
14301               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
14302               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
14303             } else
14304               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
14305           } else
14306             Val = ImpCastExprToType(Val, EltTy,
14307                                     EltTy->isBooleanType() ?
14308                                     CK_IntegralToBoolean : CK_IntegralCast)
14309                     .get();
14310         } else if (getLangOpts().CPlusPlus) {
14311           // C++11 [dcl.enum]p5:
14312           //   If the underlying type is not fixed, the type of each enumerator
14313           //   is the type of its initializing value:
14314           //     - If an initializer is specified for an enumerator, the
14315           //       initializing value has the same type as the expression.
14316           EltTy = Val->getType();
14317         } else {
14318           // C99 6.7.2.2p2:
14319           //   The expression that defines the value of an enumeration constant
14320           //   shall be an integer constant expression that has a value
14321           //   representable as an int.
14322 
14323           // Complain if the value is not representable in an int.
14324           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
14325             Diag(IdLoc, diag::ext_enum_value_not_int)
14326               << EnumVal.toString(10) << Val->getSourceRange()
14327               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
14328           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
14329             // Force the type of the expression to 'int'.
14330             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
14331           }
14332           EltTy = Val->getType();
14333         }
14334       }
14335     }
14336   }
14337 
14338   if (!Val) {
14339     if (Enum->isDependentType())
14340       EltTy = Context.DependentTy;
14341     else if (!LastEnumConst) {
14342       // C++0x [dcl.enum]p5:
14343       //   If the underlying type is not fixed, the type of each enumerator
14344       //   is the type of its initializing value:
14345       //     - If no initializer is specified for the first enumerator, the
14346       //       initializing value has an unspecified integral type.
14347       //
14348       // GCC uses 'int' for its unspecified integral type, as does
14349       // C99 6.7.2.2p3.
14350       if (Enum->isFixed()) {
14351         EltTy = Enum->getIntegerType();
14352       }
14353       else {
14354         EltTy = Context.IntTy;
14355       }
14356     } else {
14357       // Assign the last value + 1.
14358       EnumVal = LastEnumConst->getInitVal();
14359       ++EnumVal;
14360       EltTy = LastEnumConst->getType();
14361 
14362       // Check for overflow on increment.
14363       if (EnumVal < LastEnumConst->getInitVal()) {
14364         // C++0x [dcl.enum]p5:
14365         //   If the underlying type is not fixed, the type of each enumerator
14366         //   is the type of its initializing value:
14367         //
14368         //     - Otherwise the type of the initializing value is the same as
14369         //       the type of the initializing value of the preceding enumerator
14370         //       unless the incremented value is not representable in that type,
14371         //       in which case the type is an unspecified integral type
14372         //       sufficient to contain the incremented value. If no such type
14373         //       exists, the program is ill-formed.
14374         QualType T = getNextLargerIntegralType(Context, EltTy);
14375         if (T.isNull() || Enum->isFixed()) {
14376           // There is no integral type larger enough to represent this
14377           // value. Complain, then allow the value to wrap around.
14378           EnumVal = LastEnumConst->getInitVal();
14379           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
14380           ++EnumVal;
14381           if (Enum->isFixed())
14382             // When the underlying type is fixed, this is ill-formed.
14383             Diag(IdLoc, diag::err_enumerator_wrapped)
14384               << EnumVal.toString(10)
14385               << EltTy;
14386           else
14387             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
14388               << EnumVal.toString(10);
14389         } else {
14390           EltTy = T;
14391         }
14392 
14393         // Retrieve the last enumerator's value, extent that type to the
14394         // type that is supposed to be large enough to represent the incremented
14395         // value, then increment.
14396         EnumVal = LastEnumConst->getInitVal();
14397         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14398         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
14399         ++EnumVal;
14400 
14401         // If we're not in C++, diagnose the overflow of enumerator values,
14402         // which in C99 means that the enumerator value is not representable in
14403         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
14404         // permits enumerator values that are representable in some larger
14405         // integral type.
14406         if (!getLangOpts().CPlusPlus && !T.isNull())
14407           Diag(IdLoc, diag::warn_enum_value_overflow);
14408       } else if (!getLangOpts().CPlusPlus &&
14409                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
14410         // Enforce C99 6.7.2.2p2 even when we compute the next value.
14411         Diag(IdLoc, diag::ext_enum_value_not_int)
14412           << EnumVal.toString(10) << 1;
14413       }
14414     }
14415   }
14416 
14417   if (!EltTy->isDependentType()) {
14418     // Make the enumerator value match the signedness and size of the
14419     // enumerator's type.
14420     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
14421     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
14422   }
14423 
14424   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
14425                                   Val, EnumVal);
14426 }
14427 
14428 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
14429                                                 SourceLocation IILoc) {
14430   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
14431       !getLangOpts().CPlusPlus)
14432     return SkipBodyInfo();
14433 
14434   // We have an anonymous enum definition. Look up the first enumerator to
14435   // determine if we should merge the definition with an existing one and
14436   // skip the body.
14437   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
14438                                          ForRedeclaration);
14439   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
14440   if (!PrevECD)
14441     return SkipBodyInfo();
14442 
14443   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
14444   NamedDecl *Hidden;
14445   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
14446     SkipBodyInfo Skip;
14447     Skip.Previous = Hidden;
14448     return Skip;
14449   }
14450 
14451   return SkipBodyInfo();
14452 }
14453 
14454 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
14455                               SourceLocation IdLoc, IdentifierInfo *Id,
14456                               AttributeList *Attr,
14457                               SourceLocation EqualLoc, Expr *Val) {
14458   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
14459   EnumConstantDecl *LastEnumConst =
14460     cast_or_null<EnumConstantDecl>(lastEnumConst);
14461 
14462   // The scope passed in may not be a decl scope.  Zip up the scope tree until
14463   // we find one that is.
14464   S = getNonFieldDeclScope(S);
14465 
14466   // Verify that there isn't already something declared with this name in this
14467   // scope.
14468   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
14469                                          ForRedeclaration);
14470   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14471     // Maybe we will complain about the shadowed template parameter.
14472     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
14473     // Just pretend that we didn't see the previous declaration.
14474     PrevDecl = nullptr;
14475   }
14476 
14477   // C++ [class.mem]p15:
14478   // If T is the name of a class, then each of the following shall have a name
14479   // different from T:
14480   // - every enumerator of every member of class T that is an unscoped
14481   // enumerated type
14482   if (!TheEnumDecl->isScoped())
14483     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
14484                             DeclarationNameInfo(Id, IdLoc));
14485 
14486   EnumConstantDecl *New =
14487     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
14488   if (!New)
14489     return nullptr;
14490 
14491   if (PrevDecl) {
14492     // When in C++, we may get a TagDecl with the same name; in this case the
14493     // enum constant will 'hide' the tag.
14494     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
14495            "Received TagDecl when not in C++!");
14496     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
14497         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
14498       if (isa<EnumConstantDecl>(PrevDecl))
14499         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
14500       else
14501         Diag(IdLoc, diag::err_redefinition) << Id;
14502       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14503       return nullptr;
14504     }
14505   }
14506 
14507   // Process attributes.
14508   if (Attr) ProcessDeclAttributeList(S, New, Attr);
14509 
14510   // Register this decl in the current scope stack.
14511   New->setAccess(TheEnumDecl->getAccess());
14512   PushOnScopeChains(New, S);
14513 
14514   ActOnDocumentableDecl(New);
14515 
14516   return New;
14517 }
14518 
14519 // Returns true when the enum initial expression does not trigger the
14520 // duplicate enum warning.  A few common cases are exempted as follows:
14521 // Element2 = Element1
14522 // Element2 = Element1 + 1
14523 // Element2 = Element1 - 1
14524 // Where Element2 and Element1 are from the same enum.
14525 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
14526   Expr *InitExpr = ECD->getInitExpr();
14527   if (!InitExpr)
14528     return true;
14529   InitExpr = InitExpr->IgnoreImpCasts();
14530 
14531   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
14532     if (!BO->isAdditiveOp())
14533       return true;
14534     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
14535     if (!IL)
14536       return true;
14537     if (IL->getValue() != 1)
14538       return true;
14539 
14540     InitExpr = BO->getLHS();
14541   }
14542 
14543   // This checks if the elements are from the same enum.
14544   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
14545   if (!DRE)
14546     return true;
14547 
14548   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
14549   if (!EnumConstant)
14550     return true;
14551 
14552   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
14553       Enum)
14554     return true;
14555 
14556   return false;
14557 }
14558 
14559 namespace {
14560 struct DupKey {
14561   int64_t val;
14562   bool isTombstoneOrEmptyKey;
14563   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
14564     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
14565 };
14566 
14567 static DupKey GetDupKey(const llvm::APSInt& Val) {
14568   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
14569                 false);
14570 }
14571 
14572 struct DenseMapInfoDupKey {
14573   static DupKey getEmptyKey() { return DupKey(0, true); }
14574   static DupKey getTombstoneKey() { return DupKey(1, true); }
14575   static unsigned getHashValue(const DupKey Key) {
14576     return (unsigned)(Key.val * 37);
14577   }
14578   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
14579     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
14580            LHS.val == RHS.val;
14581   }
14582 };
14583 } // end anonymous namespace
14584 
14585 // Emits a warning when an element is implicitly set a value that
14586 // a previous element has already been set to.
14587 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
14588                                         EnumDecl *Enum,
14589                                         QualType EnumType) {
14590   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
14591     return;
14592   // Avoid anonymous enums
14593   if (!Enum->getIdentifier())
14594     return;
14595 
14596   // Only check for small enums.
14597   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
14598     return;
14599 
14600   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
14601   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
14602 
14603   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
14604   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
14605           ValueToVectorMap;
14606 
14607   DuplicatesVector DupVector;
14608   ValueToVectorMap EnumMap;
14609 
14610   // Populate the EnumMap with all values represented by enum constants without
14611   // an initialier.
14612   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14613     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
14614 
14615     // Null EnumConstantDecl means a previous diagnostic has been emitted for
14616     // this constant.  Skip this enum since it may be ill-formed.
14617     if (!ECD) {
14618       return;
14619     }
14620 
14621     if (ECD->getInitExpr())
14622       continue;
14623 
14624     DupKey Key = GetDupKey(ECD->getInitVal());
14625     DeclOrVector &Entry = EnumMap[Key];
14626 
14627     // First time encountering this value.
14628     if (Entry.isNull())
14629       Entry = ECD;
14630   }
14631 
14632   // Create vectors for any values that has duplicates.
14633   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14634     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
14635     if (!ValidDuplicateEnum(ECD, Enum))
14636       continue;
14637 
14638     DupKey Key = GetDupKey(ECD->getInitVal());
14639 
14640     DeclOrVector& Entry = EnumMap[Key];
14641     if (Entry.isNull())
14642       continue;
14643 
14644     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
14645       // Ensure constants are different.
14646       if (D == ECD)
14647         continue;
14648 
14649       // Create new vector and push values onto it.
14650       ECDVector *Vec = new ECDVector();
14651       Vec->push_back(D);
14652       Vec->push_back(ECD);
14653 
14654       // Update entry to point to the duplicates vector.
14655       Entry = Vec;
14656 
14657       // Store the vector somewhere we can consult later for quick emission of
14658       // diagnostics.
14659       DupVector.push_back(Vec);
14660       continue;
14661     }
14662 
14663     ECDVector *Vec = Entry.get<ECDVector*>();
14664     // Make sure constants are not added more than once.
14665     if (*Vec->begin() == ECD)
14666       continue;
14667 
14668     Vec->push_back(ECD);
14669   }
14670 
14671   // Emit diagnostics.
14672   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
14673                                   DupVectorEnd = DupVector.end();
14674        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
14675     ECDVector *Vec = *DupVectorIter;
14676     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
14677 
14678     // Emit warning for one enum constant.
14679     ECDVector::iterator I = Vec->begin();
14680     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
14681       << (*I)->getName() << (*I)->getInitVal().toString(10)
14682       << (*I)->getSourceRange();
14683     ++I;
14684 
14685     // Emit one note for each of the remaining enum constants with
14686     // the same value.
14687     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
14688       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
14689         << (*I)->getName() << (*I)->getInitVal().toString(10)
14690         << (*I)->getSourceRange();
14691     delete Vec;
14692   }
14693 }
14694 
14695 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
14696                              bool AllowMask) const {
14697   assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
14698   assert(ED->isCompleteDefinition() && "expected enum definition");
14699 
14700   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
14701   llvm::APInt &FlagBits = R.first->second;
14702 
14703   if (R.second) {
14704     for (auto *E : ED->enumerators()) {
14705       const auto &EVal = E->getInitVal();
14706       // Only single-bit enumerators introduce new flag values.
14707       if (EVal.isPowerOf2())
14708         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
14709     }
14710   }
14711 
14712   // A value is in a flag enum if either its bits are a subset of the enum's
14713   // flag bits (the first condition) or we are allowing masks and the same is
14714   // true of its complement (the second condition). When masks are allowed, we
14715   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
14716   //
14717   // While it's true that any value could be used as a mask, the assumption is
14718   // that a mask will have all of the insignificant bits set. Anything else is
14719   // likely a logic error.
14720   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
14721   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
14722 }
14723 
14724 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
14725                          SourceLocation RBraceLoc, Decl *EnumDeclX,
14726                          ArrayRef<Decl *> Elements,
14727                          Scope *S, AttributeList *Attr) {
14728   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
14729   QualType EnumType = Context.getTypeDeclType(Enum);
14730 
14731   if (Attr)
14732     ProcessDeclAttributeList(S, Enum, Attr);
14733 
14734   if (Enum->isDependentType()) {
14735     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14736       EnumConstantDecl *ECD =
14737         cast_or_null<EnumConstantDecl>(Elements[i]);
14738       if (!ECD) continue;
14739 
14740       ECD->setType(EnumType);
14741     }
14742 
14743     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
14744     return;
14745   }
14746 
14747   // TODO: If the result value doesn't fit in an int, it must be a long or long
14748   // long value.  ISO C does not support this, but GCC does as an extension,
14749   // emit a warning.
14750   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14751   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
14752   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
14753 
14754   // Verify that all the values are okay, compute the size of the values, and
14755   // reverse the list.
14756   unsigned NumNegativeBits = 0;
14757   unsigned NumPositiveBits = 0;
14758 
14759   // Keep track of whether all elements have type int.
14760   bool AllElementsInt = true;
14761 
14762   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14763     EnumConstantDecl *ECD =
14764       cast_or_null<EnumConstantDecl>(Elements[i]);
14765     if (!ECD) continue;  // Already issued a diagnostic.
14766 
14767     const llvm::APSInt &InitVal = ECD->getInitVal();
14768 
14769     // Keep track of the size of positive and negative values.
14770     if (InitVal.isUnsigned() || InitVal.isNonNegative())
14771       NumPositiveBits = std::max(NumPositiveBits,
14772                                  (unsigned)InitVal.getActiveBits());
14773     else
14774       NumNegativeBits = std::max(NumNegativeBits,
14775                                  (unsigned)InitVal.getMinSignedBits());
14776 
14777     // Keep track of whether every enum element has type int (very commmon).
14778     if (AllElementsInt)
14779       AllElementsInt = ECD->getType() == Context.IntTy;
14780   }
14781 
14782   // Figure out the type that should be used for this enum.
14783   QualType BestType;
14784   unsigned BestWidth;
14785 
14786   // C++0x N3000 [conv.prom]p3:
14787   //   An rvalue of an unscoped enumeration type whose underlying
14788   //   type is not fixed can be converted to an rvalue of the first
14789   //   of the following types that can represent all the values of
14790   //   the enumeration: int, unsigned int, long int, unsigned long
14791   //   int, long long int, or unsigned long long int.
14792   // C99 6.4.4.3p2:
14793   //   An identifier declared as an enumeration constant has type int.
14794   // The C99 rule is modified by a gcc extension
14795   QualType BestPromotionType;
14796 
14797   bool Packed = Enum->hasAttr<PackedAttr>();
14798   // -fshort-enums is the equivalent to specifying the packed attribute on all
14799   // enum definitions.
14800   if (LangOpts.ShortEnums)
14801     Packed = true;
14802 
14803   if (Enum->isFixed()) {
14804     BestType = Enum->getIntegerType();
14805     if (BestType->isPromotableIntegerType())
14806       BestPromotionType = Context.getPromotedIntegerType(BestType);
14807     else
14808       BestPromotionType = BestType;
14809 
14810     BestWidth = Context.getIntWidth(BestType);
14811   }
14812   else if (NumNegativeBits) {
14813     // If there is a negative value, figure out the smallest integer type (of
14814     // int/long/longlong) that fits.
14815     // If it's packed, check also if it fits a char or a short.
14816     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
14817       BestType = Context.SignedCharTy;
14818       BestWidth = CharWidth;
14819     } else if (Packed && NumNegativeBits <= ShortWidth &&
14820                NumPositiveBits < ShortWidth) {
14821       BestType = Context.ShortTy;
14822       BestWidth = ShortWidth;
14823     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
14824       BestType = Context.IntTy;
14825       BestWidth = IntWidth;
14826     } else {
14827       BestWidth = Context.getTargetInfo().getLongWidth();
14828 
14829       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
14830         BestType = Context.LongTy;
14831       } else {
14832         BestWidth = Context.getTargetInfo().getLongLongWidth();
14833 
14834         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
14835           Diag(Enum->getLocation(), diag::ext_enum_too_large);
14836         BestType = Context.LongLongTy;
14837       }
14838     }
14839     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
14840   } else {
14841     // If there is no negative value, figure out the smallest type that fits
14842     // all of the enumerator values.
14843     // If it's packed, check also if it fits a char or a short.
14844     if (Packed && NumPositiveBits <= CharWidth) {
14845       BestType = Context.UnsignedCharTy;
14846       BestPromotionType = Context.IntTy;
14847       BestWidth = CharWidth;
14848     } else if (Packed && NumPositiveBits <= ShortWidth) {
14849       BestType = Context.UnsignedShortTy;
14850       BestPromotionType = Context.IntTy;
14851       BestWidth = ShortWidth;
14852     } else if (NumPositiveBits <= IntWidth) {
14853       BestType = Context.UnsignedIntTy;
14854       BestWidth = IntWidth;
14855       BestPromotionType
14856         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14857                            ? Context.UnsignedIntTy : Context.IntTy;
14858     } else if (NumPositiveBits <=
14859                (BestWidth = Context.getTargetInfo().getLongWidth())) {
14860       BestType = Context.UnsignedLongTy;
14861       BestPromotionType
14862         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14863                            ? Context.UnsignedLongTy : Context.LongTy;
14864     } else {
14865       BestWidth = Context.getTargetInfo().getLongLongWidth();
14866       assert(NumPositiveBits <= BestWidth &&
14867              "How could an initializer get larger than ULL?");
14868       BestType = Context.UnsignedLongLongTy;
14869       BestPromotionType
14870         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14871                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
14872     }
14873   }
14874 
14875   // Loop over all of the enumerator constants, changing their types to match
14876   // the type of the enum if needed.
14877   for (auto *D : Elements) {
14878     auto *ECD = cast_or_null<EnumConstantDecl>(D);
14879     if (!ECD) continue;  // Already issued a diagnostic.
14880 
14881     // Standard C says the enumerators have int type, but we allow, as an
14882     // extension, the enumerators to be larger than int size.  If each
14883     // enumerator value fits in an int, type it as an int, otherwise type it the
14884     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
14885     // that X has type 'int', not 'unsigned'.
14886 
14887     // Determine whether the value fits into an int.
14888     llvm::APSInt InitVal = ECD->getInitVal();
14889 
14890     // If it fits into an integer type, force it.  Otherwise force it to match
14891     // the enum decl type.
14892     QualType NewTy;
14893     unsigned NewWidth;
14894     bool NewSign;
14895     if (!getLangOpts().CPlusPlus &&
14896         !Enum->isFixed() &&
14897         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
14898       NewTy = Context.IntTy;
14899       NewWidth = IntWidth;
14900       NewSign = true;
14901     } else if (ECD->getType() == BestType) {
14902       // Already the right type!
14903       if (getLangOpts().CPlusPlus)
14904         // C++ [dcl.enum]p4: Following the closing brace of an
14905         // enum-specifier, each enumerator has the type of its
14906         // enumeration.
14907         ECD->setType(EnumType);
14908       continue;
14909     } else {
14910       NewTy = BestType;
14911       NewWidth = BestWidth;
14912       NewSign = BestType->isSignedIntegerOrEnumerationType();
14913     }
14914 
14915     // Adjust the APSInt value.
14916     InitVal = InitVal.extOrTrunc(NewWidth);
14917     InitVal.setIsSigned(NewSign);
14918     ECD->setInitVal(InitVal);
14919 
14920     // Adjust the Expr initializer and type.
14921     if (ECD->getInitExpr() &&
14922         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
14923       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
14924                                                 CK_IntegralCast,
14925                                                 ECD->getInitExpr(),
14926                                                 /*base paths*/ nullptr,
14927                                                 VK_RValue));
14928     if (getLangOpts().CPlusPlus)
14929       // C++ [dcl.enum]p4: Following the closing brace of an
14930       // enum-specifier, each enumerator has the type of its
14931       // enumeration.
14932       ECD->setType(EnumType);
14933     else
14934       ECD->setType(NewTy);
14935   }
14936 
14937   Enum->completeDefinition(BestType, BestPromotionType,
14938                            NumPositiveBits, NumNegativeBits);
14939 
14940   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
14941 
14942   if (Enum->hasAttr<FlagEnumAttr>()) {
14943     for (Decl *D : Elements) {
14944       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
14945       if (!ECD) continue;  // Already issued a diagnostic.
14946 
14947       llvm::APSInt InitVal = ECD->getInitVal();
14948       if (InitVal != 0 && !InitVal.isPowerOf2() &&
14949           !IsValueInFlagEnum(Enum, InitVal, true))
14950         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
14951           << ECD << Enum;
14952     }
14953   }
14954 
14955   // Now that the enum type is defined, ensure it's not been underaligned.
14956   if (Enum->hasAttrs())
14957     CheckAlignasUnderalignment(Enum);
14958 }
14959 
14960 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
14961                                   SourceLocation StartLoc,
14962                                   SourceLocation EndLoc) {
14963   StringLiteral *AsmString = cast<StringLiteral>(expr);
14964 
14965   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
14966                                                    AsmString, StartLoc,
14967                                                    EndLoc);
14968   CurContext->addDecl(New);
14969   return New;
14970 }
14971 
14972 static void checkModuleImportContext(Sema &S, Module *M,
14973                                      SourceLocation ImportLoc, DeclContext *DC,
14974                                      bool FromInclude = false) {
14975   SourceLocation ExternCLoc;
14976 
14977   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
14978     switch (LSD->getLanguage()) {
14979     case LinkageSpecDecl::lang_c:
14980       if (ExternCLoc.isInvalid())
14981         ExternCLoc = LSD->getLocStart();
14982       break;
14983     case LinkageSpecDecl::lang_cxx:
14984       break;
14985     }
14986     DC = LSD->getParent();
14987   }
14988 
14989   while (isa<LinkageSpecDecl>(DC))
14990     DC = DC->getParent();
14991 
14992   if (!isa<TranslationUnitDecl>(DC)) {
14993     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
14994                           ? diag::ext_module_import_not_at_top_level_noop
14995                           : diag::err_module_import_not_at_top_level_fatal)
14996         << M->getFullModuleName() << DC;
14997     S.Diag(cast<Decl>(DC)->getLocStart(),
14998            diag::note_module_import_not_at_top_level) << DC;
14999   } else if (!M->IsExternC && ExternCLoc.isValid()) {
15000     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
15001       << M->getFullModuleName();
15002     S.Diag(ExternCLoc, diag::note_module_import_in_extern_c);
15003   }
15004 }
15005 
15006 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) {
15007   return checkModuleImportContext(*this, M, ImportLoc, CurContext);
15008 }
15009 
15010 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
15011                                    SourceLocation ImportLoc,
15012                                    ModuleIdPath Path) {
15013   Module *Mod =
15014       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
15015                                    /*IsIncludeDirective=*/false);
15016   if (!Mod)
15017     return true;
15018 
15019   VisibleModules.setVisible(Mod, ImportLoc);
15020 
15021   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
15022 
15023   // FIXME: we should support importing a submodule within a different submodule
15024   // of the same top-level module. Until we do, make it an error rather than
15025   // silently ignoring the import.
15026   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
15027     Diag(ImportLoc, getLangOpts().CompilingModule
15028                         ? diag::err_module_self_import
15029                         : diag::err_module_import_in_implementation)
15030         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
15031 
15032   SmallVector<SourceLocation, 2> IdentifierLocs;
15033   Module *ModCheck = Mod;
15034   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
15035     // If we've run out of module parents, just drop the remaining identifiers.
15036     // We need the length to be consistent.
15037     if (!ModCheck)
15038       break;
15039     ModCheck = ModCheck->Parent;
15040 
15041     IdentifierLocs.push_back(Path[I].second);
15042   }
15043 
15044   ImportDecl *Import = ImportDecl::Create(Context,
15045                                           Context.getTranslationUnitDecl(),
15046                                           AtLoc.isValid()? AtLoc : ImportLoc,
15047                                           Mod, IdentifierLocs);
15048   Context.getTranslationUnitDecl()->addDecl(Import);
15049   return Import;
15050 }
15051 
15052 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
15053   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
15054 
15055   // Determine whether we're in the #include buffer for a module. The #includes
15056   // in that buffer do not qualify as module imports; they're just an
15057   // implementation detail of us building the module.
15058   //
15059   // FIXME: Should we even get ActOnModuleInclude calls for those?
15060   bool IsInModuleIncludes =
15061       TUKind == TU_Module &&
15062       getSourceManager().isWrittenInMainFile(DirectiveLoc);
15063 
15064   // Similarly, if we're in the implementation of a module, don't
15065   // synthesize an illegal module import. FIXME: Why not?
15066   bool ShouldAddImport =
15067       !IsInModuleIncludes &&
15068       (getLangOpts().CompilingModule ||
15069        getLangOpts().CurrentModule.empty() ||
15070        getLangOpts().CurrentModule != Mod->getTopLevelModuleName());
15071 
15072   // If this module import was due to an inclusion directive, create an
15073   // implicit import declaration to capture it in the AST.
15074   if (ShouldAddImport) {
15075     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15076     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15077                                                      DirectiveLoc, Mod,
15078                                                      DirectiveLoc);
15079     TU->addDecl(ImportD);
15080     Consumer.HandleImplicitImportDecl(ImportD);
15081   }
15082 
15083   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
15084   VisibleModules.setVisible(Mod, DirectiveLoc);
15085 }
15086 
15087 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
15088   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
15089 
15090   if (getLangOpts().ModulesLocalVisibility)
15091     VisibleModulesStack.push_back(std::move(VisibleModules));
15092   VisibleModules.setVisible(Mod, DirectiveLoc);
15093 }
15094 
15095 void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) {
15096   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
15097 
15098   if (getLangOpts().ModulesLocalVisibility) {
15099     VisibleModules = std::move(VisibleModulesStack.back());
15100     VisibleModulesStack.pop_back();
15101     VisibleModules.setVisible(Mod, DirectiveLoc);
15102     // Leaving a module hides namespace names, so our visible namespace cache
15103     // is now out of date.
15104     VisibleNamespaceCache.clear();
15105   }
15106 }
15107 
15108 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
15109                                                       Module *Mod) {
15110   // Bail if we're not allowed to implicitly import a module here.
15111   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
15112     return;
15113 
15114   // Create the implicit import declaration.
15115   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
15116   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
15117                                                    Loc, Mod, Loc);
15118   TU->addDecl(ImportD);
15119   Consumer.HandleImplicitImportDecl(ImportD);
15120 
15121   // Make the module visible.
15122   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
15123   VisibleModules.setVisible(Mod, Loc);
15124 }
15125 
15126 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
15127                                       IdentifierInfo* AliasName,
15128                                       SourceLocation PragmaLoc,
15129                                       SourceLocation NameLoc,
15130                                       SourceLocation AliasNameLoc) {
15131   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
15132                                          LookupOrdinaryName);
15133   AsmLabelAttr *Attr =
15134       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
15135 
15136   // If a declaration that:
15137   // 1) declares a function or a variable
15138   // 2) has external linkage
15139   // already exists, add a label attribute to it.
15140   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15141     if (isDeclExternC(PrevDecl))
15142       PrevDecl->addAttr(Attr);
15143     else
15144       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
15145           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
15146   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
15147   } else
15148     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
15149 }
15150 
15151 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
15152                              SourceLocation PragmaLoc,
15153                              SourceLocation NameLoc) {
15154   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
15155 
15156   if (PrevDecl) {
15157     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
15158   } else {
15159     (void)WeakUndeclaredIdentifiers.insert(
15160       std::pair<IdentifierInfo*,WeakInfo>
15161         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
15162   }
15163 }
15164 
15165 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
15166                                 IdentifierInfo* AliasName,
15167                                 SourceLocation PragmaLoc,
15168                                 SourceLocation NameLoc,
15169                                 SourceLocation AliasNameLoc) {
15170   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
15171                                     LookupOrdinaryName);
15172   WeakInfo W = WeakInfo(Name, NameLoc);
15173 
15174   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
15175     if (!PrevDecl->hasAttr<AliasAttr>())
15176       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
15177         DeclApplyPragmaWeak(TUScope, ND, W);
15178   } else {
15179     (void)WeakUndeclaredIdentifiers.insert(
15180       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
15181   }
15182 }
15183 
15184 Decl *Sema::getObjCDeclContext() const {
15185   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
15186 }
15187 
15188 AvailabilityResult Sema::getCurContextAvailability() const {
15189   const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
15190   if (!D)
15191     return AR_Available;
15192 
15193   // If we are within an Objective-C method, we should consult
15194   // both the availability of the method as well as the
15195   // enclosing class.  If the class is (say) deprecated,
15196   // the entire method is considered deprecated from the
15197   // purpose of checking if the current context is deprecated.
15198   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
15199     AvailabilityResult R = MD->getAvailability();
15200     if (R != AR_Available)
15201       return R;
15202     D = MD->getClassInterface();
15203   }
15204   // If we are within an Objective-c @implementation, it
15205   // gets the same availability context as the @interface.
15206   else if (const ObjCImplementationDecl *ID =
15207             dyn_cast<ObjCImplementationDecl>(D)) {
15208     D = ID->getClassInterface();
15209   }
15210   // Recover from user error.
15211   return D ? D->getAvailability() : AR_Available;
15212 }
15213