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 using namespace clang;
51 using namespace sema;
52 
53 Sema::DeclGroupPtrTy Sema::ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType) {
54   if (OwnedType) {
55     Decl *Group[2] = { OwnedType, Ptr };
56     return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
57   }
58 
59   return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
60 }
61 
62 namespace {
63 
64 class TypeNameValidatorCCC : public CorrectionCandidateCallback {
65  public:
66   TypeNameValidatorCCC(bool AllowInvalid, bool WantClass=false,
67                        bool AllowTemplates=false)
68       : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
69         AllowClassTemplates(AllowTemplates) {
70     WantExpressionKeywords = false;
71     WantCXXNamedCasts = false;
72     WantRemainingKeywords = false;
73   }
74 
75   bool ValidateCandidate(const TypoCorrection &candidate) override {
76     if (NamedDecl *ND = candidate.getCorrectionDecl()) {
77       bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
78       bool AllowedTemplate = AllowClassTemplates && isa<ClassTemplateDecl>(ND);
79       return (IsType || AllowedTemplate) &&
80              (AllowInvalidDecl || !ND->isInvalidDecl());
81     }
82     return !WantClassName && candidate.isKeyword();
83   }
84 
85  private:
86   bool AllowInvalidDecl;
87   bool WantClassName;
88   bool AllowClassTemplates;
89 };
90 
91 }
92 
93 /// \brief Determine whether the token kind starts a simple-type-specifier.
94 bool Sema::isSimpleTypeSpecifier(tok::TokenKind Kind) const {
95   switch (Kind) {
96   // FIXME: Take into account the current language when deciding whether a
97   // token kind is a valid type specifier
98   case tok::kw_short:
99   case tok::kw_long:
100   case tok::kw___int64:
101   case tok::kw___int128:
102   case tok::kw_signed:
103   case tok::kw_unsigned:
104   case tok::kw_void:
105   case tok::kw_char:
106   case tok::kw_int:
107   case tok::kw_half:
108   case tok::kw_float:
109   case tok::kw_double:
110   case tok::kw_wchar_t:
111   case tok::kw_bool:
112   case tok::kw___underlying_type:
113   case tok::kw___auto_type:
114     return true;
115 
116   case tok::annot_typename:
117   case tok::kw_char16_t:
118   case tok::kw_char32_t:
119   case tok::kw_typeof:
120   case tok::annot_decltype:
121   case tok::kw_decltype:
122     return getLangOpts().CPlusPlus;
123 
124   default:
125     break;
126   }
127 
128   return false;
129 }
130 
131 namespace {
132 enum class UnqualifiedTypeNameLookupResult {
133   NotFound,
134   FoundNonType,
135   FoundType
136 };
137 } // namespace
138 
139 /// \brief Tries to perform unqualified lookup of the type decls in bases for
140 /// dependent class.
141 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
142 /// type decl, \a FoundType if only type decls are found.
143 static UnqualifiedTypeNameLookupResult
144 lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II,
145                                 SourceLocation NameLoc,
146                                 const CXXRecordDecl *RD) {
147   if (!RD->hasDefinition())
148     return UnqualifiedTypeNameLookupResult::NotFound;
149   // Look for type decls in base classes.
150   UnqualifiedTypeNameLookupResult FoundTypeDecl =
151       UnqualifiedTypeNameLookupResult::NotFound;
152   for (const auto &Base : RD->bases()) {
153     const CXXRecordDecl *BaseRD = nullptr;
154     if (auto *BaseTT = Base.getType()->getAs<TagType>())
155       BaseRD = BaseTT->getAsCXXRecordDecl();
156     else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
157       // Look for type decls in dependent base classes that have known primary
158       // templates.
159       if (!TST || !TST->isDependentType())
160         continue;
161       auto *TD = TST->getTemplateName().getAsTemplateDecl();
162       if (!TD)
163         continue;
164       auto *BasePrimaryTemplate =
165           dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl());
166       if (!BasePrimaryTemplate)
167         continue;
168       BaseRD = BasePrimaryTemplate;
169     }
170     if (BaseRD) {
171       for (NamedDecl *ND : BaseRD->lookup(&II)) {
172         if (!isa<TypeDecl>(ND))
173           return UnqualifiedTypeNameLookupResult::FoundNonType;
174         FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
175       }
176       if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
177         switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
178         case UnqualifiedTypeNameLookupResult::FoundNonType:
179           return UnqualifiedTypeNameLookupResult::FoundNonType;
180         case UnqualifiedTypeNameLookupResult::FoundType:
181           FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
182           break;
183         case UnqualifiedTypeNameLookupResult::NotFound:
184           break;
185         }
186       }
187     }
188   }
189 
190   return FoundTypeDecl;
191 }
192 
193 static ParsedType recoverFromTypeInKnownDependentBase(Sema &S,
194                                                       const IdentifierInfo &II,
195                                                       SourceLocation NameLoc) {
196   // Lookup in the parent class template context, if any.
197   const CXXRecordDecl *RD = nullptr;
198   UnqualifiedTypeNameLookupResult FoundTypeDecl =
199       UnqualifiedTypeNameLookupResult::NotFound;
200   for (DeclContext *DC = S.CurContext;
201        DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
202        DC = DC->getParent()) {
203     // Look for type decls in dependent base classes that have known primary
204     // templates.
205     RD = dyn_cast<CXXRecordDecl>(DC);
206     if (RD && RD->getDescribedClassTemplate())
207       FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
208   }
209   if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
210     return ParsedType();
211 
212   // We found some types in dependent base classes.  Recover as if the user
213   // wrote 'typename MyClass::II' instead of 'II'.  We'll fully resolve the
214   // lookup during template instantiation.
215   S.Diag(NameLoc, diag::ext_found_via_dependent_bases_lookup) << &II;
216 
217   ASTContext &Context = S.Context;
218   auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
219                                           cast<Type>(Context.getRecordType(RD)));
220   QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
221 
222   CXXScopeSpec SS;
223   SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
224 
225   TypeLocBuilder Builder;
226   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
227   DepTL.setNameLoc(NameLoc);
228   DepTL.setElaboratedKeywordLoc(SourceLocation());
229   DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
230   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
231 }
232 
233 /// \brief If the identifier refers to a type name within this scope,
234 /// return the declaration of that type.
235 ///
236 /// This routine performs ordinary name lookup of the identifier II
237 /// within the given scope, with optional C++ scope specifier SS, to
238 /// determine whether the name refers to a type. If so, returns an
239 /// opaque pointer (actually a QualType) corresponding to that
240 /// type. Otherwise, returns NULL.
241 ParsedType Sema::getTypeName(const IdentifierInfo &II, SourceLocation NameLoc,
242                              Scope *S, CXXScopeSpec *SS,
243                              bool isClassName, bool HasTrailingDot,
244                              ParsedType ObjectTypePtr,
245                              bool IsCtorOrDtorName,
246                              bool WantNontrivialTypeSourceInfo,
247                              IdentifierInfo **CorrectedII) {
248   // Determine where we will perform name lookup.
249   DeclContext *LookupCtx = nullptr;
250   if (ObjectTypePtr) {
251     QualType ObjectType = ObjectTypePtr.get();
252     if (ObjectType->isRecordType())
253       LookupCtx = computeDeclContext(ObjectType);
254   } else if (SS && SS->isNotEmpty()) {
255     LookupCtx = computeDeclContext(*SS, false);
256 
257     if (!LookupCtx) {
258       if (isDependentScopeSpecifier(*SS)) {
259         // C++ [temp.res]p3:
260         //   A qualified-id that refers to a type and in which the
261         //   nested-name-specifier depends on a template-parameter (14.6.2)
262         //   shall be prefixed by the keyword typename to indicate that the
263         //   qualified-id denotes a type, forming an
264         //   elaborated-type-specifier (7.1.5.3).
265         //
266         // We therefore do not perform any name lookup if the result would
267         // refer to a member of an unknown specialization.
268         if (!isClassName && !IsCtorOrDtorName)
269           return ParsedType();
270 
271         // We know from the grammar that this name refers to a type,
272         // so build a dependent node to describe the type.
273         if (WantNontrivialTypeSourceInfo)
274           return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
275 
276         NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
277         QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
278                                        II, NameLoc);
279         return ParsedType::make(T);
280       }
281 
282       return ParsedType();
283     }
284 
285     if (!LookupCtx->isDependentContext() &&
286         RequireCompleteDeclContext(*SS, LookupCtx))
287       return ParsedType();
288   }
289 
290   // FIXME: LookupNestedNameSpecifierName isn't the right kind of
291   // lookup for class-names.
292   LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
293                                       LookupOrdinaryName;
294   LookupResult Result(*this, &II, NameLoc, Kind);
295   if (LookupCtx) {
296     // Perform "qualified" name lookup into the declaration context we
297     // computed, which is either the type of the base of a member access
298     // expression or the declaration context associated with a prior
299     // nested-name-specifier.
300     LookupQualifiedName(Result, LookupCtx);
301 
302     if (ObjectTypePtr && Result.empty()) {
303       // C++ [basic.lookup.classref]p3:
304       //   If the unqualified-id is ~type-name, the type-name is looked up
305       //   in the context of the entire postfix-expression. If the type T of
306       //   the object expression is of a class type C, the type-name is also
307       //   looked up in the scope of class C. At least one of the lookups shall
308       //   find a name that refers to (possibly cv-qualified) T.
309       LookupName(Result, S);
310     }
311   } else {
312     // Perform unqualified name lookup.
313     LookupName(Result, S);
314 
315     // For unqualified lookup in a class template in MSVC mode, look into
316     // dependent base classes where the primary class template is known.
317     if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
318       if (ParsedType TypeInBase =
319               recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
320         return TypeInBase;
321     }
322   }
323 
324   NamedDecl *IIDecl = nullptr;
325   switch (Result.getResultKind()) {
326   case LookupResult::NotFound:
327   case LookupResult::NotFoundInCurrentInstantiation:
328     if (CorrectedII) {
329       TypoCorrection Correction = CorrectTypo(
330           Result.getLookupNameInfo(), Kind, S, SS,
331           llvm::make_unique<TypeNameValidatorCCC>(true, isClassName),
332           CTK_ErrorRecovery);
333       IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
334       TemplateTy Template;
335       bool MemberOfUnknownSpecialization;
336       UnqualifiedId TemplateName;
337       TemplateName.setIdentifier(NewII, NameLoc);
338       NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
339       CXXScopeSpec NewSS, *NewSSPtr = SS;
340       if (SS && NNS) {
341         NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
342         NewSSPtr = &NewSS;
343       }
344       if (Correction && (NNS || NewII != &II) &&
345           // Ignore a correction to a template type as the to-be-corrected
346           // identifier is not a template (typo correction for template names
347           // is handled elsewhere).
348           !(getLangOpts().CPlusPlus && NewSSPtr &&
349             isTemplateName(S, *NewSSPtr, false, TemplateName, ParsedType(),
350                            false, Template, MemberOfUnknownSpecialization))) {
351         ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
352                                     isClassName, HasTrailingDot, ObjectTypePtr,
353                                     IsCtorOrDtorName,
354                                     WantNontrivialTypeSourceInfo);
355         if (Ty) {
356           diagnoseTypo(Correction,
357                        PDiag(diag::err_unknown_type_or_class_name_suggest)
358                          << Result.getLookupName() << isClassName);
359           if (SS && NNS)
360             SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
361           *CorrectedII = NewII;
362           return Ty;
363         }
364       }
365     }
366     // If typo correction failed or was not performed, fall through
367   case LookupResult::FoundOverloaded:
368   case LookupResult::FoundUnresolvedValue:
369     Result.suppressDiagnostics();
370     return ParsedType();
371 
372   case LookupResult::Ambiguous:
373     // Recover from type-hiding ambiguities by hiding the type.  We'll
374     // do the lookup again when looking for an object, and we can
375     // diagnose the error then.  If we don't do this, then the error
376     // about hiding the type will be immediately followed by an error
377     // that only makes sense if the identifier was treated like a type.
378     if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
379       Result.suppressDiagnostics();
380       return ParsedType();
381     }
382 
383     // Look to see if we have a type anywhere in the list of results.
384     for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
385          Res != ResEnd; ++Res) {
386       if (isa<TypeDecl>(*Res) || isa<ObjCInterfaceDecl>(*Res)) {
387         if (!IIDecl ||
388             (*Res)->getLocation().getRawEncoding() <
389               IIDecl->getLocation().getRawEncoding())
390           IIDecl = *Res;
391       }
392     }
393 
394     if (!IIDecl) {
395       // None of the entities we found is a type, so there is no way
396       // to even assume that the result is a type. In this case, don't
397       // complain about the ambiguity. The parser will either try to
398       // perform this lookup again (e.g., as an object name), which
399       // will produce the ambiguity, or will complain that it expected
400       // a type name.
401       Result.suppressDiagnostics();
402       return ParsedType();
403     }
404 
405     // We found a type within the ambiguous lookup; diagnose the
406     // ambiguity and then return that type. This might be the right
407     // answer, or it might not be, but it suppresses any attempt to
408     // perform the name lookup again.
409     break;
410 
411   case LookupResult::Found:
412     IIDecl = Result.getFoundDecl();
413     break;
414   }
415 
416   assert(IIDecl && "Didn't find decl");
417 
418   QualType T;
419   if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
420     DiagnoseUseOfDecl(IIDecl, NameLoc);
421 
422     T = Context.getTypeDeclType(TD);
423     MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
424 
425     // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
426     // constructor or destructor name (in such a case, the scope specifier
427     // will be attached to the enclosing Expr or Decl node).
428     if (SS && SS->isNotEmpty() && !IsCtorOrDtorName) {
429       if (WantNontrivialTypeSourceInfo) {
430         // Construct a type with type-source information.
431         TypeLocBuilder Builder;
432         Builder.pushTypeSpec(T).setNameLoc(NameLoc);
433 
434         T = getElaboratedType(ETK_None, *SS, T);
435         ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
436         ElabTL.setElaboratedKeywordLoc(SourceLocation());
437         ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
438         return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
439       } else {
440         T = getElaboratedType(ETK_None, *SS, T);
441       }
442     }
443   } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
444     (void)DiagnoseUseOfDecl(IDecl, NameLoc);
445     if (!HasTrailingDot)
446       T = Context.getObjCInterfaceType(IDecl);
447   }
448 
449   if (T.isNull()) {
450     // If it's not plausibly a type, suppress diagnostics.
451     Result.suppressDiagnostics();
452     return ParsedType();
453   }
454   return ParsedType::make(T);
455 }
456 
457 // Builds a fake NNS for the given decl context.
458 static NestedNameSpecifier *
459 synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC) {
460   for (;; DC = DC->getLookupParent()) {
461     DC = DC->getPrimaryContext();
462     auto *ND = dyn_cast<NamespaceDecl>(DC);
463     if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
464       return NestedNameSpecifier::Create(Context, nullptr, ND);
465     else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
466       return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
467                                          RD->getTypeForDecl());
468     else if (isa<TranslationUnitDecl>(DC))
469       return NestedNameSpecifier::GlobalSpecifier(Context);
470   }
471   llvm_unreachable("something isn't in TU scope?");
472 }
473 
474 ParsedType Sema::ActOnDelayedDefaultTemplateArg(const IdentifierInfo &II,
475                                                 SourceLocation NameLoc) {
476   // Accepting an undeclared identifier as a default argument for a template
477   // type parameter is a Microsoft extension.
478   Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
479 
480   // Build a fake DependentNameType that will perform lookup into CurContext at
481   // instantiation time.  The name specifier isn't dependent, so template
482   // instantiation won't transform it.  It will retry the lookup, however.
483   NestedNameSpecifier *NNS =
484       synthesizeCurrentNestedNameSpecifier(Context, CurContext);
485   QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
486 
487   // Build type location information.  We synthesized the qualifier, so we have
488   // to build a fake NestedNameSpecifierLoc.
489   NestedNameSpecifierLocBuilder NNSLocBuilder;
490   NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
491   NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
492 
493   TypeLocBuilder Builder;
494   DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
495   DepTL.setNameLoc(NameLoc);
496   DepTL.setElaboratedKeywordLoc(SourceLocation());
497   DepTL.setQualifierLoc(QualifierLoc);
498   return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
499 }
500 
501 /// isTagName() - This method is called *for error recovery purposes only*
502 /// to determine if the specified name is a valid tag name ("struct foo").  If
503 /// so, this returns the TST for the tag corresponding to it (TST_enum,
504 /// TST_union, TST_struct, TST_interface, TST_class).  This is used to diagnose
505 /// cases in C where the user forgot to specify the tag.
506 DeclSpec::TST Sema::isTagName(IdentifierInfo &II, Scope *S) {
507   // Do a tag name lookup in this scope.
508   LookupResult R(*this, &II, SourceLocation(), LookupTagName);
509   LookupName(R, S, false);
510   R.suppressDiagnostics();
511   if (R.getResultKind() == LookupResult::Found)
512     if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
513       switch (TD->getTagKind()) {
514       case TTK_Struct: return DeclSpec::TST_struct;
515       case TTK_Interface: return DeclSpec::TST_interface;
516       case TTK_Union:  return DeclSpec::TST_union;
517       case TTK_Class:  return DeclSpec::TST_class;
518       case TTK_Enum:   return DeclSpec::TST_enum;
519       }
520     }
521 
522   return DeclSpec::TST_unspecified;
523 }
524 
525 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
526 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
527 /// then downgrade the missing typename error to a warning.
528 /// This is needed for MSVC compatibility; Example:
529 /// @code
530 /// template<class T> class A {
531 /// public:
532 ///   typedef int TYPE;
533 /// };
534 /// template<class T> class B : public A<T> {
535 /// public:
536 ///   A<T>::TYPE a; // no typename required because A<T> is a base class.
537 /// };
538 /// @endcode
539 bool Sema::isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S) {
540   if (CurContext->isRecord()) {
541     if (SS->getScopeRep()->getKind() == NestedNameSpecifier::Super)
542       return true;
543 
544     const Type *Ty = SS->getScopeRep()->getAsType();
545 
546     CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
547     for (const auto &Base : RD->bases())
548       if (Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
549         return true;
550     return S->isFunctionPrototypeScope();
551   }
552   return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
553 }
554 
555 void Sema::DiagnoseUnknownTypeName(IdentifierInfo *&II,
556                                    SourceLocation IILoc,
557                                    Scope *S,
558                                    CXXScopeSpec *SS,
559                                    ParsedType &SuggestedType,
560                                    bool AllowClassTemplates) {
561   // We don't have anything to suggest (yet).
562   SuggestedType = ParsedType();
563 
564   // There may have been a typo in the name of the type. Look up typo
565   // results, in case we have something that we can suggest.
566   if (TypoCorrection Corrected =
567           CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
568                       llvm::make_unique<TypeNameValidatorCCC>(
569                           false, false, AllowClassTemplates),
570                       CTK_ErrorRecovery)) {
571     if (Corrected.isKeyword()) {
572       // We corrected to a keyword.
573       diagnoseTypo(Corrected, PDiag(diag::err_unknown_typename_suggest) << II);
574       II = Corrected.getCorrectionAsIdentifierInfo();
575     } else {
576       // We found a similarly-named type or interface; suggest that.
577       if (!SS || !SS->isSet()) {
578         diagnoseTypo(Corrected,
579                      PDiag(diag::err_unknown_typename_suggest) << II);
580       } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
581         std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
582         bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
583                                 II->getName().equals(CorrectedStr);
584         diagnoseTypo(Corrected,
585                      PDiag(diag::err_unknown_nested_typename_suggest)
586                        << II << DC << DroppedSpecifier << SS->getRange());
587       } else {
588         llvm_unreachable("could not have corrected a typo here");
589       }
590 
591       CXXScopeSpec tmpSS;
592       if (Corrected.getCorrectionSpecifier())
593         tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
594                           SourceRange(IILoc));
595       SuggestedType = getTypeName(*Corrected.getCorrectionAsIdentifierInfo(),
596                                   IILoc, S, tmpSS.isSet() ? &tmpSS : SS, false,
597                                   false, ParsedType(),
598                                   /*IsCtorOrDtorName=*/false,
599                                   /*NonTrivialTypeSourceInfo=*/true);
600     }
601     return;
602   }
603 
604   if (getLangOpts().CPlusPlus) {
605     // See if II is a class template that the user forgot to pass arguments to.
606     UnqualifiedId Name;
607     Name.setIdentifier(II, IILoc);
608     CXXScopeSpec EmptySS;
609     TemplateTy TemplateResult;
610     bool MemberOfUnknownSpecialization;
611     if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
612                        Name, ParsedType(), true, TemplateResult,
613                        MemberOfUnknownSpecialization) == TNK_Type_template) {
614       TemplateName TplName = TemplateResult.get();
615       Diag(IILoc, diag::err_template_missing_args) << TplName;
616       if (TemplateDecl *TplDecl = TplName.getAsTemplateDecl()) {
617         Diag(TplDecl->getLocation(), diag::note_template_decl_here)
618           << TplDecl->getTemplateParameters()->getSourceRange();
619       }
620       return;
621     }
622   }
623 
624   // FIXME: Should we move the logic that tries to recover from a missing tag
625   // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
626 
627   if (!SS || (!SS->isSet() && !SS->isInvalid()))
628     Diag(IILoc, diag::err_unknown_typename) << II;
629   else if (DeclContext *DC = computeDeclContext(*SS, false))
630     Diag(IILoc, diag::err_typename_nested_not_found)
631       << II << DC << SS->getRange();
632   else if (isDependentScopeSpecifier(*SS)) {
633     unsigned DiagID = diag::err_typename_missing;
634     if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
635       DiagID = diag::ext_typename_missing;
636 
637     Diag(SS->getRange().getBegin(), DiagID)
638       << SS->getScopeRep() << II->getName()
639       << SourceRange(SS->getRange().getBegin(), IILoc)
640       << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
641     SuggestedType = ActOnTypenameType(S, SourceLocation(),
642                                       *SS, *II, IILoc).get();
643   } else {
644     assert(SS && SS->isInvalid() &&
645            "Invalid scope specifier has already been diagnosed");
646   }
647 }
648 
649 /// \brief Determine whether the given result set contains either a type name
650 /// or
651 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
652   bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
653                        NextToken.is(tok::less);
654 
655   for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
656     if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
657       return true;
658 
659     if (CheckTemplate && isa<TemplateDecl>(*I))
660       return true;
661   }
662 
663   return false;
664 }
665 
666 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
667                                     Scope *S, CXXScopeSpec &SS,
668                                     IdentifierInfo *&Name,
669                                     SourceLocation NameLoc) {
670   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
671   SemaRef.LookupParsedName(R, S, &SS);
672   if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
673     StringRef FixItTagName;
674     switch (Tag->getTagKind()) {
675       case TTK_Class:
676         FixItTagName = "class ";
677         break;
678 
679       case TTK_Enum:
680         FixItTagName = "enum ";
681         break;
682 
683       case TTK_Struct:
684         FixItTagName = "struct ";
685         break;
686 
687       case TTK_Interface:
688         FixItTagName = "__interface ";
689         break;
690 
691       case TTK_Union:
692         FixItTagName = "union ";
693         break;
694     }
695 
696     StringRef TagName = FixItTagName.drop_back();
697     SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
698       << Name << TagName << SemaRef.getLangOpts().CPlusPlus
699       << FixItHint::CreateInsertion(NameLoc, FixItTagName);
700 
701     for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
702          I != IEnd; ++I)
703       SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
704         << Name << TagName;
705 
706     // Replace lookup results with just the tag decl.
707     Result.clear(Sema::LookupTagName);
708     SemaRef.LookupParsedName(Result, S, &SS);
709     return true;
710   }
711 
712   return false;
713 }
714 
715 /// Build a ParsedType for a simple-type-specifier with a nested-name-specifier.
716 static ParsedType buildNestedType(Sema &S, CXXScopeSpec &SS,
717                                   QualType T, SourceLocation NameLoc) {
718   ASTContext &Context = S.Context;
719 
720   TypeLocBuilder Builder;
721   Builder.pushTypeSpec(T).setNameLoc(NameLoc);
722 
723   T = S.getElaboratedType(ETK_None, SS, T);
724   ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
725   ElabTL.setElaboratedKeywordLoc(SourceLocation());
726   ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
727   return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
728 }
729 
730 Sema::NameClassification
731 Sema::ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name,
732                    SourceLocation NameLoc, const Token &NextToken,
733                    bool IsAddressOfOperand,
734                    std::unique_ptr<CorrectionCandidateCallback> CCC) {
735   DeclarationNameInfo NameInfo(Name, NameLoc);
736   ObjCMethodDecl *CurMethod = getCurMethodDecl();
737 
738   if (NextToken.is(tok::coloncolon)) {
739     BuildCXXNestedNameSpecifier(S, *Name, NameLoc, NextToken.getLocation(),
740                                 QualType(), false, SS, nullptr, false);
741   }
742 
743   LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
744   LookupParsedName(Result, S, &SS, !CurMethod);
745 
746   // For unqualified lookup in a class template in MSVC mode, look into
747   // dependent base classes where the primary class template is known.
748   if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
749     if (ParsedType TypeInBase =
750             recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
751       return TypeInBase;
752   }
753 
754   // Perform lookup for Objective-C instance variables (including automatically
755   // synthesized instance variables), if we're in an Objective-C method.
756   // FIXME: This lookup really, really needs to be folded in to the normal
757   // unqualified lookup mechanism.
758   if (!SS.isSet() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
759     ExprResult E = LookupInObjCMethod(Result, S, Name, true);
760     if (E.get() || E.isInvalid())
761       return E;
762   }
763 
764   bool SecondTry = false;
765   bool IsFilteredTemplateName = false;
766 
767 Corrected:
768   switch (Result.getResultKind()) {
769   case LookupResult::NotFound:
770     // If an unqualified-id is followed by a '(', then we have a function
771     // call.
772     if (!SS.isSet() && NextToken.is(tok::l_paren)) {
773       // In C++, this is an ADL-only call.
774       // FIXME: Reference?
775       if (getLangOpts().CPlusPlus)
776         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
777 
778       // C90 6.3.2.2:
779       //   If the expression that precedes the parenthesized argument list in a
780       //   function call consists solely of an identifier, and if no
781       //   declaration is visible for this identifier, the identifier is
782       //   implicitly declared exactly as if, in the innermost block containing
783       //   the function call, the declaration
784       //
785       //     extern int identifier ();
786       //
787       //   appeared.
788       //
789       // We also allow this in C99 as an extension.
790       if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S)) {
791         Result.addDecl(D);
792         Result.resolveKind();
793         return BuildDeclarationNameExpr(SS, Result, /*ADL=*/false);
794       }
795     }
796 
797     // In C, we first see whether there is a tag type by the same name, in
798     // which case it's likely that the user just forget to write "enum",
799     // "struct", or "union".
800     if (!getLangOpts().CPlusPlus && !SecondTry &&
801         isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
802       break;
803     }
804 
805     // Perform typo correction to determine if there is another name that is
806     // close to this name.
807     if (!SecondTry && CCC) {
808       SecondTry = true;
809       if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(),
810                                                  Result.getLookupKind(), S,
811                                                  &SS, std::move(CCC),
812                                                  CTK_ErrorRecovery)) {
813         unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
814         unsigned QualifiedDiag = diag::err_no_member_suggest;
815 
816         NamedDecl *FirstDecl = Corrected.getCorrectionDecl();
817         NamedDecl *UnderlyingFirstDecl
818           = FirstDecl? FirstDecl->getUnderlyingDecl() : nullptr;
819         if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
820             UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
821           UnqualifiedDiag = diag::err_no_template_suggest;
822           QualifiedDiag = diag::err_no_member_template_suggest;
823         } else if (UnderlyingFirstDecl &&
824                    (isa<TypeDecl>(UnderlyingFirstDecl) ||
825                     isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
826                     isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
827           UnqualifiedDiag = diag::err_unknown_typename_suggest;
828           QualifiedDiag = diag::err_unknown_nested_typename_suggest;
829         }
830 
831         if (SS.isEmpty()) {
832           diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
833         } else {// FIXME: is this even reachable? Test it.
834           std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
835           bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
836                                   Name->getName().equals(CorrectedStr);
837           diagnoseTypo(Corrected, PDiag(QualifiedDiag)
838                                     << Name << computeDeclContext(SS, false)
839                                     << DroppedSpecifier << SS.getRange());
840         }
841 
842         // Update the name, so that the caller has the new name.
843         Name = Corrected.getCorrectionAsIdentifierInfo();
844 
845         // Typo correction corrected to a keyword.
846         if (Corrected.isKeyword())
847           return Name;
848 
849         // Also update the LookupResult...
850         // FIXME: This should probably go away at some point
851         Result.clear();
852         Result.setLookupName(Corrected.getCorrection());
853         if (FirstDecl)
854           Result.addDecl(FirstDecl);
855 
856         // If we found an Objective-C instance variable, let
857         // LookupInObjCMethod build the appropriate expression to
858         // reference the ivar.
859         // FIXME: This is a gross hack.
860         if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
861           Result.clear();
862           ExprResult E(LookupInObjCMethod(Result, S, Ivar->getIdentifier()));
863           return E;
864         }
865 
866         goto Corrected;
867       }
868     }
869 
870     // We failed to correct; just fall through and let the parser deal with it.
871     Result.suppressDiagnostics();
872     return NameClassification::Unknown();
873 
874   case LookupResult::NotFoundInCurrentInstantiation: {
875     // We performed name lookup into the current instantiation, and there were
876     // dependent bases, so we treat this result the same way as any other
877     // dependent nested-name-specifier.
878 
879     // C++ [temp.res]p2:
880     //   A name used in a template declaration or definition and that is
881     //   dependent on a template-parameter is assumed not to name a type
882     //   unless the applicable name lookup finds a type name or the name is
883     //   qualified by the keyword typename.
884     //
885     // FIXME: If the next token is '<', we might want to ask the parser to
886     // perform some heroics to see if we actually have a
887     // template-argument-list, which would indicate a missing 'template'
888     // keyword here.
889     return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
890                                       NameInfo, IsAddressOfOperand,
891                                       /*TemplateArgs=*/nullptr);
892   }
893 
894   case LookupResult::Found:
895   case LookupResult::FoundOverloaded:
896   case LookupResult::FoundUnresolvedValue:
897     break;
898 
899   case LookupResult::Ambiguous:
900     if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
901         hasAnyAcceptableTemplateNames(Result)) {
902       // C++ [temp.local]p3:
903       //   A lookup that finds an injected-class-name (10.2) can result in an
904       //   ambiguity in certain cases (for example, if it is found in more than
905       //   one base class). If all of the injected-class-names that are found
906       //   refer to specializations of the same class template, and if the name
907       //   is followed by a template-argument-list, the reference refers to the
908       //   class template itself and not a specialization thereof, and is not
909       //   ambiguous.
910       //
911       // This filtering can make an ambiguous result into an unambiguous one,
912       // so try again after filtering out template names.
913       FilterAcceptableTemplateNames(Result);
914       if (!Result.isAmbiguous()) {
915         IsFilteredTemplateName = true;
916         break;
917       }
918     }
919 
920     // Diagnose the ambiguity and return an error.
921     return NameClassification::Error();
922   }
923 
924   if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
925       (IsFilteredTemplateName || hasAnyAcceptableTemplateNames(Result))) {
926     // C++ [temp.names]p3:
927     //   After name lookup (3.4) finds that a name is a template-name or that
928     //   an operator-function-id or a literal- operator-id refers to a set of
929     //   overloaded functions any member of which is a function template if
930     //   this is followed by a <, the < is always taken as the delimiter of a
931     //   template-argument-list and never as the less-than operator.
932     if (!IsFilteredTemplateName)
933       FilterAcceptableTemplateNames(Result);
934 
935     if (!Result.empty()) {
936       bool IsFunctionTemplate;
937       bool IsVarTemplate;
938       TemplateName Template;
939       if (Result.end() - Result.begin() > 1) {
940         IsFunctionTemplate = true;
941         Template = Context.getOverloadedTemplateName(Result.begin(),
942                                                      Result.end());
943       } else {
944         TemplateDecl *TD
945           = cast<TemplateDecl>((*Result.begin())->getUnderlyingDecl());
946         IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
947         IsVarTemplate = isa<VarTemplateDecl>(TD);
948 
949         if (SS.isSet() && !SS.isInvalid())
950           Template = Context.getQualifiedTemplateName(SS.getScopeRep(),
951                                                     /*TemplateKeyword=*/false,
952                                                       TD);
953         else
954           Template = TemplateName(TD);
955       }
956 
957       if (IsFunctionTemplate) {
958         // Function templates always go through overload resolution, at which
959         // point we'll perform the various checks (e.g., accessibility) we need
960         // to based on which function we selected.
961         Result.suppressDiagnostics();
962 
963         return NameClassification::FunctionTemplate(Template);
964       }
965 
966       return IsVarTemplate ? NameClassification::VarTemplate(Template)
967                            : NameClassification::TypeTemplate(Template);
968     }
969   }
970 
971   NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
972   if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
973     DiagnoseUseOfDecl(Type, NameLoc);
974     MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
975     QualType T = Context.getTypeDeclType(Type);
976     if (SS.isNotEmpty())
977       return buildNestedType(*this, SS, T, NameLoc);
978     return ParsedType::make(T);
979   }
980 
981   ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
982   if (!Class) {
983     // FIXME: It's unfortunate that we don't have a Type node for handling this.
984     if (ObjCCompatibleAliasDecl *Alias =
985             dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
986       Class = Alias->getClassInterface();
987   }
988 
989   if (Class) {
990     DiagnoseUseOfDecl(Class, NameLoc);
991 
992     if (NextToken.is(tok::period)) {
993       // Interface. <something> is parsed as a property reference expression.
994       // Just return "unknown" as a fall-through for now.
995       Result.suppressDiagnostics();
996       return NameClassification::Unknown();
997     }
998 
999     QualType T = Context.getObjCInterfaceType(Class);
1000     return ParsedType::make(T);
1001   }
1002 
1003   // We can have a type template here if we're classifying a template argument.
1004   if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl))
1005     return NameClassification::TypeTemplate(
1006         TemplateName(cast<TemplateDecl>(FirstDecl)));
1007 
1008   // Check for a tag type hidden by a non-type decl in a few cases where it
1009   // seems likely a type is wanted instead of the non-type that was found.
1010   bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1011   if ((NextToken.is(tok::identifier) ||
1012        (NextIsOp &&
1013         FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1014       isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1015     TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1016     DiagnoseUseOfDecl(Type, NameLoc);
1017     QualType T = Context.getTypeDeclType(Type);
1018     if (SS.isNotEmpty())
1019       return buildNestedType(*this, SS, T, NameLoc);
1020     return ParsedType::make(T);
1021   }
1022 
1023   if (FirstDecl->isCXXClassMember())
1024     return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1025                                            nullptr, S);
1026 
1027   bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1028   return BuildDeclarationNameExpr(SS, Result, ADL);
1029 }
1030 
1031 // Determines the context to return to after temporarily entering a
1032 // context.  This depends in an unnecessarily complicated way on the
1033 // exact ordering of callbacks from the parser.
1034 DeclContext *Sema::getContainingDC(DeclContext *DC) {
1035 
1036   // Functions defined inline within classes aren't parsed until we've
1037   // finished parsing the top-level class, so the top-level class is
1038   // the context we'll need to return to.
1039   // A Lambda call operator whose parent is a class must not be treated
1040   // as an inline member function.  A Lambda can be used legally
1041   // either as an in-class member initializer or a default argument.  These
1042   // are parsed once the class has been marked complete and so the containing
1043   // context would be the nested class (when the lambda is defined in one);
1044   // If the class is not complete, then the lambda is being used in an
1045   // ill-formed fashion (such as to specify the width of a bit-field, or
1046   // in an array-bound) - in which case we still want to return the
1047   // lexically containing DC (which could be a nested class).
1048   if (isa<FunctionDecl>(DC) && !isLambdaCallOperator(DC)) {
1049     DC = DC->getLexicalParent();
1050 
1051     // A function not defined within a class will always return to its
1052     // lexical context.
1053     if (!isa<CXXRecordDecl>(DC))
1054       return DC;
1055 
1056     // A C++ inline method/friend is parsed *after* the topmost class
1057     // it was declared in is fully parsed ("complete");  the topmost
1058     // class is the context we need to return to.
1059     while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
1060       DC = RD;
1061 
1062     // Return the declaration context of the topmost class the inline method is
1063     // declared in.
1064     return DC;
1065   }
1066 
1067   return DC->getLexicalParent();
1068 }
1069 
1070 void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
1071   assert(getContainingDC(DC) == CurContext &&
1072       "The next DeclContext should be lexically contained in the current one.");
1073   CurContext = DC;
1074   S->setEntity(DC);
1075 }
1076 
1077 void Sema::PopDeclContext() {
1078   assert(CurContext && "DeclContext imbalance!");
1079 
1080   CurContext = getContainingDC(CurContext);
1081   assert(CurContext && "Popped translation unit!");
1082 }
1083 
1084 Sema::SkippedDefinitionContext Sema::ActOnTagStartSkippedDefinition(Scope *S,
1085                                                                     Decl *D) {
1086   // Unlike PushDeclContext, the context to which we return is not necessarily
1087   // the containing DC of TD, because the new context will be some pre-existing
1088   // TagDecl definition instead of a fresh one.
1089   auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1090   CurContext = cast<TagDecl>(D)->getDefinition();
1091   assert(CurContext && "skipping definition of undefined tag");
1092   // Start lookups from the parent of the current context; we don't want to look
1093   // into the pre-existing complete definition.
1094   S->setEntity(CurContext->getLookupParent());
1095   return Result;
1096 }
1097 
1098 void Sema::ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context) {
1099   CurContext = static_cast<decltype(CurContext)>(Context);
1100 }
1101 
1102 /// EnterDeclaratorContext - Used when we must lookup names in the context
1103 /// of a declarator's nested name specifier.
1104 ///
1105 void Sema::EnterDeclaratorContext(Scope *S, DeclContext *DC) {
1106   // C++0x [basic.lookup.unqual]p13:
1107   //   A name used in the definition of a static data member of class
1108   //   X (after the qualified-id of the static member) is looked up as
1109   //   if the name was used in a member function of X.
1110   // C++0x [basic.lookup.unqual]p14:
1111   //   If a variable member of a namespace is defined outside of the
1112   //   scope of its namespace then any name used in the definition of
1113   //   the variable member (after the declarator-id) is looked up as
1114   //   if the definition of the variable member occurred in its
1115   //   namespace.
1116   // Both of these imply that we should push a scope whose context
1117   // is the semantic context of the declaration.  We can't use
1118   // PushDeclContext here because that context is not necessarily
1119   // lexically contained in the current context.  Fortunately,
1120   // the containing scope should have the appropriate information.
1121 
1122   assert(!S->getEntity() && "scope already has entity");
1123 
1124 #ifndef NDEBUG
1125   Scope *Ancestor = S->getParent();
1126   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1127   assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1128 #endif
1129 
1130   CurContext = DC;
1131   S->setEntity(DC);
1132 }
1133 
1134 void Sema::ExitDeclaratorContext(Scope *S) {
1135   assert(S->getEntity() == CurContext && "Context imbalance!");
1136 
1137   // Switch back to the lexical context.  The safety of this is
1138   // enforced by an assert in EnterDeclaratorContext.
1139   Scope *Ancestor = S->getParent();
1140   while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1141   CurContext = Ancestor->getEntity();
1142 
1143   // We don't need to do anything with the scope, which is going to
1144   // disappear.
1145 }
1146 
1147 
1148 void Sema::ActOnReenterFunctionContext(Scope* S, Decl *D) {
1149   // We assume that the caller has already called
1150   // ActOnReenterTemplateScope so getTemplatedDecl() works.
1151   FunctionDecl *FD = D->getAsFunction();
1152   if (!FD)
1153     return;
1154 
1155   // Same implementation as PushDeclContext, but enters the context
1156   // from the lexical parent, rather than the top-level class.
1157   assert(CurContext == FD->getLexicalParent() &&
1158     "The next DeclContext should be lexically contained in the current one.");
1159   CurContext = FD;
1160   S->setEntity(CurContext);
1161 
1162   for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1163     ParmVarDecl *Param = FD->getParamDecl(P);
1164     // If the parameter has an identifier, then add it to the scope
1165     if (Param->getIdentifier()) {
1166       S->AddDecl(Param);
1167       IdResolver.AddDecl(Param);
1168     }
1169   }
1170 }
1171 
1172 
1173 void Sema::ActOnExitFunctionContext() {
1174   // Same implementation as PopDeclContext, but returns to the lexical parent,
1175   // rather than the top-level class.
1176   assert(CurContext && "DeclContext imbalance!");
1177   CurContext = CurContext->getLexicalParent();
1178   assert(CurContext && "Popped translation unit!");
1179 }
1180 
1181 
1182 /// \brief Determine whether we allow overloading of the function
1183 /// PrevDecl with another declaration.
1184 ///
1185 /// This routine determines whether overloading is possible, not
1186 /// whether some new function is actually an overload. It will return
1187 /// true in C++ (where we can always provide overloads) or, as an
1188 /// extension, in C when the previous function is already an
1189 /// overloaded function declaration or has the "overloadable"
1190 /// attribute.
1191 static bool AllowOverloadingOfFunction(LookupResult &Previous,
1192                                        ASTContext &Context) {
1193   if (Context.getLangOpts().CPlusPlus)
1194     return true;
1195 
1196   if (Previous.getResultKind() == LookupResult::FoundOverloaded)
1197     return true;
1198 
1199   return (Previous.getResultKind() == LookupResult::Found
1200           && Previous.getFoundDecl()->hasAttr<OverloadableAttr>());
1201 }
1202 
1203 /// Add this decl to the scope shadowed decl chains.
1204 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1205   // Move up the scope chain until we find the nearest enclosing
1206   // non-transparent context. The declaration will be introduced into this
1207   // scope.
1208   while (S->getEntity() && S->getEntity()->isTransparentContext())
1209     S = S->getParent();
1210 
1211   // Add scoped declarations into their context, so that they can be
1212   // found later. Declarations without a context won't be inserted
1213   // into any context.
1214   if (AddToContext)
1215     CurContext->addDecl(D);
1216 
1217   // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1218   // are function-local declarations.
1219   if (getLangOpts().CPlusPlus && D->isOutOfLine() &&
1220       !D->getDeclContext()->getRedeclContext()->Equals(
1221         D->getLexicalDeclContext()->getRedeclContext()) &&
1222       !D->getLexicalDeclContext()->isFunctionOrMethod())
1223     return;
1224 
1225   // Template instantiations should also not be pushed into scope.
1226   if (isa<FunctionDecl>(D) &&
1227       cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1228     return;
1229 
1230   // If this replaces anything in the current scope,
1231   IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1232                                IEnd = IdResolver.end();
1233   for (; I != IEnd; ++I) {
1234     if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1235       S->RemoveDecl(*I);
1236       IdResolver.RemoveDecl(*I);
1237 
1238       // Should only need to replace one decl.
1239       break;
1240     }
1241   }
1242 
1243   S->AddDecl(D);
1244 
1245   if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1246     // Implicitly-generated labels may end up getting generated in an order that
1247     // isn't strictly lexical, which breaks name lookup. Be careful to insert
1248     // the label at the appropriate place in the identifier chain.
1249     for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1250       DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1251       if (IDC == CurContext) {
1252         if (!S->isDeclScope(*I))
1253           continue;
1254       } else if (IDC->Encloses(CurContext))
1255         break;
1256     }
1257 
1258     IdResolver.InsertDeclAfter(I, D);
1259   } else {
1260     IdResolver.AddDecl(D);
1261   }
1262 }
1263 
1264 void Sema::pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name) {
1265   if (IdResolver.tryAddTopLevelDecl(D, Name) && TUScope)
1266     TUScope->AddDecl(D);
1267 }
1268 
1269 bool Sema::isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S,
1270                          bool AllowInlineNamespace) {
1271   return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1272 }
1273 
1274 Scope *Sema::getScopeForDeclContext(Scope *S, DeclContext *DC) {
1275   DeclContext *TargetDC = DC->getPrimaryContext();
1276   do {
1277     if (DeclContext *ScopeDC = S->getEntity())
1278       if (ScopeDC->getPrimaryContext() == TargetDC)
1279         return S;
1280   } while ((S = S->getParent()));
1281 
1282   return nullptr;
1283 }
1284 
1285 static bool isOutOfScopePreviousDeclaration(NamedDecl *,
1286                                             DeclContext*,
1287                                             ASTContext&);
1288 
1289 /// Filters out lookup results that don't fall within the given scope
1290 /// as determined by isDeclInScope.
1291 void Sema::FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S,
1292                                 bool ConsiderLinkage,
1293                                 bool AllowInlineNamespace) {
1294   LookupResult::Filter F = R.makeFilter();
1295   while (F.hasNext()) {
1296     NamedDecl *D = F.next();
1297 
1298     if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1299       continue;
1300 
1301     if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1302       continue;
1303 
1304     F.erase();
1305   }
1306 
1307   F.done();
1308 }
1309 
1310 static bool isUsingDecl(NamedDecl *D) {
1311   return isa<UsingShadowDecl>(D) ||
1312          isa<UnresolvedUsingTypenameDecl>(D) ||
1313          isa<UnresolvedUsingValueDecl>(D);
1314 }
1315 
1316 /// Removes using shadow declarations from the lookup results.
1317 static void RemoveUsingDecls(LookupResult &R) {
1318   LookupResult::Filter F = R.makeFilter();
1319   while (F.hasNext())
1320     if (isUsingDecl(F.next()))
1321       F.erase();
1322 
1323   F.done();
1324 }
1325 
1326 /// \brief Check for this common pattern:
1327 /// @code
1328 /// class S {
1329 ///   S(const S&); // DO NOT IMPLEMENT
1330 ///   void operator=(const S&); // DO NOT IMPLEMENT
1331 /// };
1332 /// @endcode
1333 static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D) {
1334   // FIXME: Should check for private access too but access is set after we get
1335   // the decl here.
1336   if (D->doesThisDeclarationHaveABody())
1337     return false;
1338 
1339   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1340     return CD->isCopyConstructor();
1341   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
1342     return Method->isCopyAssignmentOperator();
1343   return false;
1344 }
1345 
1346 // We need this to handle
1347 //
1348 // typedef struct {
1349 //   void *foo() { return 0; }
1350 // } A;
1351 //
1352 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1353 // for example. If 'A', foo will have external linkage. If we have '*A',
1354 // foo will have no linkage. Since we can't know until we get to the end
1355 // of the typedef, this function finds out if D might have non-external linkage.
1356 // Callers should verify at the end of the TU if it D has external linkage or
1357 // not.
1358 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1359   const DeclContext *DC = D->getDeclContext();
1360   while (!DC->isTranslationUnit()) {
1361     if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1362       if (!RD->hasNameForLinkage())
1363         return true;
1364     }
1365     DC = DC->getParent();
1366   }
1367 
1368   return !D->isExternallyVisible();
1369 }
1370 
1371 // FIXME: This needs to be refactored; some other isInMainFile users want
1372 // these semantics.
1373 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1374   if (S.TUKind != TU_Complete)
1375     return false;
1376   return S.SourceMgr.isInMainFile(Loc);
1377 }
1378 
1379 bool Sema::ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const {
1380   assert(D);
1381 
1382   if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1383     return false;
1384 
1385   // Ignore all entities declared within templates, and out-of-line definitions
1386   // of members of class templates.
1387   if (D->getDeclContext()->isDependentContext() ||
1388       D->getLexicalDeclContext()->isDependentContext())
1389     return false;
1390 
1391   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1392     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1393       return false;
1394 
1395     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1396       if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1397         return false;
1398     } else {
1399       // 'static inline' functions are defined in headers; don't warn.
1400       if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1401         return false;
1402     }
1403 
1404     if (FD->doesThisDeclarationHaveABody() &&
1405         Context.DeclMustBeEmitted(FD))
1406       return false;
1407   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1408     // Constants and utility variables are defined in headers with internal
1409     // linkage; don't warn.  (Unlike functions, there isn't a convenient marker
1410     // like "inline".)
1411     if (!isMainFileLoc(*this, VD->getLocation()))
1412       return false;
1413 
1414     if (Context.DeclMustBeEmitted(VD))
1415       return false;
1416 
1417     if (VD->isStaticDataMember() &&
1418         VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1419       return false;
1420   } else {
1421     return false;
1422   }
1423 
1424   // Only warn for unused decls internal to the translation unit.
1425   // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1426   // for inline functions defined in the main source file, for instance.
1427   return mightHaveNonExternalLinkage(D);
1428 }
1429 
1430 void Sema::MarkUnusedFileScopedDecl(const DeclaratorDecl *D) {
1431   if (!D)
1432     return;
1433 
1434   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1435     const FunctionDecl *First = FD->getFirstDecl();
1436     if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1437       return; // First should already be in the vector.
1438   }
1439 
1440   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1441     const VarDecl *First = VD->getFirstDecl();
1442     if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1443       return; // First should already be in the vector.
1444   }
1445 
1446   if (ShouldWarnIfUnusedFileScopedDecl(D))
1447     UnusedFileScopedDecls.push_back(D);
1448 }
1449 
1450 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1451   if (D->isInvalidDecl())
1452     return false;
1453 
1454   if (D->isReferenced() || D->isUsed() || D->hasAttr<UnusedAttr>() ||
1455       D->hasAttr<ObjCPreciseLifetimeAttr>())
1456     return false;
1457 
1458   if (isa<LabelDecl>(D))
1459     return true;
1460 
1461   // Except for labels, we only care about unused decls that are local to
1462   // functions.
1463   bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1464   if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1465     // For dependent types, the diagnostic is deferred.
1466     WithinFunction =
1467         WithinFunction || (R->isLocalClass() && !R->isDependentType());
1468   if (!WithinFunction)
1469     return false;
1470 
1471   if (isa<TypedefNameDecl>(D))
1472     return true;
1473 
1474   // White-list anything that isn't a local variable.
1475   if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1476     return false;
1477 
1478   // Types of valid local variables should be complete, so this should succeed.
1479   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1480 
1481     // White-list anything with an __attribute__((unused)) type.
1482     QualType Ty = VD->getType();
1483 
1484     // Only look at the outermost level of typedef.
1485     if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1486       if (TT->getDecl()->hasAttr<UnusedAttr>())
1487         return false;
1488     }
1489 
1490     // If we failed to complete the type for some reason, or if the type is
1491     // dependent, don't diagnose the variable.
1492     if (Ty->isIncompleteType() || Ty->isDependentType())
1493       return false;
1494 
1495     if (const TagType *TT = Ty->getAs<TagType>()) {
1496       const TagDecl *Tag = TT->getDecl();
1497       if (Tag->hasAttr<UnusedAttr>())
1498         return false;
1499 
1500       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1501         if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1502           return false;
1503 
1504         if (const Expr *Init = VD->getInit()) {
1505           if (const ExprWithCleanups *Cleanups =
1506                   dyn_cast<ExprWithCleanups>(Init))
1507             Init = Cleanups->getSubExpr();
1508           const CXXConstructExpr *Construct =
1509             dyn_cast<CXXConstructExpr>(Init);
1510           if (Construct && !Construct->isElidable()) {
1511             CXXConstructorDecl *CD = Construct->getConstructor();
1512             if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>())
1513               return false;
1514           }
1515         }
1516       }
1517     }
1518 
1519     // TODO: __attribute__((unused)) templates?
1520   }
1521 
1522   return true;
1523 }
1524 
1525 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1526                                      FixItHint &Hint) {
1527   if (isa<LabelDecl>(D)) {
1528     SourceLocation AfterColon = Lexer::findLocationAfterToken(D->getLocEnd(),
1529                 tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(), true);
1530     if (AfterColon.isInvalid())
1531       return;
1532     Hint = FixItHint::CreateRemoval(CharSourceRange::
1533                                     getCharRange(D->getLocStart(), AfterColon));
1534   }
1535   return;
1536 }
1537 
1538 void Sema::DiagnoseUnusedNestedTypedefs(const RecordDecl *D) {
1539   if (D->getTypeForDecl()->isDependentType())
1540     return;
1541 
1542   for (auto *TmpD : D->decls()) {
1543     if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1544       DiagnoseUnusedDecl(T);
1545     else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1546       DiagnoseUnusedNestedTypedefs(R);
1547   }
1548 }
1549 
1550 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1551 /// unless they are marked attr(unused).
1552 void Sema::DiagnoseUnusedDecl(const NamedDecl *D) {
1553   if (!ShouldDiagnoseUnusedDecl(D))
1554     return;
1555 
1556   if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1557     // typedefs can be referenced later on, so the diagnostics are emitted
1558     // at end-of-translation-unit.
1559     UnusedLocalTypedefNameCandidates.insert(TD);
1560     return;
1561   }
1562 
1563   FixItHint Hint;
1564   GenerateFixForUnusedDecl(D, Context, Hint);
1565 
1566   unsigned DiagID;
1567   if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1568     DiagID = diag::warn_unused_exception_param;
1569   else if (isa<LabelDecl>(D))
1570     DiagID = diag::warn_unused_label;
1571   else
1572     DiagID = diag::warn_unused_variable;
1573 
1574   Diag(D->getLocation(), DiagID) << D->getDeclName() << Hint;
1575 }
1576 
1577 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
1578   // Verify that we have no forward references left.  If so, there was a goto
1579   // or address of a label taken, but no definition of it.  Label fwd
1580   // definitions are indicated with a null substmt which is also not a resolved
1581   // MS inline assembly label name.
1582   bool Diagnose = false;
1583   if (L->isMSAsmLabel())
1584     Diagnose = !L->isResolvedMSAsmLabel();
1585   else
1586     Diagnose = L->getStmt() == nullptr;
1587   if (Diagnose)
1588     S.Diag(L->getLocation(), diag::err_undeclared_label_use) <<L->getDeclName();
1589 }
1590 
1591 void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
1592   S->mergeNRVOIntoParent();
1593 
1594   if (S->decl_empty()) return;
1595   assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
1596          "Scope shouldn't contain decls!");
1597 
1598   for (auto *TmpD : S->decls()) {
1599     assert(TmpD && "This decl didn't get pushed??");
1600 
1601     assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
1602     NamedDecl *D = cast<NamedDecl>(TmpD);
1603 
1604     if (!D->getDeclName()) continue;
1605 
1606     // Diagnose unused variables in this scope.
1607     if (!S->hasUnrecoverableErrorOccurred()) {
1608       DiagnoseUnusedDecl(D);
1609       if (const auto *RD = dyn_cast<RecordDecl>(D))
1610         DiagnoseUnusedNestedTypedefs(RD);
1611     }
1612 
1613     // If this was a forward reference to a label, verify it was defined.
1614     if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
1615       CheckPoppedLabel(LD, *this);
1616 
1617     // Remove this name from our lexical scope.
1618     IdResolver.RemoveDecl(D);
1619   }
1620 }
1621 
1622 /// \brief Look for an Objective-C class in the translation unit.
1623 ///
1624 /// \param Id The name of the Objective-C class we're looking for. If
1625 /// typo-correction fixes this name, the Id will be updated
1626 /// to the fixed name.
1627 ///
1628 /// \param IdLoc The location of the name in the translation unit.
1629 ///
1630 /// \param DoTypoCorrection If true, this routine will attempt typo correction
1631 /// if there is no class with the given name.
1632 ///
1633 /// \returns The declaration of the named Objective-C class, or NULL if the
1634 /// class could not be found.
1635 ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *&Id,
1636                                               SourceLocation IdLoc,
1637                                               bool DoTypoCorrection) {
1638   // The third "scope" argument is 0 since we aren't enabling lazy built-in
1639   // creation from this context.
1640   NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
1641 
1642   if (!IDecl && DoTypoCorrection) {
1643     // Perform typo correction at the given location, but only if we
1644     // find an Objective-C class name.
1645     if (TypoCorrection C = CorrectTypo(
1646             DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName, TUScope, nullptr,
1647             llvm::make_unique<DeclFilterCCC<ObjCInterfaceDecl>>(),
1648             CTK_ErrorRecovery)) {
1649       diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
1650       IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
1651       Id = IDecl->getIdentifier();
1652     }
1653   }
1654   ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
1655   // This routine must always return a class definition, if any.
1656   if (Def && Def->getDefinition())
1657       Def = Def->getDefinition();
1658   return Def;
1659 }
1660 
1661 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
1662 /// from S, where a non-field would be declared. This routine copes
1663 /// with the difference between C and C++ scoping rules in structs and
1664 /// unions. For example, the following code is well-formed in C but
1665 /// ill-formed in C++:
1666 /// @code
1667 /// struct S6 {
1668 ///   enum { BAR } e;
1669 /// };
1670 ///
1671 /// void test_S6() {
1672 ///   struct S6 a;
1673 ///   a.e = BAR;
1674 /// }
1675 /// @endcode
1676 /// For the declaration of BAR, this routine will return a different
1677 /// scope. The scope S will be the scope of the unnamed enumeration
1678 /// within S6. In C++, this routine will return the scope associated
1679 /// with S6, because the enumeration's scope is a transparent
1680 /// context but structures can contain non-field names. In C, this
1681 /// routine will return the translation unit scope, since the
1682 /// enumeration's scope is a transparent context and structures cannot
1683 /// contain non-field names.
1684 Scope *Sema::getNonFieldDeclScope(Scope *S) {
1685   while (((S->getFlags() & Scope::DeclScope) == 0) ||
1686          (S->getEntity() && S->getEntity()->isTransparentContext()) ||
1687          (S->isClassScope() && !getLangOpts().CPlusPlus))
1688     S = S->getParent();
1689   return S;
1690 }
1691 
1692 /// \brief Looks up the declaration of "struct objc_super" and
1693 /// saves it for later use in building builtin declaration of
1694 /// objc_msgSendSuper and objc_msgSendSuper_stret. If no such
1695 /// pre-existing declaration exists no action takes place.
1696 static void LookupPredefedObjCSuperType(Sema &ThisSema, Scope *S,
1697                                         IdentifierInfo *II) {
1698   if (!II->isStr("objc_msgSendSuper"))
1699     return;
1700   ASTContext &Context = ThisSema.Context;
1701 
1702   LookupResult Result(ThisSema, &Context.Idents.get("objc_super"),
1703                       SourceLocation(), Sema::LookupTagName);
1704   ThisSema.LookupName(Result, S);
1705   if (Result.getResultKind() == LookupResult::Found)
1706     if (const TagDecl *TD = Result.getAsSingle<TagDecl>())
1707       Context.setObjCSuperType(Context.getTagDeclType(TD));
1708 }
1709 
1710 static StringRef getHeaderName(ASTContext::GetBuiltinTypeError Error) {
1711   switch (Error) {
1712   case ASTContext::GE_None:
1713     return "";
1714   case ASTContext::GE_Missing_stdio:
1715     return "stdio.h";
1716   case ASTContext::GE_Missing_setjmp:
1717     return "setjmp.h";
1718   case ASTContext::GE_Missing_ucontext:
1719     return "ucontext.h";
1720   }
1721   llvm_unreachable("unhandled error kind");
1722 }
1723 
1724 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
1725 /// file scope.  lazily create a decl for it. ForRedeclaration is true
1726 /// if we're creating this built-in in anticipation of redeclaring the
1727 /// built-in.
1728 NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID,
1729                                      Scope *S, bool ForRedeclaration,
1730                                      SourceLocation Loc) {
1731   LookupPredefedObjCSuperType(*this, S, II);
1732 
1733   ASTContext::GetBuiltinTypeError Error;
1734   QualType R = Context.GetBuiltinType(ID, Error);
1735   if (Error) {
1736     if (ForRedeclaration)
1737       Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
1738           << getHeaderName(Error) << Context.BuiltinInfo.getName(ID);
1739     return nullptr;
1740   }
1741 
1742   if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(ID)) {
1743     Diag(Loc, diag::ext_implicit_lib_function_decl)
1744         << Context.BuiltinInfo.getName(ID) << R;
1745     if (Context.BuiltinInfo.getHeaderName(ID) &&
1746         !Diags.isIgnored(diag::ext_implicit_lib_function_decl, Loc))
1747       Diag(Loc, diag::note_include_header_or_declare)
1748           << Context.BuiltinInfo.getHeaderName(ID)
1749           << Context.BuiltinInfo.getName(ID);
1750   }
1751 
1752   DeclContext *Parent = Context.getTranslationUnitDecl();
1753   if (getLangOpts().CPlusPlus) {
1754     LinkageSpecDecl *CLinkageDecl =
1755         LinkageSpecDecl::Create(Context, Parent, Loc, Loc,
1756                                 LinkageSpecDecl::lang_c, false);
1757     CLinkageDecl->setImplicit();
1758     Parent->addDecl(CLinkageDecl);
1759     Parent = CLinkageDecl;
1760   }
1761 
1762   FunctionDecl *New = FunctionDecl::Create(Context,
1763                                            Parent,
1764                                            Loc, Loc, II, R, /*TInfo=*/nullptr,
1765                                            SC_Extern,
1766                                            false,
1767                                            R->isFunctionProtoType());
1768   New->setImplicit();
1769 
1770   // Create Decl objects for each parameter, adding them to the
1771   // FunctionDecl.
1772   if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
1773     SmallVector<ParmVarDecl*, 16> Params;
1774     for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1775       ParmVarDecl *parm =
1776           ParmVarDecl::Create(Context, New, SourceLocation(), SourceLocation(),
1777                               nullptr, FT->getParamType(i), /*TInfo=*/nullptr,
1778                               SC_None, nullptr);
1779       parm->setScopeInfo(0, i);
1780       Params.push_back(parm);
1781     }
1782     New->setParams(Params);
1783   }
1784 
1785   AddKnownFunctionAttributes(New);
1786   RegisterLocallyScopedExternCDecl(New, S);
1787 
1788   // TUScope is the translation-unit scope to insert this function into.
1789   // FIXME: This is hideous. We need to teach PushOnScopeChains to
1790   // relate Scopes to DeclContexts, and probably eliminate CurContext
1791   // entirely, but we're not there yet.
1792   DeclContext *SavedContext = CurContext;
1793   CurContext = Parent;
1794   PushOnScopeChains(New, TUScope);
1795   CurContext = SavedContext;
1796   return New;
1797 }
1798 
1799 /// Typedef declarations don't have linkage, but they still denote the same
1800 /// entity if their types are the same.
1801 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
1802 /// isSameEntity.
1803 static void filterNonConflictingPreviousTypedefDecls(Sema &S,
1804                                                      TypedefNameDecl *Decl,
1805                                                      LookupResult &Previous) {
1806   // This is only interesting when modules are enabled.
1807   if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
1808     return;
1809 
1810   // Empty sets are uninteresting.
1811   if (Previous.empty())
1812     return;
1813 
1814   LookupResult::Filter Filter = Previous.makeFilter();
1815   while (Filter.hasNext()) {
1816     NamedDecl *Old = Filter.next();
1817 
1818     // Non-hidden declarations are never ignored.
1819     if (S.isVisible(Old))
1820       continue;
1821 
1822     // Declarations of the same entity are not ignored, even if they have
1823     // different linkages.
1824     if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1825       if (S.Context.hasSameType(OldTD->getUnderlyingType(),
1826                                 Decl->getUnderlyingType()))
1827         continue;
1828 
1829       // If both declarations give a tag declaration a typedef name for linkage
1830       // purposes, then they declare the same entity.
1831       if (S.getLangOpts().CPlusPlus &&
1832           OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
1833           Decl->getAnonDeclWithTypedefName())
1834         continue;
1835     }
1836 
1837     Filter.erase();
1838   }
1839 
1840   Filter.done();
1841 }
1842 
1843 bool Sema::isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New) {
1844   QualType OldType;
1845   if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
1846     OldType = OldTypedef->getUnderlyingType();
1847   else
1848     OldType = Context.getTypeDeclType(Old);
1849   QualType NewType = New->getUnderlyingType();
1850 
1851   if (NewType->isVariablyModifiedType()) {
1852     // Must not redefine a typedef with a variably-modified type.
1853     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1854     Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
1855       << Kind << NewType;
1856     if (Old->getLocation().isValid())
1857       Diag(Old->getLocation(), diag::note_previous_definition);
1858     New->setInvalidDecl();
1859     return true;
1860   }
1861 
1862   if (OldType != NewType &&
1863       !OldType->isDependentType() &&
1864       !NewType->isDependentType() &&
1865       !Context.hasSameType(OldType, NewType)) {
1866     int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
1867     Diag(New->getLocation(), diag::err_redefinition_different_typedef)
1868       << Kind << NewType << OldType;
1869     if (Old->getLocation().isValid())
1870       Diag(Old->getLocation(), diag::note_previous_definition);
1871     New->setInvalidDecl();
1872     return true;
1873   }
1874   return false;
1875 }
1876 
1877 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
1878 /// same name and scope as a previous declaration 'Old'.  Figure out
1879 /// how to resolve this situation, merging decls or emitting
1880 /// diagnostics as appropriate. If there was an error, set New to be invalid.
1881 ///
1882 void Sema::MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New,
1883                                 LookupResult &OldDecls) {
1884   // If the new decl is known invalid already, don't bother doing any
1885   // merging checks.
1886   if (New->isInvalidDecl()) return;
1887 
1888   // Allow multiple definitions for ObjC built-in typedefs.
1889   // FIXME: Verify the underlying types are equivalent!
1890   if (getLangOpts().ObjC1) {
1891     const IdentifierInfo *TypeID = New->getIdentifier();
1892     switch (TypeID->getLength()) {
1893     default: break;
1894     case 2:
1895       {
1896         if (!TypeID->isStr("id"))
1897           break;
1898         QualType T = New->getUnderlyingType();
1899         if (!T->isPointerType())
1900           break;
1901         if (!T->isVoidPointerType()) {
1902           QualType PT = T->getAs<PointerType>()->getPointeeType();
1903           if (!PT->isStructureType())
1904             break;
1905         }
1906         Context.setObjCIdRedefinitionType(T);
1907         // Install the built-in type for 'id', ignoring the current definition.
1908         New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
1909         return;
1910       }
1911     case 5:
1912       if (!TypeID->isStr("Class"))
1913         break;
1914       Context.setObjCClassRedefinitionType(New->getUnderlyingType());
1915       // Install the built-in type for 'Class', ignoring the current definition.
1916       New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
1917       return;
1918     case 3:
1919       if (!TypeID->isStr("SEL"))
1920         break;
1921       Context.setObjCSelRedefinitionType(New->getUnderlyingType());
1922       // Install the built-in type for 'SEL', ignoring the current definition.
1923       New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
1924       return;
1925     }
1926     // Fall through - the typedef name was not a builtin type.
1927   }
1928 
1929   // Verify the old decl was also a type.
1930   TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
1931   if (!Old) {
1932     Diag(New->getLocation(), diag::err_redefinition_different_kind)
1933       << New->getDeclName();
1934 
1935     NamedDecl *OldD = OldDecls.getRepresentativeDecl();
1936     if (OldD->getLocation().isValid())
1937       Diag(OldD->getLocation(), diag::note_previous_definition);
1938 
1939     return New->setInvalidDecl();
1940   }
1941 
1942   // If the old declaration is invalid, just give up here.
1943   if (Old->isInvalidDecl())
1944     return New->setInvalidDecl();
1945 
1946   if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
1947     auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
1948     auto *NewTag = New->getAnonDeclWithTypedefName();
1949     NamedDecl *Hidden = nullptr;
1950     if (getLangOpts().CPlusPlus && OldTag && NewTag &&
1951         OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
1952         !hasVisibleDefinition(OldTag, &Hidden)) {
1953       // There is a definition of this tag, but it is not visible. Use it
1954       // instead of our tag.
1955       New->setTypeForDecl(OldTD->getTypeForDecl());
1956       if (OldTD->isModed())
1957         New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
1958                                     OldTD->getUnderlyingType());
1959       else
1960         New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
1961 
1962       // Make the old tag definition visible.
1963       makeMergedDefinitionVisible(Hidden, NewTag->getLocation());
1964 
1965       // If this was an unscoped enumeration, yank all of its enumerators
1966       // out of the scope.
1967       if (isa<EnumDecl>(NewTag)) {
1968         Scope *EnumScope = getNonFieldDeclScope(S);
1969         for (auto *D : NewTag->decls()) {
1970           auto *ED = cast<EnumConstantDecl>(D);
1971           assert(EnumScope->isDeclScope(ED));
1972           EnumScope->RemoveDecl(ED);
1973           IdResolver.RemoveDecl(ED);
1974           ED->getLexicalDeclContext()->removeDecl(ED);
1975         }
1976       }
1977     }
1978   }
1979 
1980   // If the typedef types are not identical, reject them in all languages and
1981   // with any extensions enabled.
1982   if (isIncompatibleTypedef(Old, New))
1983     return;
1984 
1985   // The types match.  Link up the redeclaration chain and merge attributes if
1986   // the old declaration was a typedef.
1987   if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
1988     New->setPreviousDecl(Typedef);
1989     mergeDeclAttributes(New, Old);
1990   }
1991 
1992   if (getLangOpts().MicrosoftExt)
1993     return;
1994 
1995   if (getLangOpts().CPlusPlus) {
1996     // C++ [dcl.typedef]p2:
1997     //   In a given non-class scope, a typedef specifier can be used to
1998     //   redefine the name of any type declared in that scope to refer
1999     //   to the type to which it already refers.
2000     if (!isa<CXXRecordDecl>(CurContext))
2001       return;
2002 
2003     // C++0x [dcl.typedef]p4:
2004     //   In a given class scope, a typedef specifier can be used to redefine
2005     //   any class-name declared in that scope that is not also a typedef-name
2006     //   to refer to the type to which it already refers.
2007     //
2008     // This wording came in via DR424, which was a correction to the
2009     // wording in DR56, which accidentally banned code like:
2010     //
2011     //   struct S {
2012     //     typedef struct A { } A;
2013     //   };
2014     //
2015     // in the C++03 standard. We implement the C++0x semantics, which
2016     // allow the above but disallow
2017     //
2018     //   struct S {
2019     //     typedef int I;
2020     //     typedef int I;
2021     //   };
2022     //
2023     // since that was the intent of DR56.
2024     if (!isa<TypedefNameDecl>(Old))
2025       return;
2026 
2027     Diag(New->getLocation(), diag::err_redefinition)
2028       << New->getDeclName();
2029     Diag(Old->getLocation(), diag::note_previous_definition);
2030     return New->setInvalidDecl();
2031   }
2032 
2033   // Modules always permit redefinition of typedefs, as does C11.
2034   if (getLangOpts().Modules || getLangOpts().C11)
2035     return;
2036 
2037   // If we have a redefinition of a typedef in C, emit a warning.  This warning
2038   // is normally mapped to an error, but can be controlled with
2039   // -Wtypedef-redefinition.  If either the original or the redefinition is
2040   // in a system header, don't emit this for compatibility with GCC.
2041   if (getDiagnostics().getSuppressSystemWarnings() &&
2042       (Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2043        Context.getSourceManager().isInSystemHeader(New->getLocation())))
2044     return;
2045 
2046   Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2047     << New->getDeclName();
2048   Diag(Old->getLocation(), diag::note_previous_definition);
2049 }
2050 
2051 /// DeclhasAttr - returns true if decl Declaration already has the target
2052 /// attribute.
2053 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2054   const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2055   const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2056   for (const auto *i : D->attrs())
2057     if (i->getKind() == A->getKind()) {
2058       if (Ann) {
2059         if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2060           return true;
2061         continue;
2062       }
2063       // FIXME: Don't hardcode this check
2064       if (OA && isa<OwnershipAttr>(i))
2065         return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2066       return true;
2067     }
2068 
2069   return false;
2070 }
2071 
2072 static bool isAttributeTargetADefinition(Decl *D) {
2073   if (VarDecl *VD = dyn_cast<VarDecl>(D))
2074     return VD->isThisDeclarationADefinition();
2075   if (TagDecl *TD = dyn_cast<TagDecl>(D))
2076     return TD->isCompleteDefinition() || TD->isBeingDefined();
2077   return true;
2078 }
2079 
2080 /// Merge alignment attributes from \p Old to \p New, taking into account the
2081 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2082 ///
2083 /// \return \c true if any attributes were added to \p New.
2084 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2085   // Look for alignas attributes on Old, and pick out whichever attribute
2086   // specifies the strictest alignment requirement.
2087   AlignedAttr *OldAlignasAttr = nullptr;
2088   AlignedAttr *OldStrictestAlignAttr = nullptr;
2089   unsigned OldAlign = 0;
2090   for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2091     // FIXME: We have no way of representing inherited dependent alignments
2092     // in a case like:
2093     //   template<int A, int B> struct alignas(A) X;
2094     //   template<int A, int B> struct alignas(B) X {};
2095     // For now, we just ignore any alignas attributes which are not on the
2096     // definition in such a case.
2097     if (I->isAlignmentDependent())
2098       return false;
2099 
2100     if (I->isAlignas())
2101       OldAlignasAttr = I;
2102 
2103     unsigned Align = I->getAlignment(S.Context);
2104     if (Align > OldAlign) {
2105       OldAlign = Align;
2106       OldStrictestAlignAttr = I;
2107     }
2108   }
2109 
2110   // Look for alignas attributes on New.
2111   AlignedAttr *NewAlignasAttr = nullptr;
2112   unsigned NewAlign = 0;
2113   for (auto *I : New->specific_attrs<AlignedAttr>()) {
2114     if (I->isAlignmentDependent())
2115       return false;
2116 
2117     if (I->isAlignas())
2118       NewAlignasAttr = I;
2119 
2120     unsigned Align = I->getAlignment(S.Context);
2121     if (Align > NewAlign)
2122       NewAlign = Align;
2123   }
2124 
2125   if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2126     // Both declarations have 'alignas' attributes. We require them to match.
2127     // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2128     // fall short. (If two declarations both have alignas, they must both match
2129     // every definition, and so must match each other if there is a definition.)
2130 
2131     // If either declaration only contains 'alignas(0)' specifiers, then it
2132     // specifies the natural alignment for the type.
2133     if (OldAlign == 0 || NewAlign == 0) {
2134       QualType Ty;
2135       if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2136         Ty = VD->getType();
2137       else
2138         Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2139 
2140       if (OldAlign == 0)
2141         OldAlign = S.Context.getTypeAlign(Ty);
2142       if (NewAlign == 0)
2143         NewAlign = S.Context.getTypeAlign(Ty);
2144     }
2145 
2146     if (OldAlign != NewAlign) {
2147       S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2148         << (unsigned)S.Context.toCharUnitsFromBits(OldAlign).getQuantity()
2149         << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2150       S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2151     }
2152   }
2153 
2154   if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2155     // C++11 [dcl.align]p6:
2156     //   if any declaration of an entity has an alignment-specifier,
2157     //   every defining declaration of that entity shall specify an
2158     //   equivalent alignment.
2159     // C11 6.7.5/7:
2160     //   If the definition of an object does not have an alignment
2161     //   specifier, any other declaration of that object shall also
2162     //   have no alignment specifier.
2163     S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2164       << OldAlignasAttr;
2165     S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2166       << OldAlignasAttr;
2167   }
2168 
2169   bool AnyAdded = false;
2170 
2171   // Ensure we have an attribute representing the strictest alignment.
2172   if (OldAlign > NewAlign) {
2173     AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2174     Clone->setInherited(true);
2175     New->addAttr(Clone);
2176     AnyAdded = true;
2177   }
2178 
2179   // Ensure we have an alignas attribute if the old declaration had one.
2180   if (OldAlignasAttr && !NewAlignasAttr &&
2181       !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2182     AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2183     Clone->setInherited(true);
2184     New->addAttr(Clone);
2185     AnyAdded = true;
2186   }
2187 
2188   return AnyAdded;
2189 }
2190 
2191 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2192                                const InheritableAttr *Attr,
2193                                Sema::AvailabilityMergeKind AMK) {
2194   InheritableAttr *NewAttr = nullptr;
2195   unsigned AttrSpellingListIndex = Attr->getSpellingListIndex();
2196   if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2197     NewAttr = S.mergeAvailabilityAttr(D, AA->getRange(), AA->getPlatform(),
2198                                       AA->getIntroduced(), AA->getDeprecated(),
2199                                       AA->getObsoleted(), AA->getUnavailable(),
2200                                       AA->getMessage(), AMK,
2201                                       AttrSpellingListIndex);
2202   else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2203     NewAttr = S.mergeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2204                                     AttrSpellingListIndex);
2205   else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2206     NewAttr = S.mergeTypeVisibilityAttr(D, VA->getRange(), VA->getVisibility(),
2207                                         AttrSpellingListIndex);
2208   else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2209     NewAttr = S.mergeDLLImportAttr(D, ImportA->getRange(),
2210                                    AttrSpellingListIndex);
2211   else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2212     NewAttr = S.mergeDLLExportAttr(D, ExportA->getRange(),
2213                                    AttrSpellingListIndex);
2214   else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2215     NewAttr = S.mergeFormatAttr(D, FA->getRange(), FA->getType(),
2216                                 FA->getFormatIdx(), FA->getFirstArg(),
2217                                 AttrSpellingListIndex);
2218   else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2219     NewAttr = S.mergeSectionAttr(D, SA->getRange(), SA->getName(),
2220                                  AttrSpellingListIndex);
2221   else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2222     NewAttr = S.mergeMSInheritanceAttr(D, IA->getRange(), IA->getBestCase(),
2223                                        AttrSpellingListIndex,
2224                                        IA->getSemanticSpelling());
2225   else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2226     NewAttr = S.mergeAlwaysInlineAttr(D, AA->getRange(),
2227                                       &S.Context.Idents.get(AA->getSpelling()),
2228                                       AttrSpellingListIndex);
2229   else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2230     NewAttr = S.mergeMinSizeAttr(D, MA->getRange(), AttrSpellingListIndex);
2231   else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2232     NewAttr = S.mergeOptimizeNoneAttr(D, OA->getRange(), AttrSpellingListIndex);
2233   else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2234     NewAttr = S.mergeInternalLinkageAttr(
2235         D, InternalLinkageA->getRange(),
2236         &S.Context.Idents.get(InternalLinkageA->getSpelling()),
2237         AttrSpellingListIndex);
2238   else if (const auto *CommonA = dyn_cast<CommonAttr>(Attr))
2239     NewAttr = S.mergeCommonAttr(D, CommonA->getRange(),
2240                                 &S.Context.Idents.get(CommonA->getSpelling()),
2241                                 AttrSpellingListIndex);
2242   else if (isa<AlignedAttr>(Attr))
2243     // AlignedAttrs are handled separately, because we need to handle all
2244     // such attributes on a declaration at the same time.
2245     NewAttr = nullptr;
2246   else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2247            (AMK == Sema::AMK_Override ||
2248             AMK == Sema::AMK_ProtocolImplementation))
2249     NewAttr = nullptr;
2250   else if (Attr->duplicatesAllowed() || !DeclHasAttr(D, Attr))
2251     NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2252 
2253   if (NewAttr) {
2254     NewAttr->setInherited(true);
2255     D->addAttr(NewAttr);
2256     return true;
2257   }
2258 
2259   return false;
2260 }
2261 
2262 static const Decl *getDefinition(const Decl *D) {
2263   if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2264     return TD->getDefinition();
2265   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2266     const VarDecl *Def = VD->getDefinition();
2267     if (Def)
2268       return Def;
2269     return VD->getActingDefinition();
2270   }
2271   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2272     const FunctionDecl* Def;
2273     if (FD->isDefined(Def))
2274       return Def;
2275   }
2276   return nullptr;
2277 }
2278 
2279 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2280   for (const auto *Attribute : D->attrs())
2281     if (Attribute->getKind() == Kind)
2282       return true;
2283   return false;
2284 }
2285 
2286 /// checkNewAttributesAfterDef - If we already have a definition, check that
2287 /// there are no new attributes in this declaration.
2288 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2289   if (!New->hasAttrs())
2290     return;
2291 
2292   const Decl *Def = getDefinition(Old);
2293   if (!Def || Def == New)
2294     return;
2295 
2296   AttrVec &NewAttributes = New->getAttrs();
2297   for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2298     const Attr *NewAttribute = NewAttributes[I];
2299 
2300     if (isa<AliasAttr>(NewAttribute)) {
2301       if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2302         Sema::SkipBodyInfo SkipBody;
2303         S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2304 
2305         // If we're skipping this definition, drop the "alias" attribute.
2306         if (SkipBody.ShouldSkip) {
2307           NewAttributes.erase(NewAttributes.begin() + I);
2308           --E;
2309           continue;
2310         }
2311       } else {
2312         VarDecl *VD = cast<VarDecl>(New);
2313         unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2314                                 VarDecl::TentativeDefinition
2315                             ? diag::err_alias_after_tentative
2316                             : diag::err_redefinition;
2317         S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2318         S.Diag(Def->getLocation(), diag::note_previous_definition);
2319         VD->setInvalidDecl();
2320       }
2321       ++I;
2322       continue;
2323     }
2324 
2325     if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2326       // Tentative definitions are only interesting for the alias check above.
2327       if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2328         ++I;
2329         continue;
2330       }
2331     }
2332 
2333     if (hasAttribute(Def, NewAttribute->getKind())) {
2334       ++I;
2335       continue; // regular attr merging will take care of validating this.
2336     }
2337 
2338     if (isa<C11NoReturnAttr>(NewAttribute)) {
2339       // C's _Noreturn is allowed to be added to a function after it is defined.
2340       ++I;
2341       continue;
2342     } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2343       if (AA->isAlignas()) {
2344         // C++11 [dcl.align]p6:
2345         //   if any declaration of an entity has an alignment-specifier,
2346         //   every defining declaration of that entity shall specify an
2347         //   equivalent alignment.
2348         // C11 6.7.5/7:
2349         //   If the definition of an object does not have an alignment
2350         //   specifier, any other declaration of that object shall also
2351         //   have no alignment specifier.
2352         S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2353           << AA;
2354         S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2355           << AA;
2356         NewAttributes.erase(NewAttributes.begin() + I);
2357         --E;
2358         continue;
2359       }
2360     }
2361 
2362     S.Diag(NewAttribute->getLocation(),
2363            diag::warn_attribute_precede_definition);
2364     S.Diag(Def->getLocation(), diag::note_previous_definition);
2365     NewAttributes.erase(NewAttributes.begin() + I);
2366     --E;
2367   }
2368 }
2369 
2370 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
2371 void Sema::mergeDeclAttributes(NamedDecl *New, Decl *Old,
2372                                AvailabilityMergeKind AMK) {
2373   if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
2374     UsedAttr *NewAttr = OldAttr->clone(Context);
2375     NewAttr->setInherited(true);
2376     New->addAttr(NewAttr);
2377   }
2378 
2379   if (!Old->hasAttrs() && !New->hasAttrs())
2380     return;
2381 
2382   // attributes declared post-definition are currently ignored
2383   checkNewAttributesAfterDef(*this, New, Old);
2384 
2385   if (!Old->hasAttrs())
2386     return;
2387 
2388   bool foundAny = New->hasAttrs();
2389 
2390   // Ensure that any moving of objects within the allocated map is done before
2391   // we process them.
2392   if (!foundAny) New->setAttrs(AttrVec());
2393 
2394   for (auto *I : Old->specific_attrs<InheritableAttr>()) {
2395     // Ignore deprecated/unavailable/availability attributes if requested.
2396     AvailabilityMergeKind LocalAMK = AMK_None;
2397     if (isa<DeprecatedAttr>(I) ||
2398         isa<UnavailableAttr>(I) ||
2399         isa<AvailabilityAttr>(I)) {
2400       switch (AMK) {
2401       case AMK_None:
2402         continue;
2403 
2404       case AMK_Redeclaration:
2405       case AMK_Override:
2406       case AMK_ProtocolImplementation:
2407         LocalAMK = AMK;
2408         break;
2409       }
2410     }
2411 
2412     // Already handled.
2413     if (isa<UsedAttr>(I))
2414       continue;
2415 
2416     if (mergeDeclAttribute(*this, New, I, LocalAMK))
2417       foundAny = true;
2418   }
2419 
2420   if (mergeAlignedAttrs(*this, New, Old))
2421     foundAny = true;
2422 
2423   if (!foundAny) New->dropAttrs();
2424 }
2425 
2426 /// mergeParamDeclAttributes - Copy attributes from the old parameter
2427 /// to the new one.
2428 static void mergeParamDeclAttributes(ParmVarDecl *newDecl,
2429                                      const ParmVarDecl *oldDecl,
2430                                      Sema &S) {
2431   // C++11 [dcl.attr.depend]p2:
2432   //   The first declaration of a function shall specify the
2433   //   carries_dependency attribute for its declarator-id if any declaration
2434   //   of the function specifies the carries_dependency attribute.
2435   const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
2436   if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
2437     S.Diag(CDA->getLocation(),
2438            diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
2439     // Find the first declaration of the parameter.
2440     // FIXME: Should we build redeclaration chains for function parameters?
2441     const FunctionDecl *FirstFD =
2442       cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
2443     const ParmVarDecl *FirstVD =
2444       FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
2445     S.Diag(FirstVD->getLocation(),
2446            diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
2447   }
2448 
2449   if (!oldDecl->hasAttrs())
2450     return;
2451 
2452   bool foundAny = newDecl->hasAttrs();
2453 
2454   // Ensure that any moving of objects within the allocated map is
2455   // done before we process them.
2456   if (!foundAny) newDecl->setAttrs(AttrVec());
2457 
2458   for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
2459     if (!DeclHasAttr(newDecl, I)) {
2460       InheritableAttr *newAttr =
2461         cast<InheritableParamAttr>(I->clone(S.Context));
2462       newAttr->setInherited(true);
2463       newDecl->addAttr(newAttr);
2464       foundAny = true;
2465     }
2466   }
2467 
2468   if (!foundAny) newDecl->dropAttrs();
2469 }
2470 
2471 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
2472                                 const ParmVarDecl *OldParam,
2473                                 Sema &S) {
2474   if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
2475     if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
2476       if (*Oldnullability != *Newnullability) {
2477         S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
2478           << DiagNullabilityKind(
2479                *Newnullability,
2480                ((NewParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2481                 != 0))
2482           << DiagNullabilityKind(
2483                *Oldnullability,
2484                ((OldParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2485                 != 0));
2486         S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
2487       }
2488     } else {
2489       QualType NewT = NewParam->getType();
2490       NewT = S.Context.getAttributedType(
2491                          AttributedType::getNullabilityAttrKind(*Oldnullability),
2492                          NewT, NewT);
2493       NewParam->setType(NewT);
2494     }
2495   }
2496 }
2497 
2498 namespace {
2499 
2500 /// Used in MergeFunctionDecl to keep track of function parameters in
2501 /// C.
2502 struct GNUCompatibleParamWarning {
2503   ParmVarDecl *OldParm;
2504   ParmVarDecl *NewParm;
2505   QualType PromotedType;
2506 };
2507 
2508 }
2509 
2510 /// getSpecialMember - get the special member enum for a method.
2511 Sema::CXXSpecialMember Sema::getSpecialMember(const CXXMethodDecl *MD) {
2512   if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
2513     if (Ctor->isDefaultConstructor())
2514       return Sema::CXXDefaultConstructor;
2515 
2516     if (Ctor->isCopyConstructor())
2517       return Sema::CXXCopyConstructor;
2518 
2519     if (Ctor->isMoveConstructor())
2520       return Sema::CXXMoveConstructor;
2521   } else if (isa<CXXDestructorDecl>(MD)) {
2522     return Sema::CXXDestructor;
2523   } else if (MD->isCopyAssignmentOperator()) {
2524     return Sema::CXXCopyAssignment;
2525   } else if (MD->isMoveAssignmentOperator()) {
2526     return Sema::CXXMoveAssignment;
2527   }
2528 
2529   return Sema::CXXInvalid;
2530 }
2531 
2532 // Determine whether the previous declaration was a definition, implicit
2533 // declaration, or a declaration.
2534 template <typename T>
2535 static std::pair<diag::kind, SourceLocation>
2536 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
2537   diag::kind PrevDiag;
2538   SourceLocation OldLocation = Old->getLocation();
2539   if (Old->isThisDeclarationADefinition())
2540     PrevDiag = diag::note_previous_definition;
2541   else if (Old->isImplicit()) {
2542     PrevDiag = diag::note_previous_implicit_declaration;
2543     if (OldLocation.isInvalid())
2544       OldLocation = New->getLocation();
2545   } else
2546     PrevDiag = diag::note_previous_declaration;
2547   return std::make_pair(PrevDiag, OldLocation);
2548 }
2549 
2550 /// canRedefineFunction - checks if a function can be redefined. Currently,
2551 /// only extern inline functions can be redefined, and even then only in
2552 /// GNU89 mode.
2553 static bool canRedefineFunction(const FunctionDecl *FD,
2554                                 const LangOptions& LangOpts) {
2555   return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
2556           !LangOpts.CPlusPlus &&
2557           FD->isInlineSpecified() &&
2558           FD->getStorageClass() == SC_Extern);
2559 }
2560 
2561 const AttributedType *Sema::getCallingConvAttributedType(QualType T) const {
2562   const AttributedType *AT = T->getAs<AttributedType>();
2563   while (AT && !AT->isCallingConv())
2564     AT = AT->getModifiedType()->getAs<AttributedType>();
2565   return AT;
2566 }
2567 
2568 template <typename T>
2569 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
2570   const DeclContext *DC = Old->getDeclContext();
2571   if (DC->isRecord())
2572     return false;
2573 
2574   LanguageLinkage OldLinkage = Old->getLanguageLinkage();
2575   if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
2576     return true;
2577   if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
2578     return true;
2579   return false;
2580 }
2581 
2582 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
2583 static bool isExternC(VarTemplateDecl *) { return false; }
2584 
2585 /// \brief Check whether a redeclaration of an entity introduced by a
2586 /// using-declaration is valid, given that we know it's not an overload
2587 /// (nor a hidden tag declaration).
2588 template<typename ExpectedDecl>
2589 static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS,
2590                                    ExpectedDecl *New) {
2591   // C++11 [basic.scope.declarative]p4:
2592   //   Given a set of declarations in a single declarative region, each of
2593   //   which specifies the same unqualified name,
2594   //   -- they shall all refer to the same entity, or all refer to functions
2595   //      and function templates; or
2596   //   -- exactly one declaration shall declare a class name or enumeration
2597   //      name that is not a typedef name and the other declarations shall all
2598   //      refer to the same variable or enumerator, or all refer to functions
2599   //      and function templates; in this case the class name or enumeration
2600   //      name is hidden (3.3.10).
2601 
2602   // C++11 [namespace.udecl]p14:
2603   //   If a function declaration in namespace scope or block scope has the
2604   //   same name and the same parameter-type-list as a function introduced
2605   //   by a using-declaration, and the declarations do not declare the same
2606   //   function, the program is ill-formed.
2607 
2608   auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
2609   if (Old &&
2610       !Old->getDeclContext()->getRedeclContext()->Equals(
2611           New->getDeclContext()->getRedeclContext()) &&
2612       !(isExternC(Old) && isExternC(New)))
2613     Old = nullptr;
2614 
2615   if (!Old) {
2616     S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
2617     S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
2618     S.Diag(OldS->getUsingDecl()->getLocation(), diag::note_using_decl) << 0;
2619     return true;
2620   }
2621   return false;
2622 }
2623 
2624 /// MergeFunctionDecl - We just parsed a function 'New' from
2625 /// declarator D which has the same name and scope as a previous
2626 /// declaration 'Old'.  Figure out how to resolve this situation,
2627 /// merging decls or emitting diagnostics as appropriate.
2628 ///
2629 /// In C++, New and Old must be declarations that are not
2630 /// overloaded. Use IsOverload to determine whether New and Old are
2631 /// overloaded, and to select the Old declaration that New should be
2632 /// merged with.
2633 ///
2634 /// Returns true if there was an error, false otherwise.
2635 bool Sema::MergeFunctionDecl(FunctionDecl *New, NamedDecl *&OldD,
2636                              Scope *S, bool MergeTypeWithOld) {
2637   // Verify the old decl was also a function.
2638   FunctionDecl *Old = OldD->getAsFunction();
2639   if (!Old) {
2640     if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
2641       if (New->getFriendObjectKind()) {
2642         Diag(New->getLocation(), diag::err_using_decl_friend);
2643         Diag(Shadow->getTargetDecl()->getLocation(),
2644              diag::note_using_decl_target);
2645         Diag(Shadow->getUsingDecl()->getLocation(),
2646              diag::note_using_decl) << 0;
2647         return true;
2648       }
2649 
2650       // Check whether the two declarations might declare the same function.
2651       if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
2652         return true;
2653       OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
2654     } else {
2655       Diag(New->getLocation(), diag::err_redefinition_different_kind)
2656         << New->getDeclName();
2657       Diag(OldD->getLocation(), diag::note_previous_definition);
2658       return true;
2659     }
2660   }
2661 
2662   // If the old declaration is invalid, just give up here.
2663   if (Old->isInvalidDecl())
2664     return true;
2665 
2666   diag::kind PrevDiag;
2667   SourceLocation OldLocation;
2668   std::tie(PrevDiag, OldLocation) =
2669       getNoteDiagForInvalidRedeclaration(Old, New);
2670 
2671   // Don't complain about this if we're in GNU89 mode and the old function
2672   // is an extern inline function.
2673   // Don't complain about specializations. They are not supposed to have
2674   // storage classes.
2675   if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
2676       New->getStorageClass() == SC_Static &&
2677       Old->hasExternalFormalLinkage() &&
2678       !New->getTemplateSpecializationInfo() &&
2679       !canRedefineFunction(Old, getLangOpts())) {
2680     if (getLangOpts().MicrosoftExt) {
2681       Diag(New->getLocation(), diag::ext_static_non_static) << New;
2682       Diag(OldLocation, PrevDiag);
2683     } else {
2684       Diag(New->getLocation(), diag::err_static_non_static) << New;
2685       Diag(OldLocation, PrevDiag);
2686       return true;
2687     }
2688   }
2689 
2690   if (New->hasAttr<InternalLinkageAttr>() &&
2691       !Old->hasAttr<InternalLinkageAttr>()) {
2692     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
2693         << New->getDeclName();
2694     Diag(Old->getLocation(), diag::note_previous_definition);
2695     New->dropAttr<InternalLinkageAttr>();
2696   }
2697 
2698   // If a function is first declared with a calling convention, but is later
2699   // declared or defined without one, all following decls assume the calling
2700   // convention of the first.
2701   //
2702   // It's OK if a function is first declared without a calling convention,
2703   // but is later declared or defined with the default calling convention.
2704   //
2705   // To test if either decl has an explicit calling convention, we look for
2706   // AttributedType sugar nodes on the type as written.  If they are missing or
2707   // were canonicalized away, we assume the calling convention was implicit.
2708   //
2709   // Note also that we DO NOT return at this point, because we still have
2710   // other tests to run.
2711   QualType OldQType = Context.getCanonicalType(Old->getType());
2712   QualType NewQType = Context.getCanonicalType(New->getType());
2713   const FunctionType *OldType = cast<FunctionType>(OldQType);
2714   const FunctionType *NewType = cast<FunctionType>(NewQType);
2715   FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
2716   FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
2717   bool RequiresAdjustment = false;
2718 
2719   if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
2720     FunctionDecl *First = Old->getFirstDecl();
2721     const FunctionType *FT =
2722         First->getType().getCanonicalType()->castAs<FunctionType>();
2723     FunctionType::ExtInfo FI = FT->getExtInfo();
2724     bool NewCCExplicit = getCallingConvAttributedType(New->getType());
2725     if (!NewCCExplicit) {
2726       // Inherit the CC from the previous declaration if it was specified
2727       // there but not here.
2728       NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
2729       RequiresAdjustment = true;
2730     } else {
2731       // Calling conventions aren't compatible, so complain.
2732       bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
2733       Diag(New->getLocation(), diag::err_cconv_change)
2734         << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
2735         << !FirstCCExplicit
2736         << (!FirstCCExplicit ? "" :
2737             FunctionType::getNameForCallConv(FI.getCC()));
2738 
2739       // Put the note on the first decl, since it is the one that matters.
2740       Diag(First->getLocation(), diag::note_previous_declaration);
2741       return true;
2742     }
2743   }
2744 
2745   // FIXME: diagnose the other way around?
2746   if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
2747     NewTypeInfo = NewTypeInfo.withNoReturn(true);
2748     RequiresAdjustment = true;
2749   }
2750 
2751   // Merge regparm attribute.
2752   if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
2753       OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
2754     if (NewTypeInfo.getHasRegParm()) {
2755       Diag(New->getLocation(), diag::err_regparm_mismatch)
2756         << NewType->getRegParmType()
2757         << OldType->getRegParmType();
2758       Diag(OldLocation, diag::note_previous_declaration);
2759       return true;
2760     }
2761 
2762     NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
2763     RequiresAdjustment = true;
2764   }
2765 
2766   // Merge ns_returns_retained attribute.
2767   if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
2768     if (NewTypeInfo.getProducesResult()) {
2769       Diag(New->getLocation(), diag::err_returns_retained_mismatch);
2770       Diag(OldLocation, diag::note_previous_declaration);
2771       return true;
2772     }
2773 
2774     NewTypeInfo = NewTypeInfo.withProducesResult(true);
2775     RequiresAdjustment = true;
2776   }
2777 
2778   if (RequiresAdjustment) {
2779     const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
2780     AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
2781     New->setType(QualType(AdjustedType, 0));
2782     NewQType = Context.getCanonicalType(New->getType());
2783     NewType = cast<FunctionType>(NewQType);
2784   }
2785 
2786   // If this redeclaration makes the function inline, we may need to add it to
2787   // UndefinedButUsed.
2788   if (!Old->isInlined() && New->isInlined() &&
2789       !New->hasAttr<GNUInlineAttr>() &&
2790       !getLangOpts().GNUInline &&
2791       Old->isUsed(false) &&
2792       !Old->isDefined() && !New->isThisDeclarationADefinition())
2793     UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
2794                                            SourceLocation()));
2795 
2796   // If this redeclaration makes it newly gnu_inline, we don't want to warn
2797   // about it.
2798   if (New->hasAttr<GNUInlineAttr>() &&
2799       Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
2800     UndefinedButUsed.erase(Old->getCanonicalDecl());
2801   }
2802 
2803   if (getLangOpts().CPlusPlus) {
2804     // (C++98 13.1p2):
2805     //   Certain function declarations cannot be overloaded:
2806     //     -- Function declarations that differ only in the return type
2807     //        cannot be overloaded.
2808 
2809     // Go back to the type source info to compare the declared return types,
2810     // per C++1y [dcl.type.auto]p13:
2811     //   Redeclarations or specializations of a function or function template
2812     //   with a declared return type that uses a placeholder type shall also
2813     //   use that placeholder, not a deduced type.
2814     QualType OldDeclaredReturnType =
2815         (Old->getTypeSourceInfo()
2816              ? Old->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2817              : OldType)->getReturnType();
2818     QualType NewDeclaredReturnType =
2819         (New->getTypeSourceInfo()
2820              ? New->getTypeSourceInfo()->getType()->castAs<FunctionType>()
2821              : NewType)->getReturnType();
2822     QualType ResQT;
2823     if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
2824         !((NewQType->isDependentType() || OldQType->isDependentType()) &&
2825           New->isLocalExternDecl())) {
2826       if (NewDeclaredReturnType->isObjCObjectPointerType() &&
2827           OldDeclaredReturnType->isObjCObjectPointerType())
2828         ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
2829       if (ResQT.isNull()) {
2830         if (New->isCXXClassMember() && New->isOutOfLine())
2831           Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
2832               << New << New->getReturnTypeSourceRange();
2833         else
2834           Diag(New->getLocation(), diag::err_ovl_diff_return_type)
2835               << New->getReturnTypeSourceRange();
2836         Diag(OldLocation, PrevDiag) << Old << Old->getType()
2837                                     << Old->getReturnTypeSourceRange();
2838         return true;
2839       }
2840       else
2841         NewQType = ResQT;
2842     }
2843 
2844     QualType OldReturnType = OldType->getReturnType();
2845     QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
2846     if (OldReturnType != NewReturnType) {
2847       // If this function has a deduced return type and has already been
2848       // defined, copy the deduced value from the old declaration.
2849       AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
2850       if (OldAT && OldAT->isDeduced()) {
2851         New->setType(
2852             SubstAutoType(New->getType(),
2853                           OldAT->isDependentType() ? Context.DependentTy
2854                                                    : OldAT->getDeducedType()));
2855         NewQType = Context.getCanonicalType(
2856             SubstAutoType(NewQType,
2857                           OldAT->isDependentType() ? Context.DependentTy
2858                                                    : OldAT->getDeducedType()));
2859       }
2860     }
2861 
2862     const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
2863     CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
2864     if (OldMethod && NewMethod) {
2865       // Preserve triviality.
2866       NewMethod->setTrivial(OldMethod->isTrivial());
2867 
2868       // MSVC allows explicit template specialization at class scope:
2869       // 2 CXXMethodDecls referring to the same function will be injected.
2870       // We don't want a redeclaration error.
2871       bool IsClassScopeExplicitSpecialization =
2872                               OldMethod->isFunctionTemplateSpecialization() &&
2873                               NewMethod->isFunctionTemplateSpecialization();
2874       bool isFriend = NewMethod->getFriendObjectKind();
2875 
2876       if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
2877           !IsClassScopeExplicitSpecialization) {
2878         //    -- Member function declarations with the same name and the
2879         //       same parameter types cannot be overloaded if any of them
2880         //       is a static member function declaration.
2881         if (OldMethod->isStatic() != NewMethod->isStatic()) {
2882           Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
2883           Diag(OldLocation, PrevDiag) << Old << Old->getType();
2884           return true;
2885         }
2886 
2887         // C++ [class.mem]p1:
2888         //   [...] A member shall not be declared twice in the
2889         //   member-specification, except that a nested class or member
2890         //   class template can be declared and then later defined.
2891         if (ActiveTemplateInstantiations.empty()) {
2892           unsigned NewDiag;
2893           if (isa<CXXConstructorDecl>(OldMethod))
2894             NewDiag = diag::err_constructor_redeclared;
2895           else if (isa<CXXDestructorDecl>(NewMethod))
2896             NewDiag = diag::err_destructor_redeclared;
2897           else if (isa<CXXConversionDecl>(NewMethod))
2898             NewDiag = diag::err_conv_function_redeclared;
2899           else
2900             NewDiag = diag::err_member_redeclared;
2901 
2902           Diag(New->getLocation(), NewDiag);
2903         } else {
2904           Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
2905             << New << New->getType();
2906         }
2907         Diag(OldLocation, PrevDiag) << Old << Old->getType();
2908         return true;
2909 
2910       // Complain if this is an explicit declaration of a special
2911       // member that was initially declared implicitly.
2912       //
2913       // As an exception, it's okay to befriend such methods in order
2914       // to permit the implicit constructor/destructor/operator calls.
2915       } else if (OldMethod->isImplicit()) {
2916         if (isFriend) {
2917           NewMethod->setImplicit();
2918         } else {
2919           Diag(NewMethod->getLocation(),
2920                diag::err_definition_of_implicitly_declared_member)
2921             << New << getSpecialMember(OldMethod);
2922           return true;
2923         }
2924       } else if (OldMethod->isExplicitlyDefaulted() && !isFriend) {
2925         Diag(NewMethod->getLocation(),
2926              diag::err_definition_of_explicitly_defaulted_member)
2927           << getSpecialMember(OldMethod);
2928         return true;
2929       }
2930     }
2931 
2932     // C++11 [dcl.attr.noreturn]p1:
2933     //   The first declaration of a function shall specify the noreturn
2934     //   attribute if any declaration of that function specifies the noreturn
2935     //   attribute.
2936     const CXX11NoReturnAttr *NRA = New->getAttr<CXX11NoReturnAttr>();
2937     if (NRA && !Old->hasAttr<CXX11NoReturnAttr>()) {
2938       Diag(NRA->getLocation(), diag::err_noreturn_missing_on_first_decl);
2939       Diag(Old->getFirstDecl()->getLocation(),
2940            diag::note_noreturn_missing_first_decl);
2941     }
2942 
2943     // C++11 [dcl.attr.depend]p2:
2944     //   The first declaration of a function shall specify the
2945     //   carries_dependency attribute for its declarator-id if any declaration
2946     //   of the function specifies the carries_dependency attribute.
2947     const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
2948     if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
2949       Diag(CDA->getLocation(),
2950            diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
2951       Diag(Old->getFirstDecl()->getLocation(),
2952            diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
2953     }
2954 
2955     // (C++98 8.3.5p3):
2956     //   All declarations for a function shall agree exactly in both the
2957     //   return type and the parameter-type-list.
2958     // We also want to respect all the extended bits except noreturn.
2959 
2960     // noreturn should now match unless the old type info didn't have it.
2961     QualType OldQTypeForComparison = OldQType;
2962     if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
2963       assert(OldQType == QualType(OldType, 0));
2964       const FunctionType *OldTypeForComparison
2965         = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
2966       OldQTypeForComparison = QualType(OldTypeForComparison, 0);
2967       assert(OldQTypeForComparison.isCanonical());
2968     }
2969 
2970     if (haveIncompatibleLanguageLinkages(Old, New)) {
2971       // As a special case, retain the language linkage from previous
2972       // declarations of a friend function as an extension.
2973       //
2974       // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
2975       // and is useful because there's otherwise no way to specify language
2976       // linkage within class scope.
2977       //
2978       // Check cautiously as the friend object kind isn't yet complete.
2979       if (New->getFriendObjectKind() != Decl::FOK_None) {
2980         Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
2981         Diag(OldLocation, PrevDiag);
2982       } else {
2983         Diag(New->getLocation(), diag::err_different_language_linkage) << New;
2984         Diag(OldLocation, PrevDiag);
2985         return true;
2986       }
2987     }
2988 
2989     if (OldQTypeForComparison == NewQType)
2990       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
2991 
2992     if ((NewQType->isDependentType() || OldQType->isDependentType()) &&
2993         New->isLocalExternDecl()) {
2994       // It's OK if we couldn't merge types for a local function declaraton
2995       // if either the old or new type is dependent. We'll merge the types
2996       // when we instantiate the function.
2997       return false;
2998     }
2999 
3000     // Fall through for conflicting redeclarations and redefinitions.
3001   }
3002 
3003   // C: Function types need to be compatible, not identical. This handles
3004   // duplicate function decls like "void f(int); void f(enum X);" properly.
3005   if (!getLangOpts().CPlusPlus &&
3006       Context.typesAreCompatible(OldQType, NewQType)) {
3007     const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3008     const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3009     const FunctionProtoType *OldProto = nullptr;
3010     if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3011         (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3012       // The old declaration provided a function prototype, but the
3013       // new declaration does not. Merge in the prototype.
3014       assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3015       SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3016       NewQType =
3017           Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3018                                   OldProto->getExtProtoInfo());
3019       New->setType(NewQType);
3020       New->setHasInheritedPrototype();
3021 
3022       // Synthesize parameters with the same types.
3023       SmallVector<ParmVarDecl*, 16> Params;
3024       for (const auto &ParamType : OldProto->param_types()) {
3025         ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3026                                                  SourceLocation(), nullptr,
3027                                                  ParamType, /*TInfo=*/nullptr,
3028                                                  SC_None, nullptr);
3029         Param->setScopeInfo(0, Params.size());
3030         Param->setImplicit();
3031         Params.push_back(Param);
3032       }
3033 
3034       New->setParams(Params);
3035     }
3036 
3037     return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3038   }
3039 
3040   // GNU C permits a K&R definition to follow a prototype declaration
3041   // if the declared types of the parameters in the K&R definition
3042   // match the types in the prototype declaration, even when the
3043   // promoted types of the parameters from the K&R definition differ
3044   // from the types in the prototype. GCC then keeps the types from
3045   // the prototype.
3046   //
3047   // If a variadic prototype is followed by a non-variadic K&R definition,
3048   // the K&R definition becomes variadic.  This is sort of an edge case, but
3049   // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3050   // C99 6.9.1p8.
3051   if (!getLangOpts().CPlusPlus &&
3052       Old->hasPrototype() && !New->hasPrototype() &&
3053       New->getType()->getAs<FunctionProtoType>() &&
3054       Old->getNumParams() == New->getNumParams()) {
3055     SmallVector<QualType, 16> ArgTypes;
3056     SmallVector<GNUCompatibleParamWarning, 16> Warnings;
3057     const FunctionProtoType *OldProto
3058       = Old->getType()->getAs<FunctionProtoType>();
3059     const FunctionProtoType *NewProto
3060       = New->getType()->getAs<FunctionProtoType>();
3061 
3062     // Determine whether this is the GNU C extension.
3063     QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3064                                                NewProto->getReturnType());
3065     bool LooseCompatible = !MergedReturn.isNull();
3066     for (unsigned Idx = 0, End = Old->getNumParams();
3067          LooseCompatible && Idx != End; ++Idx) {
3068       ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3069       ParmVarDecl *NewParm = New->getParamDecl(Idx);
3070       if (Context.typesAreCompatible(OldParm->getType(),
3071                                      NewProto->getParamType(Idx))) {
3072         ArgTypes.push_back(NewParm->getType());
3073       } else if (Context.typesAreCompatible(OldParm->getType(),
3074                                             NewParm->getType(),
3075                                             /*CompareUnqualified=*/true)) {
3076         GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3077                                            NewProto->getParamType(Idx) };
3078         Warnings.push_back(Warn);
3079         ArgTypes.push_back(NewParm->getType());
3080       } else
3081         LooseCompatible = false;
3082     }
3083 
3084     if (LooseCompatible) {
3085       for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3086         Diag(Warnings[Warn].NewParm->getLocation(),
3087              diag::ext_param_promoted_not_compatible_with_prototype)
3088           << Warnings[Warn].PromotedType
3089           << Warnings[Warn].OldParm->getType();
3090         if (Warnings[Warn].OldParm->getLocation().isValid())
3091           Diag(Warnings[Warn].OldParm->getLocation(),
3092                diag::note_previous_declaration);
3093       }
3094 
3095       if (MergeTypeWithOld)
3096         New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
3097                                              OldProto->getExtProtoInfo()));
3098       return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3099     }
3100 
3101     // Fall through to diagnose conflicting types.
3102   }
3103 
3104   // A function that has already been declared has been redeclared or
3105   // defined with a different type; show an appropriate diagnostic.
3106 
3107   // If the previous declaration was an implicitly-generated builtin
3108   // declaration, then at the very least we should use a specialized note.
3109   unsigned BuiltinID;
3110   if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
3111     // If it's actually a library-defined builtin function like 'malloc'
3112     // or 'printf', just warn about the incompatible redeclaration.
3113     if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
3114       Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
3115       Diag(OldLocation, diag::note_previous_builtin_declaration)
3116         << Old << Old->getType();
3117 
3118       // If this is a global redeclaration, just forget hereafter
3119       // about the "builtin-ness" of the function.
3120       //
3121       // Doing this for local extern declarations is problematic.  If
3122       // the builtin declaration remains visible, a second invalid
3123       // local declaration will produce a hard error; if it doesn't
3124       // remain visible, a single bogus local redeclaration (which is
3125       // actually only a warning) could break all the downstream code.
3126       if (!New->getLexicalDeclContext()->isFunctionOrMethod())
3127         New->getIdentifier()->revertBuiltin();
3128 
3129       return false;
3130     }
3131 
3132     PrevDiag = diag::note_previous_builtin_declaration;
3133   }
3134 
3135   Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
3136   Diag(OldLocation, PrevDiag) << Old << Old->getType();
3137   return true;
3138 }
3139 
3140 /// \brief Completes the merge of two function declarations that are
3141 /// known to be compatible.
3142 ///
3143 /// This routine handles the merging of attributes and other
3144 /// properties of function declarations from the old declaration to
3145 /// the new declaration, once we know that New is in fact a
3146 /// redeclaration of Old.
3147 ///
3148 /// \returns false
3149 bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old,
3150                                         Scope *S, bool MergeTypeWithOld) {
3151   // Merge the attributes
3152   mergeDeclAttributes(New, Old);
3153 
3154   // Merge "pure" flag.
3155   if (Old->isPure())
3156     New->setPure();
3157 
3158   // Merge "used" flag.
3159   if (Old->getMostRecentDecl()->isUsed(false))
3160     New->setIsUsed();
3161 
3162   // Merge attributes from the parameters.  These can mismatch with K&R
3163   // declarations.
3164   if (New->getNumParams() == Old->getNumParams())
3165       for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
3166         ParmVarDecl *NewParam = New->getParamDecl(i);
3167         ParmVarDecl *OldParam = Old->getParamDecl(i);
3168         mergeParamDeclAttributes(NewParam, OldParam, *this);
3169         mergeParamDeclTypes(NewParam, OldParam, *this);
3170       }
3171 
3172   if (getLangOpts().CPlusPlus)
3173     return MergeCXXFunctionDecl(New, Old, S);
3174 
3175   // Merge the function types so the we get the composite types for the return
3176   // and argument types. Per C11 6.2.7/4, only update the type if the old decl
3177   // was visible.
3178   QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
3179   if (!Merged.isNull() && MergeTypeWithOld)
3180     New->setType(Merged);
3181 
3182   return false;
3183 }
3184 
3185 
3186 void Sema::mergeObjCMethodDecls(ObjCMethodDecl *newMethod,
3187                                 ObjCMethodDecl *oldMethod) {
3188 
3189   // Merge the attributes, including deprecated/unavailable
3190   AvailabilityMergeKind MergeKind =
3191     isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
3192       ? AMK_ProtocolImplementation
3193       : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
3194                                                        : AMK_Override;
3195 
3196   mergeDeclAttributes(newMethod, oldMethod, MergeKind);
3197 
3198   // Merge attributes from the parameters.
3199   ObjCMethodDecl::param_const_iterator oi = oldMethod->param_begin(),
3200                                        oe = oldMethod->param_end();
3201   for (ObjCMethodDecl::param_iterator
3202          ni = newMethod->param_begin(), ne = newMethod->param_end();
3203        ni != ne && oi != oe; ++ni, ++oi)
3204     mergeParamDeclAttributes(*ni, *oi, *this);
3205 
3206   CheckObjCMethodOverride(newMethod, oldMethod);
3207 }
3208 
3209 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
3210 /// scope as a previous declaration 'Old'.  Figure out how to merge their types,
3211 /// emitting diagnostics as appropriate.
3212 ///
3213 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
3214 /// to here in AddInitializerToDecl. We can't check them before the initializer
3215 /// is attached.
3216 void Sema::MergeVarDeclTypes(VarDecl *New, VarDecl *Old,
3217                              bool MergeTypeWithOld) {
3218   if (New->isInvalidDecl() || Old->isInvalidDecl())
3219     return;
3220 
3221   QualType MergedT;
3222   if (getLangOpts().CPlusPlus) {
3223     if (New->getType()->isUndeducedType()) {
3224       // We don't know what the new type is until the initializer is attached.
3225       return;
3226     } else if (Context.hasSameType(New->getType(), Old->getType())) {
3227       // These could still be something that needs exception specs checked.
3228       return MergeVarDeclExceptionSpecs(New, Old);
3229     }
3230     // C++ [basic.link]p10:
3231     //   [...] the types specified by all declarations referring to a given
3232     //   object or function shall be identical, except that declarations for an
3233     //   array object can specify array types that differ by the presence or
3234     //   absence of a major array bound (8.3.4).
3235     else if (Old->getType()->isIncompleteArrayType() &&
3236              New->getType()->isArrayType()) {
3237       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3238       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3239       if (Context.hasSameType(OldArray->getElementType(),
3240                               NewArray->getElementType()))
3241         MergedT = New->getType();
3242     } else if (Old->getType()->isArrayType() &&
3243                New->getType()->isIncompleteArrayType()) {
3244       const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
3245       const ArrayType *NewArray = Context.getAsArrayType(New->getType());
3246       if (Context.hasSameType(OldArray->getElementType(),
3247                               NewArray->getElementType()))
3248         MergedT = Old->getType();
3249     } else if (New->getType()->isObjCObjectPointerType() &&
3250                Old->getType()->isObjCObjectPointerType()) {
3251       MergedT = Context.mergeObjCGCQualifiers(New->getType(),
3252                                               Old->getType());
3253     }
3254   } else {
3255     // C 6.2.7p2:
3256     //   All declarations that refer to the same object or function shall have
3257     //   compatible type.
3258     MergedT = Context.mergeTypes(New->getType(), Old->getType());
3259   }
3260   if (MergedT.isNull()) {
3261     // It's OK if we couldn't merge types if either type is dependent, for a
3262     // block-scope variable. In other cases (static data members of class
3263     // templates, variable templates, ...), we require the types to be
3264     // equivalent.
3265     // FIXME: The C++ standard doesn't say anything about this.
3266     if ((New->getType()->isDependentType() ||
3267          Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
3268       // If the old type was dependent, we can't merge with it, so the new type
3269       // becomes dependent for now. We'll reproduce the original type when we
3270       // instantiate the TypeSourceInfo for the variable.
3271       if (!New->getType()->isDependentType() && MergeTypeWithOld)
3272         New->setType(Context.DependentTy);
3273       return;
3274     }
3275 
3276     // FIXME: Even if this merging succeeds, some other non-visible declaration
3277     // of this variable might have an incompatible type. For instance:
3278     //
3279     //   extern int arr[];
3280     //   void f() { extern int arr[2]; }
3281     //   void g() { extern int arr[3]; }
3282     //
3283     // Neither C nor C++ requires a diagnostic for this, but we should still try
3284     // to diagnose it.
3285     Diag(New->getLocation(), New->isThisDeclarationADefinition()
3286                                  ? diag::err_redefinition_different_type
3287                                  : diag::err_redeclaration_different_type)
3288         << New->getDeclName() << New->getType() << Old->getType();
3289 
3290     diag::kind PrevDiag;
3291     SourceLocation OldLocation;
3292     std::tie(PrevDiag, OldLocation) =
3293         getNoteDiagForInvalidRedeclaration(Old, New);
3294     Diag(OldLocation, PrevDiag);
3295     return New->setInvalidDecl();
3296   }
3297 
3298   // Don't actually update the type on the new declaration if the old
3299   // declaration was an extern declaration in a different scope.
3300   if (MergeTypeWithOld)
3301     New->setType(MergedT);
3302 }
3303 
3304 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
3305                                   LookupResult &Previous) {
3306   // C11 6.2.7p4:
3307   //   For an identifier with internal or external linkage declared
3308   //   in a scope in which a prior declaration of that identifier is
3309   //   visible, if the prior declaration specifies internal or
3310   //   external linkage, the type of the identifier at the later
3311   //   declaration becomes the composite type.
3312   //
3313   // If the variable isn't visible, we do not merge with its type.
3314   if (Previous.isShadowed())
3315     return false;
3316 
3317   if (S.getLangOpts().CPlusPlus) {
3318     // C++11 [dcl.array]p3:
3319     //   If there is a preceding declaration of the entity in the same
3320     //   scope in which the bound was specified, an omitted array bound
3321     //   is taken to be the same as in that earlier declaration.
3322     return NewVD->isPreviousDeclInSameBlockScope() ||
3323            (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
3324             !NewVD->getLexicalDeclContext()->isFunctionOrMethod());
3325   } else {
3326     // If the old declaration was function-local, don't merge with its
3327     // type unless we're in the same function.
3328     return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
3329            OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
3330   }
3331 }
3332 
3333 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
3334 /// and scope as a previous declaration 'Old'.  Figure out how to resolve this
3335 /// situation, merging decls or emitting diagnostics as appropriate.
3336 ///
3337 /// Tentative definition rules (C99 6.9.2p2) are checked by
3338 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
3339 /// definitions here, since the initializer hasn't been attached.
3340 ///
3341 void Sema::MergeVarDecl(VarDecl *New, LookupResult &Previous) {
3342   // If the new decl is already invalid, don't do any other checking.
3343   if (New->isInvalidDecl())
3344     return;
3345 
3346   if (!shouldLinkPossiblyHiddenDecl(Previous, New))
3347     return;
3348 
3349   VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
3350 
3351   // Verify the old decl was also a variable or variable template.
3352   VarDecl *Old = nullptr;
3353   VarTemplateDecl *OldTemplate = nullptr;
3354   if (Previous.isSingleResult()) {
3355     if (NewTemplate) {
3356       OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
3357       Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
3358 
3359       if (auto *Shadow =
3360               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3361         if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
3362           return New->setInvalidDecl();
3363     } else {
3364       Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
3365 
3366       if (auto *Shadow =
3367               dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
3368         if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
3369           return New->setInvalidDecl();
3370     }
3371   }
3372   if (!Old) {
3373     Diag(New->getLocation(), diag::err_redefinition_different_kind)
3374       << New->getDeclName();
3375     Diag(Previous.getRepresentativeDecl()->getLocation(),
3376          diag::note_previous_definition);
3377     return New->setInvalidDecl();
3378   }
3379 
3380   // Ensure the template parameters are compatible.
3381   if (NewTemplate &&
3382       !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
3383                                       OldTemplate->getTemplateParameters(),
3384                                       /*Complain=*/true, TPL_TemplateMatch))
3385     return New->setInvalidDecl();
3386 
3387   // C++ [class.mem]p1:
3388   //   A member shall not be declared twice in the member-specification [...]
3389   //
3390   // Here, we need only consider static data members.
3391   if (Old->isStaticDataMember() && !New->isOutOfLine()) {
3392     Diag(New->getLocation(), diag::err_duplicate_member)
3393       << New->getIdentifier();
3394     Diag(Old->getLocation(), diag::note_previous_declaration);
3395     New->setInvalidDecl();
3396   }
3397 
3398   mergeDeclAttributes(New, Old);
3399   // Warn if an already-declared variable is made a weak_import in a subsequent
3400   // declaration
3401   if (New->hasAttr<WeakImportAttr>() &&
3402       Old->getStorageClass() == SC_None &&
3403       !Old->hasAttr<WeakImportAttr>()) {
3404     Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
3405     Diag(Old->getLocation(), diag::note_previous_definition);
3406     // Remove weak_import attribute on new declaration.
3407     New->dropAttr<WeakImportAttr>();
3408   }
3409 
3410   if (New->hasAttr<InternalLinkageAttr>() &&
3411       !Old->hasAttr<InternalLinkageAttr>()) {
3412     Diag(New->getLocation(), diag::err_internal_linkage_redeclaration)
3413         << New->getDeclName();
3414     Diag(Old->getLocation(), diag::note_previous_definition);
3415     New->dropAttr<InternalLinkageAttr>();
3416   }
3417 
3418   // Merge the types.
3419   VarDecl *MostRecent = Old->getMostRecentDecl();
3420   if (MostRecent != Old) {
3421     MergeVarDeclTypes(New, MostRecent,
3422                       mergeTypeWithPrevious(*this, New, MostRecent, Previous));
3423     if (New->isInvalidDecl())
3424       return;
3425   }
3426 
3427   MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
3428   if (New->isInvalidDecl())
3429     return;
3430 
3431   diag::kind PrevDiag;
3432   SourceLocation OldLocation;
3433   std::tie(PrevDiag, OldLocation) =
3434       getNoteDiagForInvalidRedeclaration(Old, New);
3435 
3436   // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
3437   if (New->getStorageClass() == SC_Static &&
3438       !New->isStaticDataMember() &&
3439       Old->hasExternalFormalLinkage()) {
3440     if (getLangOpts().MicrosoftExt) {
3441       Diag(New->getLocation(), diag::ext_static_non_static)
3442           << New->getDeclName();
3443       Diag(OldLocation, PrevDiag);
3444     } else {
3445       Diag(New->getLocation(), diag::err_static_non_static)
3446           << New->getDeclName();
3447       Diag(OldLocation, PrevDiag);
3448       return New->setInvalidDecl();
3449     }
3450   }
3451   // C99 6.2.2p4:
3452   //   For an identifier declared with the storage-class specifier
3453   //   extern in a scope in which a prior declaration of that
3454   //   identifier is visible,23) if the prior declaration specifies
3455   //   internal or external linkage, the linkage of the identifier at
3456   //   the later declaration is the same as the linkage specified at
3457   //   the prior declaration. If no prior declaration is visible, or
3458   //   if the prior declaration specifies no linkage, then the
3459   //   identifier has external linkage.
3460   if (New->hasExternalStorage() && Old->hasLinkage())
3461     /* Okay */;
3462   else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
3463            !New->isStaticDataMember() &&
3464            Old->getCanonicalDecl()->getStorageClass() == SC_Static) {
3465     Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
3466     Diag(OldLocation, PrevDiag);
3467     return New->setInvalidDecl();
3468   }
3469 
3470   // Check if extern is followed by non-extern and vice-versa.
3471   if (New->hasExternalStorage() &&
3472       !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
3473     Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
3474     Diag(OldLocation, PrevDiag);
3475     return New->setInvalidDecl();
3476   }
3477   if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
3478       !New->hasExternalStorage()) {
3479     Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
3480     Diag(OldLocation, PrevDiag);
3481     return New->setInvalidDecl();
3482   }
3483 
3484   // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
3485 
3486   // FIXME: The test for external storage here seems wrong? We still
3487   // need to check for mismatches.
3488   if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
3489       // Don't complain about out-of-line definitions of static members.
3490       !(Old->getLexicalDeclContext()->isRecord() &&
3491         !New->getLexicalDeclContext()->isRecord())) {
3492     Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
3493     Diag(OldLocation, PrevDiag);
3494     return New->setInvalidDecl();
3495   }
3496 
3497   if (New->getTLSKind() != Old->getTLSKind()) {
3498     if (!Old->getTLSKind()) {
3499       Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
3500       Diag(OldLocation, PrevDiag);
3501     } else if (!New->getTLSKind()) {
3502       Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
3503       Diag(OldLocation, PrevDiag);
3504     } else {
3505       // Do not allow redeclaration to change the variable between requiring
3506       // static and dynamic initialization.
3507       // FIXME: GCC allows this, but uses the TLS keyword on the first
3508       // declaration to determine the kind. Do we need to be compatible here?
3509       Diag(New->getLocation(), diag::err_thread_thread_different_kind)
3510         << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
3511       Diag(OldLocation, PrevDiag);
3512     }
3513   }
3514 
3515   // C++ doesn't have tentative definitions, so go right ahead and check here.
3516   VarDecl *Def;
3517   if (getLangOpts().CPlusPlus &&
3518       New->isThisDeclarationADefinition() == VarDecl::Definition &&
3519       (Def = Old->getDefinition())) {
3520     NamedDecl *Hidden = nullptr;
3521     if (!hasVisibleDefinition(Def, &Hidden) &&
3522         (New->getFormalLinkage() == InternalLinkage ||
3523          New->getDescribedVarTemplate() ||
3524          New->getNumTemplateParameterLists() ||
3525          New->getDeclContext()->isDependentContext())) {
3526       // The previous definition is hidden, and multiple definitions are
3527       // permitted (in separate TUs). Form another definition of it.
3528     } else {
3529       Diag(New->getLocation(), diag::err_redefinition) << New;
3530       Diag(Def->getLocation(), diag::note_previous_definition);
3531       New->setInvalidDecl();
3532       return;
3533     }
3534   }
3535 
3536   if (haveIncompatibleLanguageLinkages(Old, New)) {
3537     Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3538     Diag(OldLocation, PrevDiag);
3539     New->setInvalidDecl();
3540     return;
3541   }
3542 
3543   // Merge "used" flag.
3544   if (Old->getMostRecentDecl()->isUsed(false))
3545     New->setIsUsed();
3546 
3547   // Keep a chain of previous declarations.
3548   New->setPreviousDecl(Old);
3549   if (NewTemplate)
3550     NewTemplate->setPreviousDecl(OldTemplate);
3551 
3552   // Inherit access appropriately.
3553   New->setAccess(Old->getAccess());
3554   if (NewTemplate)
3555     NewTemplate->setAccess(New->getAccess());
3556 }
3557 
3558 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3559 /// no declarator (e.g. "struct foo;") is parsed.
3560 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3561                                        DeclSpec &DS) {
3562   return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg());
3563 }
3564 
3565 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
3566 // disambiguate entities defined in different scopes.
3567 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
3568 // compatibility.
3569 // We will pick our mangling number depending on which version of MSVC is being
3570 // targeted.
3571 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
3572   return LO.isCompatibleWithMSVC(LangOptions::MSVC2015)
3573              ? S->getMSCurManglingNumber()
3574              : S->getMSLastManglingNumber();
3575 }
3576 
3577 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
3578   if (!Context.getLangOpts().CPlusPlus)
3579     return;
3580 
3581   if (isa<CXXRecordDecl>(Tag->getParent())) {
3582     // If this tag is the direct child of a class, number it if
3583     // it is anonymous.
3584     if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
3585       return;
3586     MangleNumberingContext &MCtx =
3587         Context.getManglingNumberContext(Tag->getParent());
3588     Context.setManglingNumber(
3589         Tag, MCtx.getManglingNumber(
3590                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3591     return;
3592   }
3593 
3594   // If this tag isn't a direct child of a class, number it if it is local.
3595   Decl *ManglingContextDecl;
3596   if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
3597           Tag->getDeclContext(), ManglingContextDecl)) {
3598     Context.setManglingNumber(
3599         Tag, MCtx->getManglingNumber(
3600                  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
3601   }
3602 }
3603 
3604 void Sema::setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec,
3605                                         TypedefNameDecl *NewTD) {
3606   if (TagFromDeclSpec->isInvalidDecl())
3607     return;
3608 
3609   // Do nothing if the tag already has a name for linkage purposes.
3610   if (TagFromDeclSpec->hasNameForLinkage())
3611     return;
3612 
3613   // A well-formed anonymous tag must always be a TUK_Definition.
3614   assert(TagFromDeclSpec->isThisDeclarationADefinition());
3615 
3616   // The type must match the tag exactly;  no qualifiers allowed.
3617   if (!Context.hasSameType(NewTD->getUnderlyingType(),
3618                            Context.getTagDeclType(TagFromDeclSpec))) {
3619     if (getLangOpts().CPlusPlus)
3620       Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
3621     return;
3622   }
3623 
3624   // If we've already computed linkage for the anonymous tag, then
3625   // adding a typedef name for the anonymous decl can change that
3626   // linkage, which might be a serious problem.  Diagnose this as
3627   // unsupported and ignore the typedef name.  TODO: we should
3628   // pursue this as a language defect and establish a formal rule
3629   // for how to handle it.
3630   if (TagFromDeclSpec->hasLinkageBeenComputed()) {
3631     Diag(NewTD->getLocation(), diag::err_typedef_changes_linkage);
3632 
3633     SourceLocation tagLoc = TagFromDeclSpec->getInnerLocStart();
3634     tagLoc = getLocForEndOfToken(tagLoc);
3635 
3636     llvm::SmallString<40> textToInsert;
3637     textToInsert += ' ';
3638     textToInsert += NewTD->getIdentifier()->getName();
3639     Diag(tagLoc, diag::note_typedef_changes_linkage)
3640         << FixItHint::CreateInsertion(tagLoc, textToInsert);
3641     return;
3642   }
3643 
3644   // Otherwise, set this is the anon-decl typedef for the tag.
3645   TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
3646 }
3647 
3648 static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T) {
3649   switch (T) {
3650   case DeclSpec::TST_class:
3651     return 0;
3652   case DeclSpec::TST_struct:
3653     return 1;
3654   case DeclSpec::TST_interface:
3655     return 2;
3656   case DeclSpec::TST_union:
3657     return 3;
3658   case DeclSpec::TST_enum:
3659     return 4;
3660   default:
3661     llvm_unreachable("unexpected type specifier");
3662   }
3663 }
3664 
3665 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
3666 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
3667 /// parameters to cope with template friend declarations.
3668 Decl *Sema::ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS,
3669                                        DeclSpec &DS,
3670                                        MultiTemplateParamsArg TemplateParams,
3671                                        bool IsExplicitInstantiation) {
3672   Decl *TagD = nullptr;
3673   TagDecl *Tag = nullptr;
3674   if (DS.getTypeSpecType() == DeclSpec::TST_class ||
3675       DS.getTypeSpecType() == DeclSpec::TST_struct ||
3676       DS.getTypeSpecType() == DeclSpec::TST_interface ||
3677       DS.getTypeSpecType() == DeclSpec::TST_union ||
3678       DS.getTypeSpecType() == DeclSpec::TST_enum) {
3679     TagD = DS.getRepAsDecl();
3680 
3681     if (!TagD) // We probably had an error
3682       return nullptr;
3683 
3684     // Note that the above type specs guarantee that the
3685     // type rep is a Decl, whereas in many of the others
3686     // it's a Type.
3687     if (isa<TagDecl>(TagD))
3688       Tag = cast<TagDecl>(TagD);
3689     else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
3690       Tag = CTD->getTemplatedDecl();
3691   }
3692 
3693   if (Tag) {
3694     handleTagNumbering(Tag, S);
3695     Tag->setFreeStanding();
3696     if (Tag->isInvalidDecl())
3697       return Tag;
3698   }
3699 
3700   if (unsigned TypeQuals = DS.getTypeQualifiers()) {
3701     // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
3702     // or incomplete types shall not be restrict-qualified."
3703     if (TypeQuals & DeclSpec::TQ_restrict)
3704       Diag(DS.getRestrictSpecLoc(),
3705            diag::err_typecheck_invalid_restrict_not_pointer_noarg)
3706            << DS.getSourceRange();
3707   }
3708 
3709   if (DS.isConstexprSpecified()) {
3710     // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
3711     // and definitions of functions and variables.
3712     if (Tag)
3713       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
3714           << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType());
3715     else
3716       Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_no_declarators);
3717     // Don't emit warnings after this error.
3718     return TagD;
3719   }
3720 
3721   if (DS.isConceptSpecified()) {
3722     // C++ Concepts TS [dcl.spec.concept]p1: A concept definition refers to
3723     // either a function concept and its definition or a variable concept and
3724     // its initializer.
3725     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
3726     return TagD;
3727   }
3728 
3729   DiagnoseFunctionSpecifiers(DS);
3730 
3731   if (DS.isFriendSpecified()) {
3732     // If we're dealing with a decl but not a TagDecl, assume that
3733     // whatever routines created it handled the friendship aspect.
3734     if (TagD && !Tag)
3735       return nullptr;
3736     return ActOnFriendTypeDecl(S, DS, TemplateParams);
3737   }
3738 
3739   const CXXScopeSpec &SS = DS.getTypeSpecScope();
3740   bool IsExplicitSpecialization =
3741     !TemplateParams.empty() && TemplateParams.back()->size() == 0;
3742   if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
3743       !IsExplicitInstantiation && !IsExplicitSpecialization) {
3744     // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
3745     // nested-name-specifier unless it is an explicit instantiation
3746     // or an explicit specialization.
3747     // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
3748     Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
3749         << GetDiagnosticTypeSpecifierID(DS.getTypeSpecType()) << SS.getRange();
3750     return nullptr;
3751   }
3752 
3753   // Track whether this decl-specifier declares anything.
3754   bool DeclaresAnything = true;
3755 
3756   // Handle anonymous struct definitions.
3757   if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
3758     if (!Record->getDeclName() && Record->isCompleteDefinition() &&
3759         DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
3760       if (getLangOpts().CPlusPlus ||
3761           Record->getDeclContext()->isRecord())
3762         return BuildAnonymousStructOrUnion(S, DS, AS, Record,
3763                                            Context.getPrintingPolicy());
3764 
3765       DeclaresAnything = false;
3766     }
3767   }
3768 
3769   // C11 6.7.2.1p2:
3770   //   A struct-declaration that does not declare an anonymous structure or
3771   //   anonymous union shall contain a struct-declarator-list.
3772   //
3773   // This rule also existed in C89 and C99; the grammar for struct-declaration
3774   // did not permit a struct-declaration without a struct-declarator-list.
3775   if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
3776       DS.getStorageClassSpec() == DeclSpec::SCS_unspecified) {
3777     // Check for Microsoft C extension: anonymous struct/union member.
3778     // Handle 2 kinds of anonymous struct/union:
3779     //   struct STRUCT;
3780     //   union UNION;
3781     // and
3782     //   STRUCT_TYPE;  <- where STRUCT_TYPE is a typedef struct.
3783     //   UNION_TYPE;   <- where UNION_TYPE is a typedef union.
3784     if ((Tag && Tag->getDeclName()) ||
3785         DS.getTypeSpecType() == DeclSpec::TST_typename) {
3786       RecordDecl *Record = nullptr;
3787       if (Tag)
3788         Record = dyn_cast<RecordDecl>(Tag);
3789       else if (const RecordType *RT =
3790                    DS.getRepAsType().get()->getAsStructureType())
3791         Record = RT->getDecl();
3792       else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
3793         Record = UT->getDecl();
3794 
3795       if (Record && getLangOpts().MicrosoftExt) {
3796         Diag(DS.getLocStart(), diag::ext_ms_anonymous_record)
3797           << Record->isUnion() << DS.getSourceRange();
3798         return BuildMicrosoftCAnonymousStruct(S, DS, Record);
3799       }
3800 
3801       DeclaresAnything = false;
3802     }
3803   }
3804 
3805   // Skip all the checks below if we have a type error.
3806   if (DS.getTypeSpecType() == DeclSpec::TST_error ||
3807       (TagD && TagD->isInvalidDecl()))
3808     return TagD;
3809 
3810   if (getLangOpts().CPlusPlus &&
3811       DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
3812     if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
3813       if (Enum->enumerator_begin() == Enum->enumerator_end() &&
3814           !Enum->getIdentifier() && !Enum->isInvalidDecl())
3815         DeclaresAnything = false;
3816 
3817   if (!DS.isMissingDeclaratorOk()) {
3818     // Customize diagnostic for a typedef missing a name.
3819     if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
3820       Diag(DS.getLocStart(), diag::ext_typedef_without_a_name)
3821         << DS.getSourceRange();
3822     else
3823       DeclaresAnything = false;
3824   }
3825 
3826   if (DS.isModulePrivateSpecified() &&
3827       Tag && Tag->getDeclContext()->isFunctionOrMethod())
3828     Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
3829       << Tag->getTagKind()
3830       << FixItHint::CreateRemoval(DS.getModulePrivateSpecLoc());
3831 
3832   ActOnDocumentableDecl(TagD);
3833 
3834   // C 6.7/2:
3835   //   A declaration [...] shall declare at least a declarator [...], a tag,
3836   //   or the members of an enumeration.
3837   // C++ [dcl.dcl]p3:
3838   //   [If there are no declarators], and except for the declaration of an
3839   //   unnamed bit-field, the decl-specifier-seq shall introduce one or more
3840   //   names into the program, or shall redeclare a name introduced by a
3841   //   previous declaration.
3842   if (!DeclaresAnything) {
3843     // In C, we allow this as a (popular) extension / bug. Don't bother
3844     // producing further diagnostics for redundant qualifiers after this.
3845     Diag(DS.getLocStart(), diag::ext_no_declarators) << DS.getSourceRange();
3846     return TagD;
3847   }
3848 
3849   // C++ [dcl.stc]p1:
3850   //   If a storage-class-specifier appears in a decl-specifier-seq, [...] the
3851   //   init-declarator-list of the declaration shall not be empty.
3852   // C++ [dcl.fct.spec]p1:
3853   //   If a cv-qualifier appears in a decl-specifier-seq, the
3854   //   init-declarator-list of the declaration shall not be empty.
3855   //
3856   // Spurious qualifiers here appear to be valid in C.
3857   unsigned DiagID = diag::warn_standalone_specifier;
3858   if (getLangOpts().CPlusPlus)
3859     DiagID = diag::ext_standalone_specifier;
3860 
3861   // Note that a linkage-specification sets a storage class, but
3862   // 'extern "C" struct foo;' is actually valid and not theoretically
3863   // useless.
3864   if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3865     if (SCS == DeclSpec::SCS_mutable)
3866       // Since mutable is not a viable storage class specifier in C, there is
3867       // no reason to treat it as an extension. Instead, diagnose as an error.
3868       Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
3869     else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
3870       Diag(DS.getStorageClassSpecLoc(), DiagID)
3871         << DeclSpec::getSpecifierName(SCS);
3872   }
3873 
3874   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
3875     Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
3876       << DeclSpec::getSpecifierName(TSCS);
3877   if (DS.getTypeQualifiers()) {
3878     if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
3879       Diag(DS.getConstSpecLoc(), DiagID) << "const";
3880     if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
3881       Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
3882     // Restrict is covered above.
3883     if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
3884       Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
3885   }
3886 
3887   // Warn about ignored type attributes, for example:
3888   // __attribute__((aligned)) struct A;
3889   // Attributes should be placed after tag to apply to type declaration.
3890   if (!DS.getAttributes().empty()) {
3891     DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
3892     if (TypeSpecType == DeclSpec::TST_class ||
3893         TypeSpecType == DeclSpec::TST_struct ||
3894         TypeSpecType == DeclSpec::TST_interface ||
3895         TypeSpecType == DeclSpec::TST_union ||
3896         TypeSpecType == DeclSpec::TST_enum) {
3897       for (AttributeList* attrs = DS.getAttributes().getList(); attrs;
3898            attrs = attrs->getNext())
3899         Diag(attrs->getLoc(), diag::warn_declspec_attribute_ignored)
3900             << attrs->getName() << GetDiagnosticTypeSpecifierID(TypeSpecType);
3901     }
3902   }
3903 
3904   return TagD;
3905 }
3906 
3907 /// We are trying to inject an anonymous member into the given scope;
3908 /// check if there's an existing declaration that can't be overloaded.
3909 ///
3910 /// \return true if this is a forbidden redeclaration
3911 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
3912                                          Scope *S,
3913                                          DeclContext *Owner,
3914                                          DeclarationName Name,
3915                                          SourceLocation NameLoc,
3916                                          bool IsUnion) {
3917   LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
3918                  Sema::ForRedeclaration);
3919   if (!SemaRef.LookupName(R, S)) return false;
3920 
3921   if (R.getAsSingle<TagDecl>())
3922     return false;
3923 
3924   // Pick a representative declaration.
3925   NamedDecl *PrevDecl = R.getRepresentativeDecl()->getUnderlyingDecl();
3926   assert(PrevDecl && "Expected a non-null Decl");
3927 
3928   if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
3929     return false;
3930 
3931   SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
3932     << IsUnion << Name;
3933   SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3934 
3935   return true;
3936 }
3937 
3938 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
3939 /// anonymous struct or union AnonRecord into the owning context Owner
3940 /// and scope S. This routine will be invoked just after we realize
3941 /// that an unnamed union or struct is actually an anonymous union or
3942 /// struct, e.g.,
3943 ///
3944 /// @code
3945 /// union {
3946 ///   int i;
3947 ///   float f;
3948 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
3949 ///    // f into the surrounding scope.x
3950 /// @endcode
3951 ///
3952 /// This routine is recursive, injecting the names of nested anonymous
3953 /// structs/unions into the owning context and scope as well.
3954 static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S,
3955                                          DeclContext *Owner,
3956                                          RecordDecl *AnonRecord,
3957                                          AccessSpecifier AS,
3958                                          SmallVectorImpl<NamedDecl *> &Chaining,
3959                                          bool MSAnonStruct) {
3960   bool Invalid = false;
3961 
3962   // Look every FieldDecl and IndirectFieldDecl with a name.
3963   for (auto *D : AnonRecord->decls()) {
3964     if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
3965         cast<NamedDecl>(D)->getDeclName()) {
3966       ValueDecl *VD = cast<ValueDecl>(D);
3967       if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
3968                                        VD->getLocation(),
3969                                        AnonRecord->isUnion())) {
3970         // C++ [class.union]p2:
3971         //   The names of the members of an anonymous union shall be
3972         //   distinct from the names of any other entity in the
3973         //   scope in which the anonymous union is declared.
3974         Invalid = true;
3975       } else {
3976         // C++ [class.union]p2:
3977         //   For the purpose of name lookup, after the anonymous union
3978         //   definition, the members of the anonymous union are
3979         //   considered to have been defined in the scope in which the
3980         //   anonymous union is declared.
3981         unsigned OldChainingSize = Chaining.size();
3982         if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
3983           Chaining.append(IF->chain_begin(), IF->chain_end());
3984         else
3985           Chaining.push_back(VD);
3986 
3987         assert(Chaining.size() >= 2);
3988         NamedDecl **NamedChain =
3989           new (SemaRef.Context)NamedDecl*[Chaining.size()];
3990         for (unsigned i = 0; i < Chaining.size(); i++)
3991           NamedChain[i] = Chaining[i];
3992 
3993         IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
3994             SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
3995             VD->getType(), NamedChain, Chaining.size());
3996 
3997         for (const auto *Attr : VD->attrs())
3998           IndirectField->addAttr(Attr->clone(SemaRef.Context));
3999 
4000         IndirectField->setAccess(AS);
4001         IndirectField->setImplicit();
4002         SemaRef.PushOnScopeChains(IndirectField, S);
4003 
4004         // That includes picking up the appropriate access specifier.
4005         if (AS != AS_none) IndirectField->setAccess(AS);
4006 
4007         Chaining.resize(OldChainingSize);
4008       }
4009     }
4010   }
4011 
4012   return Invalid;
4013 }
4014 
4015 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
4016 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
4017 /// illegal input values are mapped to SC_None.
4018 static StorageClass
4019 StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS) {
4020   DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
4021   assert(StorageClassSpec != DeclSpec::SCS_typedef &&
4022          "Parser allowed 'typedef' as storage class VarDecl.");
4023   switch (StorageClassSpec) {
4024   case DeclSpec::SCS_unspecified:    return SC_None;
4025   case DeclSpec::SCS_extern:
4026     if (DS.isExternInLinkageSpec())
4027       return SC_None;
4028     return SC_Extern;
4029   case DeclSpec::SCS_static:         return SC_Static;
4030   case DeclSpec::SCS_auto:           return SC_Auto;
4031   case DeclSpec::SCS_register:       return SC_Register;
4032   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
4033     // Illegal SCSs map to None: error reporting is up to the caller.
4034   case DeclSpec::SCS_mutable:        // Fall through.
4035   case DeclSpec::SCS_typedef:        return SC_None;
4036   }
4037   llvm_unreachable("unknown storage class specifier");
4038 }
4039 
4040 static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record) {
4041   assert(Record->hasInClassInitializer());
4042 
4043   for (const auto *I : Record->decls()) {
4044     const auto *FD = dyn_cast<FieldDecl>(I);
4045     if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
4046       FD = IFD->getAnonField();
4047     if (FD && FD->hasInClassInitializer())
4048       return FD->getLocation();
4049   }
4050 
4051   llvm_unreachable("couldn't find in-class initializer");
4052 }
4053 
4054 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4055                                       SourceLocation DefaultInitLoc) {
4056   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4057     return;
4058 
4059   S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
4060   S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
4061 }
4062 
4063 static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent,
4064                                       CXXRecordDecl *AnonUnion) {
4065   if (!Parent->isUnion() || !Parent->hasInClassInitializer())
4066     return;
4067 
4068   checkDuplicateDefaultInit(S, Parent, findDefaultInitializer(AnonUnion));
4069 }
4070 
4071 /// BuildAnonymousStructOrUnion - Handle the declaration of an
4072 /// anonymous structure or union. Anonymous unions are a C++ feature
4073 /// (C++ [class.union]) and a C11 feature; anonymous structures
4074 /// are a C11 feature and GNU C++ extension.
4075 Decl *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
4076                                         AccessSpecifier AS,
4077                                         RecordDecl *Record,
4078                                         const PrintingPolicy &Policy) {
4079   DeclContext *Owner = Record->getDeclContext();
4080 
4081   // Diagnose whether this anonymous struct/union is an extension.
4082   if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
4083     Diag(Record->getLocation(), diag::ext_anonymous_union);
4084   else if (!Record->isUnion() && getLangOpts().CPlusPlus)
4085     Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
4086   else if (!Record->isUnion() && !getLangOpts().C11)
4087     Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
4088 
4089   // C and C++ require different kinds of checks for anonymous
4090   // structs/unions.
4091   bool Invalid = false;
4092   if (getLangOpts().CPlusPlus) {
4093     const char *PrevSpec = nullptr;
4094     unsigned DiagID;
4095     if (Record->isUnion()) {
4096       // C++ [class.union]p6:
4097       //   Anonymous unions declared in a named namespace or in the
4098       //   global namespace shall be declared static.
4099       if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
4100           (isa<TranslationUnitDecl>(Owner) ||
4101            (isa<NamespaceDecl>(Owner) &&
4102             cast<NamespaceDecl>(Owner)->getDeclName()))) {
4103         Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
4104           << FixItHint::CreateInsertion(Record->getLocation(), "static ");
4105 
4106         // Recover by adding 'static'.
4107         DS.SetStorageClassSpec(*this, DeclSpec::SCS_static, SourceLocation(),
4108                                PrevSpec, DiagID, Policy);
4109       }
4110       // C++ [class.union]p6:
4111       //   A storage class is not allowed in a declaration of an
4112       //   anonymous union in a class scope.
4113       else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
4114                isa<RecordDecl>(Owner)) {
4115         Diag(DS.getStorageClassSpecLoc(),
4116              diag::err_anonymous_union_with_storage_spec)
4117           << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
4118 
4119         // Recover by removing the storage specifier.
4120         DS.SetStorageClassSpec(*this, DeclSpec::SCS_unspecified,
4121                                SourceLocation(),
4122                                PrevSpec, DiagID, Context.getPrintingPolicy());
4123       }
4124     }
4125 
4126     // Ignore const/volatile/restrict qualifiers.
4127     if (DS.getTypeQualifiers()) {
4128       if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
4129         Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
4130           << Record->isUnion() << "const"
4131           << FixItHint::CreateRemoval(DS.getConstSpecLoc());
4132       if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
4133         Diag(DS.getVolatileSpecLoc(),
4134              diag::ext_anonymous_struct_union_qualified)
4135           << Record->isUnion() << "volatile"
4136           << FixItHint::CreateRemoval(DS.getVolatileSpecLoc());
4137       if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
4138         Diag(DS.getRestrictSpecLoc(),
4139              diag::ext_anonymous_struct_union_qualified)
4140           << Record->isUnion() << "restrict"
4141           << FixItHint::CreateRemoval(DS.getRestrictSpecLoc());
4142       if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
4143         Diag(DS.getAtomicSpecLoc(),
4144              diag::ext_anonymous_struct_union_qualified)
4145           << Record->isUnion() << "_Atomic"
4146           << FixItHint::CreateRemoval(DS.getAtomicSpecLoc());
4147 
4148       DS.ClearTypeQualifiers();
4149     }
4150 
4151     // C++ [class.union]p2:
4152     //   The member-specification of an anonymous union shall only
4153     //   define non-static data members. [Note: nested types and
4154     //   functions cannot be declared within an anonymous union. ]
4155     for (auto *Mem : Record->decls()) {
4156       if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
4157         // C++ [class.union]p3:
4158         //   An anonymous union shall not have private or protected
4159         //   members (clause 11).
4160         assert(FD->getAccess() != AS_none);
4161         if (FD->getAccess() != AS_public) {
4162           Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
4163             << Record->isUnion() << (FD->getAccess() == AS_protected);
4164           Invalid = true;
4165         }
4166 
4167         // C++ [class.union]p1
4168         //   An object of a class with a non-trivial constructor, a non-trivial
4169         //   copy constructor, a non-trivial destructor, or a non-trivial copy
4170         //   assignment operator cannot be a member of a union, nor can an
4171         //   array of such objects.
4172         if (CheckNontrivialField(FD))
4173           Invalid = true;
4174       } else if (Mem->isImplicit()) {
4175         // Any implicit members are fine.
4176       } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
4177         // This is a type that showed up in an
4178         // elaborated-type-specifier inside the anonymous struct or
4179         // union, but which actually declares a type outside of the
4180         // anonymous struct or union. It's okay.
4181       } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
4182         if (!MemRecord->isAnonymousStructOrUnion() &&
4183             MemRecord->getDeclName()) {
4184           // Visual C++ allows type definition in anonymous struct or union.
4185           if (getLangOpts().MicrosoftExt)
4186             Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
4187               << Record->isUnion();
4188           else {
4189             // This is a nested type declaration.
4190             Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
4191               << Record->isUnion();
4192             Invalid = true;
4193           }
4194         } else {
4195           // This is an anonymous type definition within another anonymous type.
4196           // This is a popular extension, provided by Plan9, MSVC and GCC, but
4197           // not part of standard C++.
4198           Diag(MemRecord->getLocation(),
4199                diag::ext_anonymous_record_with_anonymous_type)
4200             << Record->isUnion();
4201         }
4202       } else if (isa<AccessSpecDecl>(Mem)) {
4203         // Any access specifier is fine.
4204       } else if (isa<StaticAssertDecl>(Mem)) {
4205         // In C++1z, static_assert declarations are also fine.
4206       } else {
4207         // We have something that isn't a non-static data
4208         // member. Complain about it.
4209         unsigned DK = diag::err_anonymous_record_bad_member;
4210         if (isa<TypeDecl>(Mem))
4211           DK = diag::err_anonymous_record_with_type;
4212         else if (isa<FunctionDecl>(Mem))
4213           DK = diag::err_anonymous_record_with_function;
4214         else if (isa<VarDecl>(Mem))
4215           DK = diag::err_anonymous_record_with_static;
4216 
4217         // Visual C++ allows type definition in anonymous struct or union.
4218         if (getLangOpts().MicrosoftExt &&
4219             DK == diag::err_anonymous_record_with_type)
4220           Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
4221             << Record->isUnion();
4222         else {
4223           Diag(Mem->getLocation(), DK) << Record->isUnion();
4224           Invalid = true;
4225         }
4226       }
4227     }
4228 
4229     // C++11 [class.union]p8 (DR1460):
4230     //   At most one variant member of a union may have a
4231     //   brace-or-equal-initializer.
4232     if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
4233         Owner->isRecord())
4234       checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
4235                                 cast<CXXRecordDecl>(Record));
4236   }
4237 
4238   if (!Record->isUnion() && !Owner->isRecord()) {
4239     Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
4240       << getLangOpts().CPlusPlus;
4241     Invalid = true;
4242   }
4243 
4244   // Mock up a declarator.
4245   Declarator Dc(DS, Declarator::MemberContext);
4246   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4247   assert(TInfo && "couldn't build declarator info for anonymous struct/union");
4248 
4249   // Create a declaration for this anonymous struct/union.
4250   NamedDecl *Anon = nullptr;
4251   if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
4252     Anon = FieldDecl::Create(Context, OwningClass,
4253                              DS.getLocStart(),
4254                              Record->getLocation(),
4255                              /*IdentifierInfo=*/nullptr,
4256                              Context.getTypeDeclType(Record),
4257                              TInfo,
4258                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4259                              /*InitStyle=*/ICIS_NoInit);
4260     Anon->setAccess(AS);
4261     if (getLangOpts().CPlusPlus)
4262       FieldCollector->Add(cast<FieldDecl>(Anon));
4263   } else {
4264     DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
4265     StorageClass SC = StorageClassSpecToVarDeclStorageClass(DS);
4266     if (SCSpec == DeclSpec::SCS_mutable) {
4267       // mutable can only appear on non-static class members, so it's always
4268       // an error here
4269       Diag(Record->getLocation(), diag::err_mutable_nonmember);
4270       Invalid = true;
4271       SC = SC_None;
4272     }
4273 
4274     Anon = VarDecl::Create(Context, Owner,
4275                            DS.getLocStart(),
4276                            Record->getLocation(), /*IdentifierInfo=*/nullptr,
4277                            Context.getTypeDeclType(Record),
4278                            TInfo, SC);
4279 
4280     // Default-initialize the implicit variable. This initialization will be
4281     // trivial in almost all cases, except if a union member has an in-class
4282     // initializer:
4283     //   union { int n = 0; };
4284     ActOnUninitializedDecl(Anon, /*TypeMayContainAuto=*/false);
4285   }
4286   Anon->setImplicit();
4287 
4288   // Mark this as an anonymous struct/union type.
4289   Record->setAnonymousStructOrUnion(true);
4290 
4291   // Add the anonymous struct/union object to the current
4292   // context. We'll be referencing this object when we refer to one of
4293   // its members.
4294   Owner->addDecl(Anon);
4295 
4296   // Inject the members of the anonymous struct/union into the owning
4297   // context and into the identifier resolver chain for name lookup
4298   // purposes.
4299   SmallVector<NamedDecl*, 2> Chain;
4300   Chain.push_back(Anon);
4301 
4302   if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS,
4303                                           Chain, false))
4304     Invalid = true;
4305 
4306   if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
4307     if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
4308       Decl *ManglingContextDecl;
4309       if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
4310               NewVD->getDeclContext(), ManglingContextDecl)) {
4311         Context.setManglingNumber(
4312             NewVD, MCtx->getManglingNumber(
4313                        NewVD, getMSManglingNumber(getLangOpts(), S)));
4314         Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
4315       }
4316     }
4317   }
4318 
4319   if (Invalid)
4320     Anon->setInvalidDecl();
4321 
4322   return Anon;
4323 }
4324 
4325 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
4326 /// Microsoft C anonymous structure.
4327 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
4328 /// Example:
4329 ///
4330 /// struct A { int a; };
4331 /// struct B { struct A; int b; };
4332 ///
4333 /// void foo() {
4334 ///   B var;
4335 ///   var.a = 3;
4336 /// }
4337 ///
4338 Decl *Sema::BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS,
4339                                            RecordDecl *Record) {
4340   assert(Record && "expected a record!");
4341 
4342   // Mock up a declarator.
4343   Declarator Dc(DS, Declarator::TypeNameContext);
4344   TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
4345   assert(TInfo && "couldn't build declarator info for anonymous struct");
4346 
4347   auto *ParentDecl = cast<RecordDecl>(CurContext);
4348   QualType RecTy = Context.getTypeDeclType(Record);
4349 
4350   // Create a declaration for this anonymous struct.
4351   NamedDecl *Anon = FieldDecl::Create(Context,
4352                              ParentDecl,
4353                              DS.getLocStart(),
4354                              DS.getLocStart(),
4355                              /*IdentifierInfo=*/nullptr,
4356                              RecTy,
4357                              TInfo,
4358                              /*BitWidth=*/nullptr, /*Mutable=*/false,
4359                              /*InitStyle=*/ICIS_NoInit);
4360   Anon->setImplicit();
4361 
4362   // Add the anonymous struct object to the current context.
4363   CurContext->addDecl(Anon);
4364 
4365   // Inject the members of the anonymous struct into the current
4366   // context and into the identifier resolver chain for name lookup
4367   // purposes.
4368   SmallVector<NamedDecl*, 2> Chain;
4369   Chain.push_back(Anon);
4370 
4371   RecordDecl *RecordDef = Record->getDefinition();
4372   if (RequireCompleteType(Anon->getLocation(), RecTy,
4373                           diag::err_field_incomplete) ||
4374       InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
4375                                           AS_none, Chain, true)) {
4376     Anon->setInvalidDecl();
4377     ParentDecl->setInvalidDecl();
4378   }
4379 
4380   return Anon;
4381 }
4382 
4383 /// GetNameForDeclarator - Determine the full declaration name for the
4384 /// given Declarator.
4385 DeclarationNameInfo Sema::GetNameForDeclarator(Declarator &D) {
4386   return GetNameFromUnqualifiedId(D.getName());
4387 }
4388 
4389 /// \brief Retrieves the declaration name from a parsed unqualified-id.
4390 DeclarationNameInfo
4391 Sema::GetNameFromUnqualifiedId(const UnqualifiedId &Name) {
4392   DeclarationNameInfo NameInfo;
4393   NameInfo.setLoc(Name.StartLocation);
4394 
4395   switch (Name.getKind()) {
4396 
4397   case UnqualifiedId::IK_ImplicitSelfParam:
4398   case UnqualifiedId::IK_Identifier:
4399     NameInfo.setName(Name.Identifier);
4400     NameInfo.setLoc(Name.StartLocation);
4401     return NameInfo;
4402 
4403   case UnqualifiedId::IK_OperatorFunctionId:
4404     NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
4405                                            Name.OperatorFunctionId.Operator));
4406     NameInfo.setLoc(Name.StartLocation);
4407     NameInfo.getInfo().CXXOperatorName.BeginOpNameLoc
4408       = Name.OperatorFunctionId.SymbolLocations[0];
4409     NameInfo.getInfo().CXXOperatorName.EndOpNameLoc
4410       = Name.EndLocation.getRawEncoding();
4411     return NameInfo;
4412 
4413   case UnqualifiedId::IK_LiteralOperatorId:
4414     NameInfo.setName(Context.DeclarationNames.getCXXLiteralOperatorName(
4415                                                            Name.Identifier));
4416     NameInfo.setLoc(Name.StartLocation);
4417     NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
4418     return NameInfo;
4419 
4420   case UnqualifiedId::IK_ConversionFunctionId: {
4421     TypeSourceInfo *TInfo;
4422     QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
4423     if (Ty.isNull())
4424       return DeclarationNameInfo();
4425     NameInfo.setName(Context.DeclarationNames.getCXXConversionFunctionName(
4426                                                Context.getCanonicalType(Ty)));
4427     NameInfo.setLoc(Name.StartLocation);
4428     NameInfo.setNamedTypeInfo(TInfo);
4429     return NameInfo;
4430   }
4431 
4432   case UnqualifiedId::IK_ConstructorName: {
4433     TypeSourceInfo *TInfo;
4434     QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
4435     if (Ty.isNull())
4436       return DeclarationNameInfo();
4437     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4438                                               Context.getCanonicalType(Ty)));
4439     NameInfo.setLoc(Name.StartLocation);
4440     NameInfo.setNamedTypeInfo(TInfo);
4441     return NameInfo;
4442   }
4443 
4444   case UnqualifiedId::IK_ConstructorTemplateId: {
4445     // In well-formed code, we can only have a constructor
4446     // template-id that refers to the current context, so go there
4447     // to find the actual type being constructed.
4448     CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
4449     if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
4450       return DeclarationNameInfo();
4451 
4452     // Determine the type of the class being constructed.
4453     QualType CurClassType = Context.getTypeDeclType(CurClass);
4454 
4455     // FIXME: Check two things: that the template-id names the same type as
4456     // CurClassType, and that the template-id does not occur when the name
4457     // was qualified.
4458 
4459     NameInfo.setName(Context.DeclarationNames.getCXXConstructorName(
4460                                     Context.getCanonicalType(CurClassType)));
4461     NameInfo.setLoc(Name.StartLocation);
4462     // FIXME: should we retrieve TypeSourceInfo?
4463     NameInfo.setNamedTypeInfo(nullptr);
4464     return NameInfo;
4465   }
4466 
4467   case UnqualifiedId::IK_DestructorName: {
4468     TypeSourceInfo *TInfo;
4469     QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
4470     if (Ty.isNull())
4471       return DeclarationNameInfo();
4472     NameInfo.setName(Context.DeclarationNames.getCXXDestructorName(
4473                                               Context.getCanonicalType(Ty)));
4474     NameInfo.setLoc(Name.StartLocation);
4475     NameInfo.setNamedTypeInfo(TInfo);
4476     return NameInfo;
4477   }
4478 
4479   case UnqualifiedId::IK_TemplateId: {
4480     TemplateName TName = Name.TemplateId->Template.get();
4481     SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
4482     return Context.getNameForTemplate(TName, TNameLoc);
4483   }
4484 
4485   } // switch (Name.getKind())
4486 
4487   llvm_unreachable("Unknown name kind");
4488 }
4489 
4490 static QualType getCoreType(QualType Ty) {
4491   do {
4492     if (Ty->isPointerType() || Ty->isReferenceType())
4493       Ty = Ty->getPointeeType();
4494     else if (Ty->isArrayType())
4495       Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
4496     else
4497       return Ty.withoutLocalFastQualifiers();
4498   } while (true);
4499 }
4500 
4501 /// hasSimilarParameters - Determine whether the C++ functions Declaration
4502 /// and Definition have "nearly" matching parameters. This heuristic is
4503 /// used to improve diagnostics in the case where an out-of-line function
4504 /// definition doesn't match any declaration within the class or namespace.
4505 /// Also sets Params to the list of indices to the parameters that differ
4506 /// between the declaration and the definition. If hasSimilarParameters
4507 /// returns true and Params is empty, then all of the parameters match.
4508 static bool hasSimilarParameters(ASTContext &Context,
4509                                      FunctionDecl *Declaration,
4510                                      FunctionDecl *Definition,
4511                                      SmallVectorImpl<unsigned> &Params) {
4512   Params.clear();
4513   if (Declaration->param_size() != Definition->param_size())
4514     return false;
4515   for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
4516     QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
4517     QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
4518 
4519     // The parameter types are identical
4520     if (Context.hasSameType(DefParamTy, DeclParamTy))
4521       continue;
4522 
4523     QualType DeclParamBaseTy = getCoreType(DeclParamTy);
4524     QualType DefParamBaseTy = getCoreType(DefParamTy);
4525     const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
4526     const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
4527 
4528     if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
4529         (DeclTyName && DeclTyName == DefTyName))
4530       Params.push_back(Idx);
4531     else  // The two parameters aren't even close
4532       return false;
4533   }
4534 
4535   return true;
4536 }
4537 
4538 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
4539 /// declarator needs to be rebuilt in the current instantiation.
4540 /// Any bits of declarator which appear before the name are valid for
4541 /// consideration here.  That's specifically the type in the decl spec
4542 /// and the base type in any member-pointer chunks.
4543 static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D,
4544                                                     DeclarationName Name) {
4545   // The types we specifically need to rebuild are:
4546   //   - typenames, typeofs, and decltypes
4547   //   - types which will become injected class names
4548   // Of course, we also need to rebuild any type referencing such a
4549   // type.  It's safest to just say "dependent", but we call out a
4550   // few cases here.
4551 
4552   DeclSpec &DS = D.getMutableDeclSpec();
4553   switch (DS.getTypeSpecType()) {
4554   case DeclSpec::TST_typename:
4555   case DeclSpec::TST_typeofType:
4556   case DeclSpec::TST_underlyingType:
4557   case DeclSpec::TST_atomic: {
4558     // Grab the type from the parser.
4559     TypeSourceInfo *TSI = nullptr;
4560     QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
4561     if (T.isNull() || !T->isDependentType()) break;
4562 
4563     // Make sure there's a type source info.  This isn't really much
4564     // of a waste; most dependent types should have type source info
4565     // attached already.
4566     if (!TSI)
4567       TSI = S.Context.getTrivialTypeSourceInfo(T, DS.getTypeSpecTypeLoc());
4568 
4569     // Rebuild the type in the current instantiation.
4570     TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
4571     if (!TSI) return true;
4572 
4573     // Store the new type back in the decl spec.
4574     ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
4575     DS.UpdateTypeRep(LocType);
4576     break;
4577   }
4578 
4579   case DeclSpec::TST_decltype:
4580   case DeclSpec::TST_typeofExpr: {
4581     Expr *E = DS.getRepAsExpr();
4582     ExprResult Result = S.RebuildExprInCurrentInstantiation(E);
4583     if (Result.isInvalid()) return true;
4584     DS.UpdateExprRep(Result.get());
4585     break;
4586   }
4587 
4588   default:
4589     // Nothing to do for these decl specs.
4590     break;
4591   }
4592 
4593   // It doesn't matter what order we do this in.
4594   for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4595     DeclaratorChunk &Chunk = D.getTypeObject(I);
4596 
4597     // The only type information in the declarator which can come
4598     // before the declaration name is the base type of a member
4599     // pointer.
4600     if (Chunk.Kind != DeclaratorChunk::MemberPointer)
4601       continue;
4602 
4603     // Rebuild the scope specifier in-place.
4604     CXXScopeSpec &SS = Chunk.Mem.Scope();
4605     if (S.RebuildNestedNameSpecifierInCurrentInstantiation(SS))
4606       return true;
4607   }
4608 
4609   return false;
4610 }
4611 
4612 Decl *Sema::ActOnDeclarator(Scope *S, Declarator &D) {
4613   D.setFunctionDefinitionKind(FDK_Declaration);
4614   Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
4615 
4616   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
4617       Dcl && Dcl->getDeclContext()->isFileContext())
4618     Dcl->setTopLevelDeclInObjCContainer();
4619 
4620   return Dcl;
4621 }
4622 
4623 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
4624 ///   If T is the name of a class, then each of the following shall have a
4625 ///   name different from T:
4626 ///     - every static data member of class T;
4627 ///     - every member function of class T
4628 ///     - every member of class T that is itself a type;
4629 /// \returns true if the declaration name violates these rules.
4630 bool Sema::DiagnoseClassNameShadow(DeclContext *DC,
4631                                    DeclarationNameInfo NameInfo) {
4632   DeclarationName Name = NameInfo.getName();
4633 
4634   if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
4635     if (Record->getIdentifier() && Record->getDeclName() == Name) {
4636       Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
4637       return true;
4638     }
4639 
4640   return false;
4641 }
4642 
4643 /// \brief Diagnose a declaration whose declarator-id has the given
4644 /// nested-name-specifier.
4645 ///
4646 /// \param SS The nested-name-specifier of the declarator-id.
4647 ///
4648 /// \param DC The declaration context to which the nested-name-specifier
4649 /// resolves.
4650 ///
4651 /// \param Name The name of the entity being declared.
4652 ///
4653 /// \param Loc The location of the name of the entity being declared.
4654 ///
4655 /// \returns true if we cannot safely recover from this error, false otherwise.
4656 bool Sema::diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC,
4657                                         DeclarationName Name,
4658                                         SourceLocation Loc) {
4659   DeclContext *Cur = CurContext;
4660   while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
4661     Cur = Cur->getParent();
4662 
4663   // If the user provided a superfluous scope specifier that refers back to the
4664   // class in which the entity is already declared, diagnose and ignore it.
4665   //
4666   // class X {
4667   //   void X::f();
4668   // };
4669   //
4670   // Note, it was once ill-formed to give redundant qualification in all
4671   // contexts, but that rule was removed by DR482.
4672   if (Cur->Equals(DC)) {
4673     if (Cur->isRecord()) {
4674       Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
4675                                       : diag::err_member_extra_qualification)
4676         << Name << FixItHint::CreateRemoval(SS.getRange());
4677       SS.clear();
4678     } else {
4679       Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
4680     }
4681     return false;
4682   }
4683 
4684   // Check whether the qualifying scope encloses the scope of the original
4685   // declaration.
4686   if (!Cur->Encloses(DC)) {
4687     if (Cur->isRecord())
4688       Diag(Loc, diag::err_member_qualification)
4689         << Name << SS.getRange();
4690     else if (isa<TranslationUnitDecl>(DC))
4691       Diag(Loc, diag::err_invalid_declarator_global_scope)
4692         << Name << SS.getRange();
4693     else if (isa<FunctionDecl>(Cur))
4694       Diag(Loc, diag::err_invalid_declarator_in_function)
4695         << Name << SS.getRange();
4696     else if (isa<BlockDecl>(Cur))
4697       Diag(Loc, diag::err_invalid_declarator_in_block)
4698         << Name << SS.getRange();
4699     else
4700       Diag(Loc, diag::err_invalid_declarator_scope)
4701       << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
4702 
4703     return true;
4704   }
4705 
4706   if (Cur->isRecord()) {
4707     // Cannot qualify members within a class.
4708     Diag(Loc, diag::err_member_qualification)
4709       << Name << SS.getRange();
4710     SS.clear();
4711 
4712     // C++ constructors and destructors with incorrect scopes can break
4713     // our AST invariants by having the wrong underlying types. If
4714     // that's the case, then drop this declaration entirely.
4715     if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
4716          Name.getNameKind() == DeclarationName::CXXDestructorName) &&
4717         !Context.hasSameType(Name.getCXXNameType(),
4718                              Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
4719       return true;
4720 
4721     return false;
4722   }
4723 
4724   // C++11 [dcl.meaning]p1:
4725   //   [...] "The nested-name-specifier of the qualified declarator-id shall
4726   //   not begin with a decltype-specifer"
4727   NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
4728   while (SpecLoc.getPrefix())
4729     SpecLoc = SpecLoc.getPrefix();
4730   if (dyn_cast_or_null<DecltypeType>(
4731         SpecLoc.getNestedNameSpecifier()->getAsType()))
4732     Diag(Loc, diag::err_decltype_in_declarator)
4733       << SpecLoc.getTypeLoc().getSourceRange();
4734 
4735   return false;
4736 }
4737 
4738 NamedDecl *Sema::HandleDeclarator(Scope *S, Declarator &D,
4739                                   MultiTemplateParamsArg TemplateParamLists) {
4740   // TODO: consider using NameInfo for diagnostic.
4741   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
4742   DeclarationName Name = NameInfo.getName();
4743 
4744   // All of these full declarators require an identifier.  If it doesn't have
4745   // one, the ParsedFreeStandingDeclSpec action should be used.
4746   if (!Name) {
4747     if (!D.isInvalidType())  // Reject this if we think it is valid.
4748       Diag(D.getDeclSpec().getLocStart(),
4749            diag::err_declarator_need_ident)
4750         << D.getDeclSpec().getSourceRange() << D.getSourceRange();
4751     return nullptr;
4752   } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
4753     return nullptr;
4754 
4755   // The scope passed in may not be a decl scope.  Zip up the scope tree until
4756   // we find one that is.
4757   while ((S->getFlags() & Scope::DeclScope) == 0 ||
4758          (S->getFlags() & Scope::TemplateParamScope) != 0)
4759     S = S->getParent();
4760 
4761   DeclContext *DC = CurContext;
4762   if (D.getCXXScopeSpec().isInvalid())
4763     D.setInvalidType();
4764   else if (D.getCXXScopeSpec().isSet()) {
4765     if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
4766                                         UPPC_DeclarationQualifier))
4767       return nullptr;
4768 
4769     bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
4770     DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
4771     if (!DC || isa<EnumDecl>(DC)) {
4772       // If we could not compute the declaration context, it's because the
4773       // declaration context is dependent but does not refer to a class,
4774       // class template, or class template partial specialization. Complain
4775       // and return early, to avoid the coming semantic disaster.
4776       Diag(D.getIdentifierLoc(),
4777            diag::err_template_qualified_declarator_no_match)
4778         << D.getCXXScopeSpec().getScopeRep()
4779         << D.getCXXScopeSpec().getRange();
4780       return nullptr;
4781     }
4782     bool IsDependentContext = DC->isDependentContext();
4783 
4784     if (!IsDependentContext &&
4785         RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
4786       return nullptr;
4787 
4788     // If a class is incomplete, do not parse entities inside it.
4789     if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
4790       Diag(D.getIdentifierLoc(),
4791            diag::err_member_def_undefined_record)
4792         << Name << DC << D.getCXXScopeSpec().getRange();
4793       return nullptr;
4794     }
4795     if (!D.getDeclSpec().isFriendSpecified()) {
4796       if (diagnoseQualifiedDeclaration(D.getCXXScopeSpec(), DC,
4797                                       Name, D.getIdentifierLoc())) {
4798         if (DC->isRecord())
4799           return nullptr;
4800 
4801         D.setInvalidType();
4802       }
4803     }
4804 
4805     // Check whether we need to rebuild the type of the given
4806     // declaration in the current instantiation.
4807     if (EnteringContext && IsDependentContext &&
4808         TemplateParamLists.size() != 0) {
4809       ContextRAII SavedContext(*this, DC);
4810       if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
4811         D.setInvalidType();
4812     }
4813   }
4814 
4815   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4816   QualType R = TInfo->getType();
4817 
4818   if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
4819     // If this is a typedef, we'll end up spewing multiple diagnostics.
4820     // Just return early; it's safer. If this is a function, let the
4821     // "constructor cannot have a return type" diagnostic handle it.
4822     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4823       return nullptr;
4824 
4825   if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
4826                                       UPPC_DeclarationType))
4827     D.setInvalidType();
4828 
4829   LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
4830                         ForRedeclaration);
4831 
4832   // See if this is a redefinition of a variable in the same scope.
4833   if (!D.getCXXScopeSpec().isSet()) {
4834     bool IsLinkageLookup = false;
4835     bool CreateBuiltins = false;
4836 
4837     // If the declaration we're planning to build will be a function
4838     // or object with linkage, then look for another declaration with
4839     // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
4840     //
4841     // If the declaration we're planning to build will be declared with
4842     // external linkage in the translation unit, create any builtin with
4843     // the same name.
4844     if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
4845       /* Do nothing*/;
4846     else if (CurContext->isFunctionOrMethod() &&
4847              (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern ||
4848               R->isFunctionType())) {
4849       IsLinkageLookup = true;
4850       CreateBuiltins =
4851           CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
4852     } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
4853                D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static)
4854       CreateBuiltins = true;
4855 
4856     if (IsLinkageLookup)
4857       Previous.clear(LookupRedeclarationWithLinkage);
4858 
4859     LookupName(Previous, S, CreateBuiltins);
4860   } else { // Something like "int foo::x;"
4861     LookupQualifiedName(Previous, DC);
4862 
4863     // C++ [dcl.meaning]p1:
4864     //   When the declarator-id is qualified, the declaration shall refer to a
4865     //  previously declared member of the class or namespace to which the
4866     //  qualifier refers (or, in the case of a namespace, of an element of the
4867     //  inline namespace set of that namespace (7.3.1)) or to a specialization
4868     //  thereof; [...]
4869     //
4870     // Note that we already checked the context above, and that we do not have
4871     // enough information to make sure that Previous contains the declaration
4872     // we want to match. For example, given:
4873     //
4874     //   class X {
4875     //     void f();
4876     //     void f(float);
4877     //   };
4878     //
4879     //   void X::f(int) { } // ill-formed
4880     //
4881     // In this case, Previous will point to the overload set
4882     // containing the two f's declared in X, but neither of them
4883     // matches.
4884 
4885     // C++ [dcl.meaning]p1:
4886     //   [...] the member shall not merely have been introduced by a
4887     //   using-declaration in the scope of the class or namespace nominated by
4888     //   the nested-name-specifier of the declarator-id.
4889     RemoveUsingDecls(Previous);
4890   }
4891 
4892   if (Previous.isSingleResult() &&
4893       Previous.getFoundDecl()->isTemplateParameter()) {
4894     // Maybe we will complain about the shadowed template parameter.
4895     if (!D.isInvalidType())
4896       DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
4897                                       Previous.getFoundDecl());
4898 
4899     // Just pretend that we didn't see the previous declaration.
4900     Previous.clear();
4901   }
4902 
4903   // In C++, the previous declaration we find might be a tag type
4904   // (class or enum). In this case, the new declaration will hide the
4905   // tag type. Note that this does does not apply if we're declaring a
4906   // typedef (C++ [dcl.typedef]p4).
4907   if (Previous.isSingleTagDecl() &&
4908       D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
4909     Previous.clear();
4910 
4911   // Check that there are no default arguments other than in the parameters
4912   // of a function declaration (C++ only).
4913   if (getLangOpts().CPlusPlus)
4914     CheckExtraCXXDefaultArguments(D);
4915 
4916   if (D.getDeclSpec().isConceptSpecified()) {
4917     // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
4918     // applied only to the definition of a function template or variable
4919     // template, declared in namespace scope
4920     if (!TemplateParamLists.size()) {
4921       Diag(D.getDeclSpec().getConceptSpecLoc(),
4922            diag:: err_concept_wrong_decl_kind);
4923       return nullptr;
4924     }
4925 
4926     if (!DC->getRedeclContext()->isFileContext()) {
4927       Diag(D.getIdentifierLoc(),
4928            diag::err_concept_decls_may_only_appear_in_namespace_scope);
4929       return nullptr;
4930     }
4931   }
4932 
4933   NamedDecl *New;
4934 
4935   bool AddToScope = true;
4936   if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
4937     if (TemplateParamLists.size()) {
4938       Diag(D.getIdentifierLoc(), diag::err_template_typedef);
4939       return nullptr;
4940     }
4941 
4942     New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
4943   } else if (R->isFunctionType()) {
4944     New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
4945                                   TemplateParamLists,
4946                                   AddToScope);
4947   } else {
4948     New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
4949                                   AddToScope);
4950   }
4951 
4952   if (!New)
4953     return nullptr;
4954 
4955   // If this has an identifier and is not an invalid redeclaration or
4956   // function template specialization, add it to the scope stack.
4957   if (New->getDeclName() && AddToScope &&
4958        !(D.isRedeclaration() && New->isInvalidDecl())) {
4959     // Only make a locally-scoped extern declaration visible if it is the first
4960     // declaration of this entity. Qualified lookup for such an entity should
4961     // only find this declaration if there is no visible declaration of it.
4962     bool AddToContext = !D.isRedeclaration() || !New->isLocalExternDecl();
4963     PushOnScopeChains(New, S, AddToContext);
4964     if (!AddToContext)
4965       CurContext->addHiddenDecl(New);
4966   }
4967 
4968   return New;
4969 }
4970 
4971 /// Helper method to turn variable array types into constant array
4972 /// types in certain situations which would otherwise be errors (for
4973 /// GCC compatibility).
4974 static QualType TryToFixInvalidVariablyModifiedType(QualType T,
4975                                                     ASTContext &Context,
4976                                                     bool &SizeIsNegative,
4977                                                     llvm::APSInt &Oversized) {
4978   // This method tries to turn a variable array into a constant
4979   // array even when the size isn't an ICE.  This is necessary
4980   // for compatibility with code that depends on gcc's buggy
4981   // constant expression folding, like struct {char x[(int)(char*)2];}
4982   SizeIsNegative = false;
4983   Oversized = 0;
4984 
4985   if (T->isDependentType())
4986     return QualType();
4987 
4988   QualifierCollector Qs;
4989   const Type *Ty = Qs.strip(T);
4990 
4991   if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
4992     QualType Pointee = PTy->getPointeeType();
4993     QualType FixedType =
4994         TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
4995                                             Oversized);
4996     if (FixedType.isNull()) return FixedType;
4997     FixedType = Context.getPointerType(FixedType);
4998     return Qs.apply(Context, FixedType);
4999   }
5000   if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
5001     QualType Inner = PTy->getInnerType();
5002     QualType FixedType =
5003         TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
5004                                             Oversized);
5005     if (FixedType.isNull()) return FixedType;
5006     FixedType = Context.getParenType(FixedType);
5007     return Qs.apply(Context, FixedType);
5008   }
5009 
5010   const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
5011   if (!VLATy)
5012     return QualType();
5013   // FIXME: We should probably handle this case
5014   if (VLATy->getElementType()->isVariablyModifiedType())
5015     return QualType();
5016 
5017   llvm::APSInt Res;
5018   if (!VLATy->getSizeExpr() ||
5019       !VLATy->getSizeExpr()->EvaluateAsInt(Res, Context))
5020     return QualType();
5021 
5022   // Check whether the array size is negative.
5023   if (Res.isSigned() && Res.isNegative()) {
5024     SizeIsNegative = true;
5025     return QualType();
5026   }
5027 
5028   // Check whether the array is too large to be addressed.
5029   unsigned ActiveSizeBits
5030     = ConstantArrayType::getNumAddressingBits(Context, VLATy->getElementType(),
5031                                               Res);
5032   if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
5033     Oversized = Res;
5034     return QualType();
5035   }
5036 
5037   return Context.getConstantArrayType(VLATy->getElementType(),
5038                                       Res, ArrayType::Normal, 0);
5039 }
5040 
5041 static void
5042 FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL) {
5043   SrcTL = SrcTL.getUnqualifiedLoc();
5044   DstTL = DstTL.getUnqualifiedLoc();
5045   if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
5046     PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
5047     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
5048                                       DstPTL.getPointeeLoc());
5049     DstPTL.setStarLoc(SrcPTL.getStarLoc());
5050     return;
5051   }
5052   if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
5053     ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
5054     FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
5055                                       DstPTL.getInnerLoc());
5056     DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
5057     DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
5058     return;
5059   }
5060   ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
5061   ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
5062   TypeLoc SrcElemTL = SrcATL.getElementLoc();
5063   TypeLoc DstElemTL = DstATL.getElementLoc();
5064   DstElemTL.initializeFullCopy(SrcElemTL);
5065   DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
5066   DstATL.setSizeExpr(SrcATL.getSizeExpr());
5067   DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
5068 }
5069 
5070 /// Helper method to turn variable array types into constant array
5071 /// types in certain situations which would otherwise be errors (for
5072 /// GCC compatibility).
5073 static TypeSourceInfo*
5074 TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo,
5075                                               ASTContext &Context,
5076                                               bool &SizeIsNegative,
5077                                               llvm::APSInt &Oversized) {
5078   QualType FixedTy
5079     = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
5080                                           SizeIsNegative, Oversized);
5081   if (FixedTy.isNull())
5082     return nullptr;
5083   TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
5084   FixInvalidVariablyModifiedTypeLoc(TInfo->getTypeLoc(),
5085                                     FixedTInfo->getTypeLoc());
5086   return FixedTInfo;
5087 }
5088 
5089 /// \brief Register the given locally-scoped extern "C" declaration so
5090 /// that it can be found later for redeclarations. We include any extern "C"
5091 /// declaration that is not visible in the translation unit here, not just
5092 /// function-scope declarations.
5093 void
5094 Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S) {
5095   if (!getLangOpts().CPlusPlus &&
5096       ND->getLexicalDeclContext()->getRedeclContext()->isTranslationUnit())
5097     // Don't need to track declarations in the TU in C.
5098     return;
5099 
5100   // Note that we have a locally-scoped external with this name.
5101   Context.getExternCContextDecl()->makeDeclVisibleInContext(ND);
5102 }
5103 
5104 NamedDecl *Sema::findLocallyScopedExternCDecl(DeclarationName Name) {
5105   // FIXME: We can have multiple results via __attribute__((overloadable)).
5106   auto Result = Context.getExternCContextDecl()->lookup(Name);
5107   return Result.empty() ? nullptr : *Result.begin();
5108 }
5109 
5110 /// \brief Diagnose function specifiers on a declaration of an identifier that
5111 /// does not identify a function.
5112 void Sema::DiagnoseFunctionSpecifiers(const DeclSpec &DS) {
5113   // FIXME: We should probably indicate the identifier in question to avoid
5114   // confusion for constructs like "inline int a(), b;"
5115   if (DS.isInlineSpecified())
5116     Diag(DS.getInlineSpecLoc(),
5117          diag::err_inline_non_function);
5118 
5119   if (DS.isVirtualSpecified())
5120     Diag(DS.getVirtualSpecLoc(),
5121          diag::err_virtual_non_function);
5122 
5123   if (DS.isExplicitSpecified())
5124     Diag(DS.getExplicitSpecLoc(),
5125          diag::err_explicit_non_function);
5126 
5127   if (DS.isNoreturnSpecified())
5128     Diag(DS.getNoreturnSpecLoc(),
5129          diag::err_noreturn_non_function);
5130 }
5131 
5132 NamedDecl*
5133 Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
5134                              TypeSourceInfo *TInfo, LookupResult &Previous) {
5135   // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
5136   if (D.getCXXScopeSpec().isSet()) {
5137     Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
5138       << D.getCXXScopeSpec().getRange();
5139     D.setInvalidType();
5140     // Pretend we didn't see the scope specifier.
5141     DC = CurContext;
5142     Previous.clear();
5143   }
5144 
5145   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5146 
5147   if (D.getDeclSpec().isConstexprSpecified())
5148     Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
5149       << 1;
5150   if (D.getDeclSpec().isConceptSpecified())
5151     Diag(D.getDeclSpec().getConceptSpecLoc(),
5152          diag::err_concept_wrong_decl_kind);
5153 
5154   if (D.getName().Kind != UnqualifiedId::IK_Identifier) {
5155     Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
5156       << D.getName().getSourceRange();
5157     return nullptr;
5158   }
5159 
5160   TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
5161   if (!NewTD) return nullptr;
5162 
5163   // Handle attributes prior to checking for duplicates in MergeVarDecl
5164   ProcessDeclAttributes(S, NewTD, D);
5165 
5166   CheckTypedefForVariablyModifiedType(S, NewTD);
5167 
5168   bool Redeclaration = D.isRedeclaration();
5169   NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
5170   D.setRedeclaration(Redeclaration);
5171   return ND;
5172 }
5173 
5174 void
5175 Sema::CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *NewTD) {
5176   // C99 6.7.7p2: If a typedef name specifies a variably modified type
5177   // then it shall have block scope.
5178   // Note that variably modified types must be fixed before merging the decl so
5179   // that redeclarations will match.
5180   TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
5181   QualType T = TInfo->getType();
5182   if (T->isVariablyModifiedType()) {
5183     getCurFunction()->setHasBranchProtectedScope();
5184 
5185     if (S->getFnParent() == nullptr) {
5186       bool SizeIsNegative;
5187       llvm::APSInt Oversized;
5188       TypeSourceInfo *FixedTInfo =
5189         TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
5190                                                       SizeIsNegative,
5191                                                       Oversized);
5192       if (FixedTInfo) {
5193         Diag(NewTD->getLocation(), diag::warn_illegal_constant_array_size);
5194         NewTD->setTypeSourceInfo(FixedTInfo);
5195       } else {
5196         if (SizeIsNegative)
5197           Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
5198         else if (T->isVariableArrayType())
5199           Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
5200         else if (Oversized.getBoolValue())
5201           Diag(NewTD->getLocation(), diag::err_array_too_large)
5202             << Oversized.toString(10);
5203         else
5204           Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
5205         NewTD->setInvalidDecl();
5206       }
5207     }
5208   }
5209 }
5210 
5211 
5212 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
5213 /// declares a typedef-name, either using the 'typedef' type specifier or via
5214 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
5215 NamedDecl*
5216 Sema::ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *NewTD,
5217                            LookupResult &Previous, bool &Redeclaration) {
5218   // Merge the decl with the existing one if appropriate. If the decl is
5219   // in an outer scope, it isn't the same thing.
5220   FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
5221                        /*AllowInlineNamespace*/false);
5222   filterNonConflictingPreviousTypedefDecls(*this, NewTD, Previous);
5223   if (!Previous.empty()) {
5224     Redeclaration = true;
5225     MergeTypedefNameDecl(S, NewTD, Previous);
5226   }
5227 
5228   // If this is the C FILE type, notify the AST context.
5229   if (IdentifierInfo *II = NewTD->getIdentifier())
5230     if (!NewTD->isInvalidDecl() &&
5231         NewTD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
5232       if (II->isStr("FILE"))
5233         Context.setFILEDecl(NewTD);
5234       else if (II->isStr("jmp_buf"))
5235         Context.setjmp_bufDecl(NewTD);
5236       else if (II->isStr("sigjmp_buf"))
5237         Context.setsigjmp_bufDecl(NewTD);
5238       else if (II->isStr("ucontext_t"))
5239         Context.setucontext_tDecl(NewTD);
5240     }
5241 
5242   return NewTD;
5243 }
5244 
5245 /// \brief Determines whether the given declaration is an out-of-scope
5246 /// previous declaration.
5247 ///
5248 /// This routine should be invoked when name lookup has found a
5249 /// previous declaration (PrevDecl) that is not in the scope where a
5250 /// new declaration by the same name is being introduced. If the new
5251 /// declaration occurs in a local scope, previous declarations with
5252 /// linkage may still be considered previous declarations (C99
5253 /// 6.2.2p4-5, C++ [basic.link]p6).
5254 ///
5255 /// \param PrevDecl the previous declaration found by name
5256 /// lookup
5257 ///
5258 /// \param DC the context in which the new declaration is being
5259 /// declared.
5260 ///
5261 /// \returns true if PrevDecl is an out-of-scope previous declaration
5262 /// for a new delcaration with the same name.
5263 static bool
5264 isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
5265                                 ASTContext &Context) {
5266   if (!PrevDecl)
5267     return false;
5268 
5269   if (!PrevDecl->hasLinkage())
5270     return false;
5271 
5272   if (Context.getLangOpts().CPlusPlus) {
5273     // C++ [basic.link]p6:
5274     //   If there is a visible declaration of an entity with linkage
5275     //   having the same name and type, ignoring entities declared
5276     //   outside the innermost enclosing namespace scope, the block
5277     //   scope declaration declares that same entity and receives the
5278     //   linkage of the previous declaration.
5279     DeclContext *OuterContext = DC->getRedeclContext();
5280     if (!OuterContext->isFunctionOrMethod())
5281       // This rule only applies to block-scope declarations.
5282       return false;
5283 
5284     DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
5285     if (PrevOuterContext->isRecord())
5286       // We found a member function: ignore it.
5287       return false;
5288 
5289     // Find the innermost enclosing namespace for the new and
5290     // previous declarations.
5291     OuterContext = OuterContext->getEnclosingNamespaceContext();
5292     PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
5293 
5294     // The previous declaration is in a different namespace, so it
5295     // isn't the same function.
5296     if (!OuterContext->Equals(PrevOuterContext))
5297       return false;
5298   }
5299 
5300   return true;
5301 }
5302 
5303 static void SetNestedNameSpecifier(DeclaratorDecl *DD, Declarator &D) {
5304   CXXScopeSpec &SS = D.getCXXScopeSpec();
5305   if (!SS.isSet()) return;
5306   DD->setQualifierInfo(SS.getWithLocInContext(DD->getASTContext()));
5307 }
5308 
5309 bool Sema::inferObjCARCLifetime(ValueDecl *decl) {
5310   QualType type = decl->getType();
5311   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
5312   if (lifetime == Qualifiers::OCL_Autoreleasing) {
5313     // Various kinds of declaration aren't allowed to be __autoreleasing.
5314     unsigned kind = -1U;
5315     if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5316       if (var->hasAttr<BlocksAttr>())
5317         kind = 0; // __block
5318       else if (!var->hasLocalStorage())
5319         kind = 1; // global
5320     } else if (isa<ObjCIvarDecl>(decl)) {
5321       kind = 3; // ivar
5322     } else if (isa<FieldDecl>(decl)) {
5323       kind = 2; // field
5324     }
5325 
5326     if (kind != -1U) {
5327       Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
5328         << kind;
5329     }
5330   } else if (lifetime == Qualifiers::OCL_None) {
5331     // Try to infer lifetime.
5332     if (!type->isObjCLifetimeType())
5333       return false;
5334 
5335     lifetime = type->getObjCARCImplicitLifetime();
5336     type = Context.getLifetimeQualifiedType(type, lifetime);
5337     decl->setType(type);
5338   }
5339 
5340   if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
5341     // Thread-local variables cannot have lifetime.
5342     if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
5343         var->getTLSKind()) {
5344       Diag(var->getLocation(), diag::err_arc_thread_ownership)
5345         << var->getType();
5346       return true;
5347     }
5348   }
5349 
5350   return false;
5351 }
5352 
5353 static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND) {
5354   // Ensure that an auto decl is deduced otherwise the checks below might cache
5355   // the wrong linkage.
5356   assert(S.ParsingInitForAutoVars.count(&ND) == 0);
5357 
5358   // 'weak' only applies to declarations with external linkage.
5359   if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
5360     if (!ND.isExternallyVisible()) {
5361       S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
5362       ND.dropAttr<WeakAttr>();
5363     }
5364   }
5365   if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
5366     if (ND.isExternallyVisible()) {
5367       S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
5368       ND.dropAttr<WeakRefAttr>();
5369       ND.dropAttr<AliasAttr>();
5370     }
5371   }
5372 
5373   if (auto *VD = dyn_cast<VarDecl>(&ND)) {
5374     if (VD->hasInit()) {
5375       if (const auto *Attr = VD->getAttr<AliasAttr>()) {
5376         assert(VD->isThisDeclarationADefinition() &&
5377                !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
5378         S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD;
5379         VD->dropAttr<AliasAttr>();
5380       }
5381     }
5382   }
5383 
5384   // 'selectany' only applies to externally visible variable declarations.
5385   // It does not apply to functions.
5386   if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
5387     if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
5388       S.Diag(Attr->getLocation(),
5389              diag::err_attribute_selectany_non_extern_data);
5390       ND.dropAttr<SelectAnyAttr>();
5391     }
5392   }
5393 
5394   if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
5395     // dll attributes require external linkage. Static locals may have external
5396     // linkage but still cannot be explicitly imported or exported.
5397     auto *VD = dyn_cast<VarDecl>(&ND);
5398     if (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())) {
5399       S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
5400         << &ND << Attr;
5401       ND.setInvalidDecl();
5402     }
5403   }
5404 
5405   // Virtual functions cannot be marked as 'notail'.
5406   if (auto *Attr = ND.getAttr<NotTailCalledAttr>())
5407     if (auto *MD = dyn_cast<CXXMethodDecl>(&ND))
5408       if (MD->isVirtual()) {
5409         S.Diag(ND.getLocation(),
5410                diag::err_invalid_attribute_on_virtual_function)
5411             << Attr;
5412         ND.dropAttr<NotTailCalledAttr>();
5413       }
5414 }
5415 
5416 static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl,
5417                                            NamedDecl *NewDecl,
5418                                            bool IsSpecialization) {
5419   if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl))
5420     OldDecl = OldTD->getTemplatedDecl();
5421   if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl))
5422     NewDecl = NewTD->getTemplatedDecl();
5423 
5424   if (!OldDecl || !NewDecl)
5425     return;
5426 
5427   const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
5428   const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
5429   const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
5430   const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
5431 
5432   // dllimport and dllexport are inheritable attributes so we have to exclude
5433   // inherited attribute instances.
5434   bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
5435                     (NewExportAttr && !NewExportAttr->isInherited());
5436 
5437   // A redeclaration is not allowed to add a dllimport or dllexport attribute,
5438   // the only exception being explicit specializations.
5439   // Implicitly generated declarations are also excluded for now because there
5440   // is no other way to switch these to use dllimport or dllexport.
5441   bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
5442 
5443   if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
5444     // Allow with a warning for free functions and global variables.
5445     bool JustWarn = false;
5446     if (!OldDecl->isCXXClassMember()) {
5447       auto *VD = dyn_cast<VarDecl>(OldDecl);
5448       if (VD && !VD->getDescribedVarTemplate())
5449         JustWarn = true;
5450       auto *FD = dyn_cast<FunctionDecl>(OldDecl);
5451       if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
5452         JustWarn = true;
5453     }
5454 
5455     // We cannot change a declaration that's been used because IR has already
5456     // been emitted. Dllimported functions will still work though (modulo
5457     // address equality) as they can use the thunk.
5458     if (OldDecl->isUsed())
5459       if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
5460         JustWarn = false;
5461 
5462     unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
5463                                : diag::err_attribute_dll_redeclaration;
5464     S.Diag(NewDecl->getLocation(), DiagID)
5465         << NewDecl
5466         << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
5467     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5468     if (!JustWarn) {
5469       NewDecl->setInvalidDecl();
5470       return;
5471     }
5472   }
5473 
5474   // A redeclaration is not allowed to drop a dllimport attribute, the only
5475   // exceptions being inline function definitions, local extern declarations,
5476   // and qualified friend declarations.
5477   // NB: MSVC converts such a declaration to dllexport.
5478   bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
5479   if (const auto *VD = dyn_cast<VarDecl>(NewDecl))
5480     // Ignore static data because out-of-line definitions are diagnosed
5481     // separately.
5482     IsStaticDataMember = VD->isStaticDataMember();
5483   else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
5484     IsInline = FD->isInlined();
5485     IsQualifiedFriend = FD->getQualifier() &&
5486                         FD->getFriendObjectKind() == Decl::FOK_Declared;
5487   }
5488 
5489   if (OldImportAttr && !HasNewAttr && !IsInline && !IsStaticDataMember &&
5490       !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
5491     S.Diag(NewDecl->getLocation(),
5492            diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
5493       << NewDecl << OldImportAttr;
5494     S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
5495     S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
5496     OldDecl->dropAttr<DLLImportAttr>();
5497     NewDecl->dropAttr<DLLImportAttr>();
5498   } else if (IsInline && OldImportAttr &&
5499              !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5500     // In MinGW, seeing a function declared inline drops the dllimport attribute.
5501     OldDecl->dropAttr<DLLImportAttr>();
5502     NewDecl->dropAttr<DLLImportAttr>();
5503     S.Diag(NewDecl->getLocation(),
5504            diag::warn_dllimport_dropped_from_inline_function)
5505         << NewDecl << OldImportAttr;
5506   }
5507 }
5508 
5509 /// Given that we are within the definition of the given function,
5510 /// will that definition behave like C99's 'inline', where the
5511 /// definition is discarded except for optimization purposes?
5512 static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD) {
5513   // Try to avoid calling GetGVALinkageForFunction.
5514 
5515   // All cases of this require the 'inline' keyword.
5516   if (!FD->isInlined()) return false;
5517 
5518   // This is only possible in C++ with the gnu_inline attribute.
5519   if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
5520     return false;
5521 
5522   // Okay, go ahead and call the relatively-more-expensive function.
5523 
5524 #ifndef NDEBUG
5525   // AST quite reasonably asserts that it's working on a function
5526   // definition.  We don't really have a way to tell it that we're
5527   // currently defining the function, so just lie to it in +Asserts
5528   // builds.  This is an awful hack.
5529   FD->setLazyBody(1);
5530 #endif
5531 
5532   bool isC99Inline =
5533       S.Context.GetGVALinkageForFunction(FD) == GVA_AvailableExternally;
5534 
5535 #ifndef NDEBUG
5536   FD->setLazyBody(0);
5537 #endif
5538 
5539   return isC99Inline;
5540 }
5541 
5542 /// Determine whether a variable is extern "C" prior to attaching
5543 /// an initializer. We can't just call isExternC() here, because that
5544 /// will also compute and cache whether the declaration is externally
5545 /// visible, which might change when we attach the initializer.
5546 ///
5547 /// This can only be used if the declaration is known to not be a
5548 /// redeclaration of an internal linkage declaration.
5549 ///
5550 /// For instance:
5551 ///
5552 ///   auto x = []{};
5553 ///
5554 /// Attaching the initializer here makes this declaration not externally
5555 /// visible, because its type has internal linkage.
5556 ///
5557 /// FIXME: This is a hack.
5558 template<typename T>
5559 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
5560   if (S.getLangOpts().CPlusPlus) {
5561     // In C++, the overloadable attribute negates the effects of extern "C".
5562     if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
5563       return false;
5564 
5565     // So do CUDA's host/device attributes if overloading is enabled.
5566     if (S.getLangOpts().CUDA && S.getLangOpts().CUDATargetOverloads &&
5567         (D->template hasAttr<CUDADeviceAttr>() ||
5568          D->template hasAttr<CUDAHostAttr>()))
5569       return false;
5570   }
5571   return D->isExternC();
5572 }
5573 
5574 static bool shouldConsiderLinkage(const VarDecl *VD) {
5575   const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
5576   if (DC->isFunctionOrMethod())
5577     return VD->hasExternalStorage();
5578   if (DC->isFileContext())
5579     return true;
5580   if (DC->isRecord())
5581     return false;
5582   llvm_unreachable("Unexpected context");
5583 }
5584 
5585 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
5586   const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
5587   if (DC->isFileContext() || DC->isFunctionOrMethod())
5588     return true;
5589   if (DC->isRecord())
5590     return false;
5591   llvm_unreachable("Unexpected context");
5592 }
5593 
5594 static bool hasParsedAttr(Scope *S, const AttributeList *AttrList,
5595                           AttributeList::Kind Kind) {
5596   for (const AttributeList *L = AttrList; L; L = L->getNext())
5597     if (L->getKind() == Kind)
5598       return true;
5599   return false;
5600 }
5601 
5602 static bool hasParsedAttr(Scope *S, const Declarator &PD,
5603                           AttributeList::Kind Kind) {
5604   // Check decl attributes on the DeclSpec.
5605   if (hasParsedAttr(S, PD.getDeclSpec().getAttributes().getList(), Kind))
5606     return true;
5607 
5608   // Walk the declarator structure, checking decl attributes that were in a type
5609   // position to the decl itself.
5610   for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
5611     if (hasParsedAttr(S, PD.getTypeObject(I).getAttrs(), Kind))
5612       return true;
5613   }
5614 
5615   // Finally, check attributes on the decl itself.
5616   return hasParsedAttr(S, PD.getAttributes(), Kind);
5617 }
5618 
5619 /// Adjust the \c DeclContext for a function or variable that might be a
5620 /// function-local external declaration.
5621 bool Sema::adjustContextForLocalExternDecl(DeclContext *&DC) {
5622   if (!DC->isFunctionOrMethod())
5623     return false;
5624 
5625   // If this is a local extern function or variable declared within a function
5626   // template, don't add it into the enclosing namespace scope until it is
5627   // instantiated; it might have a dependent type right now.
5628   if (DC->isDependentContext())
5629     return true;
5630 
5631   // C++11 [basic.link]p7:
5632   //   When a block scope declaration of an entity with linkage is not found to
5633   //   refer to some other declaration, then that entity is a member of the
5634   //   innermost enclosing namespace.
5635   //
5636   // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
5637   // semantically-enclosing namespace, not a lexically-enclosing one.
5638   while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
5639     DC = DC->getParent();
5640   return true;
5641 }
5642 
5643 /// \brief Returns true if given declaration has external C language linkage.
5644 static bool isDeclExternC(const Decl *D) {
5645   if (const auto *FD = dyn_cast<FunctionDecl>(D))
5646     return FD->isExternC();
5647   if (const auto *VD = dyn_cast<VarDecl>(D))
5648     return VD->isExternC();
5649 
5650   llvm_unreachable("Unknown type of decl!");
5651 }
5652 
5653 NamedDecl *
5654 Sema::ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC,
5655                               TypeSourceInfo *TInfo, LookupResult &Previous,
5656                               MultiTemplateParamsArg TemplateParamLists,
5657                               bool &AddToScope) {
5658   QualType R = TInfo->getType();
5659   DeclarationName Name = GetNameForDeclarator(D).getName();
5660 
5661   DeclSpec::SCS SCSpec = D.getDeclSpec().getStorageClassSpec();
5662   StorageClass SC = StorageClassSpecToVarDeclStorageClass(D.getDeclSpec());
5663 
5664   // dllimport globals without explicit storage class are treated as extern. We
5665   // have to change the storage class this early to get the right DeclContext.
5666   if (SC == SC_None && !DC->isRecord() &&
5667       hasParsedAttr(S, D, AttributeList::AT_DLLImport) &&
5668       !hasParsedAttr(S, D, AttributeList::AT_DLLExport))
5669     SC = SC_Extern;
5670 
5671   DeclContext *OriginalDC = DC;
5672   bool IsLocalExternDecl = SC == SC_Extern &&
5673                            adjustContextForLocalExternDecl(DC);
5674 
5675   if (getLangOpts().OpenCL) {
5676     // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
5677     QualType NR = R;
5678     while (NR->isPointerType()) {
5679       if (NR->isFunctionPointerType()) {
5680         Diag(D.getIdentifierLoc(), diag::err_opencl_function_pointer_variable);
5681         D.setInvalidType();
5682         break;
5683       }
5684       NR = NR->getPointeeType();
5685     }
5686 
5687     if (!getOpenCLOptions().cl_khr_fp16) {
5688       // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
5689       // half array type (unless the cl_khr_fp16 extension is enabled).
5690       if (Context.getBaseElementType(R)->isHalfType()) {
5691         Diag(D.getIdentifierLoc(), diag::err_opencl_half_declaration) << R;
5692         D.setInvalidType();
5693       }
5694     }
5695   }
5696 
5697   if (SCSpec == DeclSpec::SCS_mutable) {
5698     // mutable can only appear on non-static class members, so it's always
5699     // an error here
5700     Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
5701     D.setInvalidType();
5702     SC = SC_None;
5703   }
5704 
5705   if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
5706       !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
5707                               D.getDeclSpec().getStorageClassSpecLoc())) {
5708     // In C++11, the 'register' storage class specifier is deprecated.
5709     // Suppress the warning in system macros, it's used in macros in some
5710     // popular C system headers, such as in glibc's htonl() macro.
5711     Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5712          getLangOpts().CPlusPlus1z ? diag::ext_register_storage_class
5713                                    : diag::warn_deprecated_register)
5714       << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5715   }
5716 
5717   IdentifierInfo *II = Name.getAsIdentifierInfo();
5718   if (!II) {
5719     Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
5720       << Name;
5721     return nullptr;
5722   }
5723 
5724   DiagnoseFunctionSpecifiers(D.getDeclSpec());
5725 
5726   if (!DC->isRecord() && S->getFnParent() == nullptr) {
5727     // C99 6.9p2: The storage-class specifiers auto and register shall not
5728     // appear in the declaration specifiers in an external declaration.
5729     // Global Register+Asm is a GNU extension we support.
5730     if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
5731       Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
5732       D.setInvalidType();
5733     }
5734   }
5735 
5736   if (getLangOpts().OpenCL) {
5737     // OpenCL v1.2 s6.9.b p4:
5738     // The sampler type cannot be used with the __local and __global address
5739     // space qualifiers.
5740     if (R->isSamplerT() && (R.getAddressSpace() == LangAS::opencl_local ||
5741       R.getAddressSpace() == LangAS::opencl_global)) {
5742       Diag(D.getIdentifierLoc(), diag::err_wrong_sampler_addressspace);
5743     }
5744 
5745     // OpenCL 1.2 spec, p6.9 r:
5746     // The event type cannot be used to declare a program scope variable.
5747     // The event type cannot be used with the __local, __constant and __global
5748     // address space qualifiers.
5749     if (R->isEventT()) {
5750       if (S->getParent() == nullptr) {
5751         Diag(D.getLocStart(), diag::err_event_t_global_var);
5752         D.setInvalidType();
5753       }
5754 
5755       if (R.getAddressSpace()) {
5756         Diag(D.getLocStart(), diag::err_event_t_addr_space_qual);
5757         D.setInvalidType();
5758       }
5759     }
5760   }
5761 
5762   bool IsExplicitSpecialization = false;
5763   bool IsVariableTemplateSpecialization = false;
5764   bool IsPartialSpecialization = false;
5765   bool IsVariableTemplate = false;
5766   VarDecl *NewVD = nullptr;
5767   VarTemplateDecl *NewTemplate = nullptr;
5768   TemplateParameterList *TemplateParams = nullptr;
5769   if (!getLangOpts().CPlusPlus) {
5770     NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5771                             D.getIdentifierLoc(), II,
5772                             R, TInfo, SC);
5773 
5774     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5775       ParsingInitForAutoVars.insert(NewVD);
5776 
5777     if (D.isInvalidType())
5778       NewVD->setInvalidDecl();
5779   } else {
5780     bool Invalid = false;
5781 
5782     if (DC->isRecord() && !CurContext->isRecord()) {
5783       // This is an out-of-line definition of a static data member.
5784       switch (SC) {
5785       case SC_None:
5786         break;
5787       case SC_Static:
5788         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5789              diag::err_static_out_of_line)
5790           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5791         break;
5792       case SC_Auto:
5793       case SC_Register:
5794       case SC_Extern:
5795         // [dcl.stc] p2: The auto or register specifiers shall be applied only
5796         // to names of variables declared in a block or to function parameters.
5797         // [dcl.stc] p6: The extern specifier cannot be used in the declaration
5798         // of class members
5799 
5800         Diag(D.getDeclSpec().getStorageClassSpecLoc(),
5801              diag::err_storage_class_for_static_member)
5802           << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
5803         break;
5804       case SC_PrivateExtern:
5805         llvm_unreachable("C storage class in c++!");
5806       }
5807     }
5808 
5809     if (SC == SC_Static && CurContext->isRecord()) {
5810       if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
5811         if (RD->isLocalClass())
5812           Diag(D.getIdentifierLoc(),
5813                diag::err_static_data_member_not_allowed_in_local_class)
5814             << Name << RD->getDeclName();
5815 
5816         // C++98 [class.union]p1: If a union contains a static data member,
5817         // the program is ill-formed. C++11 drops this restriction.
5818         if (RD->isUnion())
5819           Diag(D.getIdentifierLoc(),
5820                getLangOpts().CPlusPlus11
5821                  ? diag::warn_cxx98_compat_static_data_member_in_union
5822                  : diag::ext_static_data_member_in_union) << Name;
5823         // We conservatively disallow static data members in anonymous structs.
5824         else if (!RD->getDeclName())
5825           Diag(D.getIdentifierLoc(),
5826                diag::err_static_data_member_not_allowed_in_anon_struct)
5827             << Name << RD->isUnion();
5828       }
5829     }
5830 
5831     // Match up the template parameter lists with the scope specifier, then
5832     // determine whether we have a template or a template specialization.
5833     TemplateParams = MatchTemplateParametersToScopeSpecifier(
5834         D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
5835         D.getCXXScopeSpec(),
5836         D.getName().getKind() == UnqualifiedId::IK_TemplateId
5837             ? D.getName().TemplateId
5838             : nullptr,
5839         TemplateParamLists,
5840         /*never a friend*/ false, IsExplicitSpecialization, Invalid);
5841 
5842     if (TemplateParams) {
5843       if (!TemplateParams->size() &&
5844           D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
5845         // There is an extraneous 'template<>' for this variable. Complain
5846         // about it, but allow the declaration of the variable.
5847         Diag(TemplateParams->getTemplateLoc(),
5848              diag::err_template_variable_noparams)
5849           << II
5850           << SourceRange(TemplateParams->getTemplateLoc(),
5851                          TemplateParams->getRAngleLoc());
5852         TemplateParams = nullptr;
5853       } else {
5854         if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
5855           // This is an explicit specialization or a partial specialization.
5856           // FIXME: Check that we can declare a specialization here.
5857           IsVariableTemplateSpecialization = true;
5858           IsPartialSpecialization = TemplateParams->size() > 0;
5859         } else { // if (TemplateParams->size() > 0)
5860           // This is a template declaration.
5861           IsVariableTemplate = true;
5862 
5863           // Check that we can declare a template here.
5864           if (CheckTemplateDeclScope(S, TemplateParams))
5865             return nullptr;
5866 
5867           // Only C++1y supports variable templates (N3651).
5868           Diag(D.getIdentifierLoc(),
5869                getLangOpts().CPlusPlus14
5870                    ? diag::warn_cxx11_compat_variable_template
5871                    : diag::ext_variable_template);
5872         }
5873       }
5874     } else {
5875       assert(
5876           (Invalid || D.getName().getKind() != UnqualifiedId::IK_TemplateId) &&
5877           "should have a 'template<>' for this decl");
5878     }
5879 
5880     if (IsVariableTemplateSpecialization) {
5881       SourceLocation TemplateKWLoc =
5882           TemplateParamLists.size() > 0
5883               ? TemplateParamLists[0]->getTemplateLoc()
5884               : SourceLocation();
5885       DeclResult Res = ActOnVarTemplateSpecialization(
5886           S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
5887           IsPartialSpecialization);
5888       if (Res.isInvalid())
5889         return nullptr;
5890       NewVD = cast<VarDecl>(Res.get());
5891       AddToScope = false;
5892     } else
5893       NewVD = VarDecl::Create(Context, DC, D.getLocStart(),
5894                               D.getIdentifierLoc(), II, R, TInfo, SC);
5895 
5896     // If this is supposed to be a variable template, create it as such.
5897     if (IsVariableTemplate) {
5898       NewTemplate =
5899           VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
5900                                   TemplateParams, NewVD);
5901       NewVD->setDescribedVarTemplate(NewTemplate);
5902     }
5903 
5904     // If this decl has an auto type in need of deduction, make a note of the
5905     // Decl so we can diagnose uses of it in its own initializer.
5906     if (D.getDeclSpec().containsPlaceholderType() && R->getContainedAutoType())
5907       ParsingInitForAutoVars.insert(NewVD);
5908 
5909     if (D.isInvalidType() || Invalid) {
5910       NewVD->setInvalidDecl();
5911       if (NewTemplate)
5912         NewTemplate->setInvalidDecl();
5913     }
5914 
5915     SetNestedNameSpecifier(NewVD, D);
5916 
5917     // If we have any template parameter lists that don't directly belong to
5918     // the variable (matching the scope specifier), store them.
5919     unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
5920     if (TemplateParamLists.size() > VDTemplateParamLists)
5921       NewVD->setTemplateParameterListsInfo(
5922           Context, TemplateParamLists.drop_back(VDTemplateParamLists));
5923 
5924     if (D.getDeclSpec().isConstexprSpecified())
5925       NewVD->setConstexpr(true);
5926 
5927     if (D.getDeclSpec().isConceptSpecified()) {
5928       NewVD->setConcept(true);
5929 
5930       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
5931       // be declared with the thread_local, inline, friend, or constexpr
5932       // specifiers, [...]
5933       if (D.getDeclSpec().getThreadStorageClassSpec() == TSCS_thread_local) {
5934         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5935              diag::err_concept_decl_invalid_specifiers)
5936             << 0 << 0;
5937         NewVD->setInvalidDecl(true);
5938       }
5939 
5940       if (D.getDeclSpec().isConstexprSpecified()) {
5941         Diag(D.getDeclSpec().getConstexprSpecLoc(),
5942              diag::err_concept_decl_invalid_specifiers)
5943             << 0 << 3;
5944         NewVD->setInvalidDecl(true);
5945       }
5946     }
5947   }
5948 
5949   // Set the lexical context. If the declarator has a C++ scope specifier, the
5950   // lexical context will be different from the semantic context.
5951   NewVD->setLexicalDeclContext(CurContext);
5952   if (NewTemplate)
5953     NewTemplate->setLexicalDeclContext(CurContext);
5954 
5955   if (IsLocalExternDecl)
5956     NewVD->setLocalExternDecl();
5957 
5958   bool EmitTLSUnsupportedError = false;
5959   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec()) {
5960     // C++11 [dcl.stc]p4:
5961     //   When thread_local is applied to a variable of block scope the
5962     //   storage-class-specifier static is implied if it does not appear
5963     //   explicitly.
5964     // Core issue: 'static' is not implied if the variable is declared
5965     //   'extern'.
5966     if (NewVD->hasLocalStorage() &&
5967         (SCSpec != DeclSpec::SCS_unspecified ||
5968          TSCS != DeclSpec::TSCS_thread_local ||
5969          !DC->isFunctionOrMethod()))
5970       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5971            diag::err_thread_non_global)
5972         << DeclSpec::getSpecifierName(TSCS);
5973     else if (!Context.getTargetInfo().isTLSSupported()) {
5974       if (getLangOpts().CUDA) {
5975         // Postpone error emission until we've collected attributes required to
5976         // figure out whether it's a host or device variable and whether the
5977         // error should be ignored.
5978         EmitTLSUnsupportedError = true;
5979         // We still need to mark the variable as TLS so it shows up in AST with
5980         // proper storage class for other tools to use even if we're not going
5981         // to emit any code for it.
5982         NewVD->setTSCSpec(TSCS);
5983       } else
5984         Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5985              diag::err_thread_unsupported);
5986     } else
5987       NewVD->setTSCSpec(TSCS);
5988   }
5989 
5990   // C99 6.7.4p3
5991   //   An inline definition of a function with external linkage shall
5992   //   not contain a definition of a modifiable object with static or
5993   //   thread storage duration...
5994   // We only apply this when the function is required to be defined
5995   // elsewhere, i.e. when the function is not 'extern inline'.  Note
5996   // that a local variable with thread storage duration still has to
5997   // be marked 'static'.  Also note that it's possible to get these
5998   // semantics in C++ using __attribute__((gnu_inline)).
5999   if (SC == SC_Static && S->getFnParent() != nullptr &&
6000       !NewVD->getType().isConstQualified()) {
6001     FunctionDecl *CurFD = getCurFunctionDecl();
6002     if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
6003       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6004            diag::warn_static_local_in_extern_inline);
6005       MaybeSuggestAddingStaticToDecl(CurFD);
6006     }
6007   }
6008 
6009   if (D.getDeclSpec().isModulePrivateSpecified()) {
6010     if (IsVariableTemplateSpecialization)
6011       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6012           << (IsPartialSpecialization ? 1 : 0)
6013           << FixItHint::CreateRemoval(
6014                  D.getDeclSpec().getModulePrivateSpecLoc());
6015     else if (IsExplicitSpecialization)
6016       Diag(NewVD->getLocation(), diag::err_module_private_specialization)
6017         << 2
6018         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6019     else if (NewVD->hasLocalStorage())
6020       Diag(NewVD->getLocation(), diag::err_module_private_local)
6021         << 0 << NewVD->getDeclName()
6022         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
6023         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
6024     else {
6025       NewVD->setModulePrivate();
6026       if (NewTemplate)
6027         NewTemplate->setModulePrivate();
6028     }
6029   }
6030 
6031   // Handle attributes prior to checking for duplicates in MergeVarDecl
6032   ProcessDeclAttributes(S, NewVD, D);
6033 
6034   if (getLangOpts().CUDA) {
6035     if (EmitTLSUnsupportedError && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD))
6036       Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
6037            diag::err_thread_unsupported);
6038     // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
6039     // storage [duration]."
6040     if (SC == SC_None && S->getFnParent() != nullptr &&
6041         (NewVD->hasAttr<CUDASharedAttr>() ||
6042          NewVD->hasAttr<CUDAConstantAttr>())) {
6043       NewVD->setStorageClass(SC_Static);
6044     }
6045   }
6046 
6047   // Ensure that dllimport globals without explicit storage class are treated as
6048   // extern. The storage class is set above using parsed attributes. Now we can
6049   // check the VarDecl itself.
6050   assert(!NewVD->hasAttr<DLLImportAttr>() ||
6051          NewVD->getAttr<DLLImportAttr>()->isInherited() ||
6052          NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
6053 
6054   // In auto-retain/release, infer strong retension for variables of
6055   // retainable type.
6056   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
6057     NewVD->setInvalidDecl();
6058 
6059   // Handle GNU asm-label extension (encoded as an attribute).
6060   if (Expr *E = (Expr*)D.getAsmLabel()) {
6061     // The parser guarantees this is a string.
6062     StringLiteral *SE = cast<StringLiteral>(E);
6063     StringRef Label = SE->getString();
6064     if (S->getFnParent() != nullptr) {
6065       switch (SC) {
6066       case SC_None:
6067       case SC_Auto:
6068         Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
6069         break;
6070       case SC_Register:
6071         // Local Named register
6072         if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
6073             DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
6074           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6075         break;
6076       case SC_Static:
6077       case SC_Extern:
6078       case SC_PrivateExtern:
6079         break;
6080       }
6081     } else if (SC == SC_Register) {
6082       // Global Named register
6083       if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
6084         const auto &TI = Context.getTargetInfo();
6085         bool HasSizeMismatch;
6086 
6087         if (!TI.isValidGCCRegisterName(Label))
6088           Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
6089         else if (!TI.validateGlobalRegisterVariable(Label,
6090                                                     Context.getTypeSize(R),
6091                                                     HasSizeMismatch))
6092           Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
6093         else if (HasSizeMismatch)
6094           Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
6095       }
6096 
6097       if (!R->isIntegralType(Context) && !R->isPointerType()) {
6098         Diag(D.getLocStart(), diag::err_asm_bad_register_type);
6099         NewVD->setInvalidDecl(true);
6100       }
6101     }
6102 
6103     NewVD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0),
6104                                                 Context, Label, 0));
6105   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
6106     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
6107       ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
6108     if (I != ExtnameUndeclaredIdentifiers.end()) {
6109       if (isDeclExternC(NewVD)) {
6110         NewVD->addAttr(I->second);
6111         ExtnameUndeclaredIdentifiers.erase(I);
6112       } else
6113         Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
6114             << /*Variable*/1 << NewVD;
6115     }
6116   }
6117 
6118   // Diagnose shadowed variables before filtering for scope.
6119   if (D.getCXXScopeSpec().isEmpty())
6120     CheckShadow(S, NewVD, Previous);
6121 
6122   // Don't consider existing declarations that are in a different
6123   // scope and are out-of-semantic-context declarations (if the new
6124   // declaration has linkage).
6125   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
6126                        D.getCXXScopeSpec().isNotEmpty() ||
6127                        IsExplicitSpecialization ||
6128                        IsVariableTemplateSpecialization);
6129 
6130   // Check whether the previous declaration is in the same block scope. This
6131   // affects whether we merge types with it, per C++11 [dcl.array]p3.
6132   if (getLangOpts().CPlusPlus &&
6133       NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
6134     NewVD->setPreviousDeclInSameBlockScope(
6135         Previous.isSingleResult() && !Previous.isShadowed() &&
6136         isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
6137 
6138   if (!getLangOpts().CPlusPlus) {
6139     D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6140   } else {
6141     // If this is an explicit specialization of a static data member, check it.
6142     if (IsExplicitSpecialization && !NewVD->isInvalidDecl() &&
6143         CheckMemberSpecialization(NewVD, Previous))
6144       NewVD->setInvalidDecl();
6145 
6146     // Merge the decl with the existing one if appropriate.
6147     if (!Previous.empty()) {
6148       if (Previous.isSingleResult() &&
6149           isa<FieldDecl>(Previous.getFoundDecl()) &&
6150           D.getCXXScopeSpec().isSet()) {
6151         // The user tried to define a non-static data member
6152         // out-of-line (C++ [dcl.meaning]p1).
6153         Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
6154           << D.getCXXScopeSpec().getRange();
6155         Previous.clear();
6156         NewVD->setInvalidDecl();
6157       }
6158     } else if (D.getCXXScopeSpec().isSet()) {
6159       // No previous declaration in the qualifying scope.
6160       Diag(D.getIdentifierLoc(), diag::err_no_member)
6161         << Name << computeDeclContext(D.getCXXScopeSpec(), true)
6162         << D.getCXXScopeSpec().getRange();
6163       NewVD->setInvalidDecl();
6164     }
6165 
6166     if (!IsVariableTemplateSpecialization)
6167       D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
6168 
6169     if (NewTemplate) {
6170       VarTemplateDecl *PrevVarTemplate =
6171           NewVD->getPreviousDecl()
6172               ? NewVD->getPreviousDecl()->getDescribedVarTemplate()
6173               : nullptr;
6174 
6175       // Check the template parameter list of this declaration, possibly
6176       // merging in the template parameter list from the previous variable
6177       // template declaration.
6178       if (CheckTemplateParameterList(
6179               TemplateParams,
6180               PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
6181                               : nullptr,
6182               (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
6183                DC->isDependentContext())
6184                   ? TPC_ClassTemplateMember
6185                   : TPC_VarTemplate))
6186         NewVD->setInvalidDecl();
6187 
6188       // If we are providing an explicit specialization of a static variable
6189       // template, make a note of that.
6190       if (PrevVarTemplate &&
6191           PrevVarTemplate->getInstantiatedFromMemberTemplate())
6192         PrevVarTemplate->setMemberSpecialization();
6193     }
6194   }
6195 
6196   ProcessPragmaWeak(S, NewVD);
6197 
6198   // If this is the first declaration of an extern C variable, update
6199   // the map of such variables.
6200   if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
6201       isIncompleteDeclExternC(*this, NewVD))
6202     RegisterLocallyScopedExternCDecl(NewVD, S);
6203 
6204   if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
6205     Decl *ManglingContextDecl;
6206     if (MangleNumberingContext *MCtx = getCurrentMangleNumberContext(
6207             NewVD->getDeclContext(), ManglingContextDecl)) {
6208       Context.setManglingNumber(
6209           NewVD, MCtx->getManglingNumber(
6210                      NewVD, getMSManglingNumber(getLangOpts(), S)));
6211       Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
6212     }
6213   }
6214 
6215   // Special handling of variable named 'main'.
6216   if (Name.isIdentifier() && Name.getAsIdentifierInfo()->isStr("main") &&
6217       NewVD->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
6218       !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
6219 
6220     // C++ [basic.start.main]p3
6221     // A program that declares a variable main at global scope is ill-formed.
6222     if (getLangOpts().CPlusPlus)
6223       Diag(D.getLocStart(), diag::err_main_global_variable);
6224 
6225     // In C, and external-linkage variable named main results in undefined
6226     // behavior.
6227     else if (NewVD->hasExternalFormalLinkage())
6228       Diag(D.getLocStart(), diag::warn_main_redefined);
6229   }
6230 
6231   if (D.isRedeclaration() && !Previous.empty()) {
6232     checkDLLAttributeRedeclaration(
6233         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewVD,
6234         IsExplicitSpecialization);
6235   }
6236 
6237   if (NewTemplate) {
6238     if (NewVD->isInvalidDecl())
6239       NewTemplate->setInvalidDecl();
6240     ActOnDocumentableDecl(NewTemplate);
6241     return NewTemplate;
6242   }
6243 
6244   return NewVD;
6245 }
6246 
6247 /// \brief Diagnose variable or built-in function shadowing.  Implements
6248 /// -Wshadow.
6249 ///
6250 /// This method is called whenever a VarDecl is added to a "useful"
6251 /// scope.
6252 ///
6253 /// \param S the scope in which the shadowing name is being declared
6254 /// \param R the lookup of the name
6255 ///
6256 void Sema::CheckShadow(Scope *S, VarDecl *D, const LookupResult& R) {
6257   // Return if warning is ignored.
6258   if (Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc()))
6259     return;
6260 
6261   // Don't diagnose declarations at file scope.
6262   if (D->hasGlobalStorage())
6263     return;
6264 
6265   DeclContext *NewDC = D->getDeclContext();
6266 
6267   // Only diagnose if we're shadowing an unambiguous field or variable.
6268   if (R.getResultKind() != LookupResult::Found)
6269     return;
6270 
6271   NamedDecl* ShadowedDecl = R.getFoundDecl();
6272   if (!isa<VarDecl>(ShadowedDecl) && !isa<FieldDecl>(ShadowedDecl))
6273     return;
6274 
6275   // Fields are not shadowed by variables in C++ static methods.
6276   if (isa<FieldDecl>(ShadowedDecl))
6277     if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
6278       if (MD->isStatic())
6279         return;
6280 
6281   if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
6282     if (shadowedVar->isExternC()) {
6283       // For shadowing external vars, make sure that we point to the global
6284       // declaration, not a locally scoped extern declaration.
6285       for (auto I : shadowedVar->redecls())
6286         if (I->isFileVarDecl()) {
6287           ShadowedDecl = I;
6288           break;
6289         }
6290     }
6291 
6292   DeclContext *OldDC = ShadowedDecl->getDeclContext();
6293 
6294   // Only warn about certain kinds of shadowing for class members.
6295   if (NewDC && NewDC->isRecord()) {
6296     // In particular, don't warn about shadowing non-class members.
6297     if (!OldDC->isRecord())
6298       return;
6299 
6300     // TODO: should we warn about static data members shadowing
6301     // static data members from base classes?
6302 
6303     // TODO: don't diagnose for inaccessible shadowed members.
6304     // This is hard to do perfectly because we might friend the
6305     // shadowing context, but that's just a false negative.
6306   }
6307 
6308   // Determine what kind of declaration we're shadowing.
6309   unsigned Kind;
6310   if (isa<RecordDecl>(OldDC)) {
6311     if (isa<FieldDecl>(ShadowedDecl))
6312       Kind = 3; // field
6313     else
6314       Kind = 2; // static data member
6315   } else if (OldDC->isFileContext())
6316     Kind = 1; // global
6317   else
6318     Kind = 0; // local
6319 
6320   DeclarationName Name = R.getLookupName();
6321 
6322   // Emit warning and note.
6323   if (getSourceManager().isInSystemMacro(R.getNameLoc()))
6324     return;
6325   Diag(R.getNameLoc(), diag::warn_decl_shadow) << Name << Kind << OldDC;
6326   Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
6327 }
6328 
6329 /// \brief Check -Wshadow without the advantage of a previous lookup.
6330 void Sema::CheckShadow(Scope *S, VarDecl *D) {
6331   if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
6332     return;
6333 
6334   LookupResult R(*this, D->getDeclName(), D->getLocation(),
6335                  Sema::LookupOrdinaryName, Sema::ForRedeclaration);
6336   LookupName(R, S);
6337   CheckShadow(S, D, R);
6338 }
6339 
6340 /// Check for conflict between this global or extern "C" declaration and
6341 /// previous global or extern "C" declarations. This is only used in C++.
6342 template<typename T>
6343 static bool checkGlobalOrExternCConflict(
6344     Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
6345   assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
6346   NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
6347 
6348   if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
6349     // The common case: this global doesn't conflict with any extern "C"
6350     // declaration.
6351     return false;
6352   }
6353 
6354   if (Prev) {
6355     if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
6356       // Both the old and new declarations have C language linkage. This is a
6357       // redeclaration.
6358       Previous.clear();
6359       Previous.addDecl(Prev);
6360       return true;
6361     }
6362 
6363     // This is a global, non-extern "C" declaration, and there is a previous
6364     // non-global extern "C" declaration. Diagnose if this is a variable
6365     // declaration.
6366     if (!isa<VarDecl>(ND))
6367       return false;
6368   } else {
6369     // The declaration is extern "C". Check for any declaration in the
6370     // translation unit which might conflict.
6371     if (IsGlobal) {
6372       // We have already performed the lookup into the translation unit.
6373       IsGlobal = false;
6374       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6375            I != E; ++I) {
6376         if (isa<VarDecl>(*I)) {
6377           Prev = *I;
6378           break;
6379         }
6380       }
6381     } else {
6382       DeclContext::lookup_result R =
6383           S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
6384       for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
6385            I != E; ++I) {
6386         if (isa<VarDecl>(*I)) {
6387           Prev = *I;
6388           break;
6389         }
6390         // FIXME: If we have any other entity with this name in global scope,
6391         // the declaration is ill-formed, but that is a defect: it breaks the
6392         // 'stat' hack, for instance. Only variables can have mangled name
6393         // clashes with extern "C" declarations, so only they deserve a
6394         // diagnostic.
6395       }
6396     }
6397 
6398     if (!Prev)
6399       return false;
6400   }
6401 
6402   // Use the first declaration's location to ensure we point at something which
6403   // is lexically inside an extern "C" linkage-spec.
6404   assert(Prev && "should have found a previous declaration to diagnose");
6405   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
6406     Prev = FD->getFirstDecl();
6407   else
6408     Prev = cast<VarDecl>(Prev)->getFirstDecl();
6409 
6410   S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
6411     << IsGlobal << ND;
6412   S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
6413     << IsGlobal;
6414   return false;
6415 }
6416 
6417 /// Apply special rules for handling extern "C" declarations. Returns \c true
6418 /// if we have found that this is a redeclaration of some prior entity.
6419 ///
6420 /// Per C++ [dcl.link]p6:
6421 ///   Two declarations [for a function or variable] with C language linkage
6422 ///   with the same name that appear in different scopes refer to the same
6423 ///   [entity]. An entity with C language linkage shall not be declared with
6424 ///   the same name as an entity in global scope.
6425 template<typename T>
6426 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
6427                                                   LookupResult &Previous) {
6428   if (!S.getLangOpts().CPlusPlus) {
6429     // In C, when declaring a global variable, look for a corresponding 'extern'
6430     // variable declared in function scope. We don't need this in C++, because
6431     // we find local extern decls in the surrounding file-scope DeclContext.
6432     if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
6433       if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
6434         Previous.clear();
6435         Previous.addDecl(Prev);
6436         return true;
6437       }
6438     }
6439     return false;
6440   }
6441 
6442   // A declaration in the translation unit can conflict with an extern "C"
6443   // declaration.
6444   if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
6445     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
6446 
6447   // An extern "C" declaration can conflict with a declaration in the
6448   // translation unit or can be a redeclaration of an extern "C" declaration
6449   // in another scope.
6450   if (isIncompleteDeclExternC(S,ND))
6451     return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
6452 
6453   // Neither global nor extern "C": nothing to do.
6454   return false;
6455 }
6456 
6457 void Sema::CheckVariableDeclarationType(VarDecl *NewVD) {
6458   // If the decl is already known invalid, don't check it.
6459   if (NewVD->isInvalidDecl())
6460     return;
6461 
6462   TypeSourceInfo *TInfo = NewVD->getTypeSourceInfo();
6463   QualType T = TInfo->getType();
6464 
6465   // Defer checking an 'auto' type until its initializer is attached.
6466   if (T->isUndeducedType())
6467     return;
6468 
6469   if (NewVD->hasAttrs())
6470     CheckAlignasUnderalignment(NewVD);
6471 
6472   if (T->isObjCObjectType()) {
6473     Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
6474       << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
6475     T = Context.getObjCObjectPointerType(T);
6476     NewVD->setType(T);
6477   }
6478 
6479   // Emit an error if an address space was applied to decl with local storage.
6480   // This includes arrays of objects with address space qualifiers, but not
6481   // automatic variables that point to other address spaces.
6482   // ISO/IEC TR 18037 S5.1.2
6483   if (!getLangOpts().OpenCL
6484       && NewVD->hasLocalStorage() && T.getAddressSpace() != 0) {
6485     Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl);
6486     NewVD->setInvalidDecl();
6487     return;
6488   }
6489 
6490   // OpenCL v1.2 s6.8 -- The static qualifier is valid only in program
6491   // scope.
6492   if (getLangOpts().OpenCLVersion == 120 &&
6493       !getOpenCLOptions().cl_clang_storage_class_specifiers &&
6494       NewVD->isStaticLocal()) {
6495     Diag(NewVD->getLocation(), diag::err_static_function_scope);
6496     NewVD->setInvalidDecl();
6497     return;
6498   }
6499 
6500   // OpenCL v1.2 s6.5 - All program scope variables must be declared in the
6501   // __constant address space.
6502   // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6503   // variables inside a function can also be declared in the global
6504   // address space.
6505   if (getLangOpts().OpenCL) {
6506     if (NewVD->isFileVarDecl()) {
6507       if (!T->isSamplerT() &&
6508           !(T.getAddressSpace() == LangAS::opencl_constant ||
6509             (T.getAddressSpace() == LangAS::opencl_global &&
6510              getLangOpts().OpenCLVersion == 200))) {
6511         if (getLangOpts().OpenCLVersion == 200)
6512           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6513               << "global or constant";
6514         else
6515           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6516               << "constant";
6517         NewVD->setInvalidDecl();
6518         return;
6519       }
6520     } else {
6521       // OpenCL v2.0 s6.5.1 - Variables defined at program scope and static
6522       // variables inside a function can also be declared in the global
6523       // address space.
6524       if (NewVD->isStaticLocal() &&
6525           !(T.getAddressSpace() == LangAS::opencl_constant ||
6526             (T.getAddressSpace() == LangAS::opencl_global &&
6527              getLangOpts().OpenCLVersion == 200))) {
6528         if (getLangOpts().OpenCLVersion == 200)
6529           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6530               << "global or constant";
6531         else
6532           Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
6533               << "constant";
6534         NewVD->setInvalidDecl();
6535         return;
6536       }
6537       // OpenCL v1.1 s6.5.2 and s6.5.3 no local or constant variables
6538       // in functions.
6539       if (T.getAddressSpace() == LangAS::opencl_constant ||
6540           T.getAddressSpace() == LangAS::opencl_local) {
6541         FunctionDecl *FD = getCurFunctionDecl();
6542         if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
6543           if (T.getAddressSpace() == LangAS::opencl_constant)
6544             Diag(NewVD->getLocation(), diag::err_opencl_non_kernel_variable)
6545                 << "constant";
6546           else
6547             Diag(NewVD->getLocation(), diag::err_opencl_non_kernel_variable)
6548                 << "local";
6549           NewVD->setInvalidDecl();
6550           return;
6551         }
6552       }
6553     }
6554   }
6555 
6556   if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
6557       && !NewVD->hasAttr<BlocksAttr>()) {
6558     if (getLangOpts().getGC() != LangOptions::NonGC)
6559       Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
6560     else {
6561       assert(!getLangOpts().ObjCAutoRefCount);
6562       Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
6563     }
6564   }
6565 
6566   bool isVM = T->isVariablyModifiedType();
6567   if (isVM || NewVD->hasAttr<CleanupAttr>() ||
6568       NewVD->hasAttr<BlocksAttr>())
6569     getCurFunction()->setHasBranchProtectedScope();
6570 
6571   if ((isVM && NewVD->hasLinkage()) ||
6572       (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
6573     bool SizeIsNegative;
6574     llvm::APSInt Oversized;
6575     TypeSourceInfo *FixedTInfo =
6576       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
6577                                                     SizeIsNegative, Oversized);
6578     if (!FixedTInfo && T->isVariableArrayType()) {
6579       const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
6580       // FIXME: This won't give the correct result for
6581       // int a[10][n];
6582       SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
6583 
6584       if (NewVD->isFileVarDecl())
6585         Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
6586         << SizeRange;
6587       else if (NewVD->isStaticLocal())
6588         Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
6589         << SizeRange;
6590       else
6591         Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
6592         << SizeRange;
6593       NewVD->setInvalidDecl();
6594       return;
6595     }
6596 
6597     if (!FixedTInfo) {
6598       if (NewVD->isFileVarDecl())
6599         Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
6600       else
6601         Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
6602       NewVD->setInvalidDecl();
6603       return;
6604     }
6605 
6606     Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
6607     NewVD->setType(FixedTInfo->getType());
6608     NewVD->setTypeSourceInfo(FixedTInfo);
6609   }
6610 
6611   if (T->isVoidType()) {
6612     // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
6613     //                    of objects and functions.
6614     if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
6615       Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
6616         << T;
6617       NewVD->setInvalidDecl();
6618       return;
6619     }
6620   }
6621 
6622   if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
6623     Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
6624     NewVD->setInvalidDecl();
6625     return;
6626   }
6627 
6628   if (isVM && NewVD->hasAttr<BlocksAttr>()) {
6629     Diag(NewVD->getLocation(), diag::err_block_on_vm);
6630     NewVD->setInvalidDecl();
6631     return;
6632   }
6633 
6634   if (NewVD->isConstexpr() && !T->isDependentType() &&
6635       RequireLiteralType(NewVD->getLocation(), T,
6636                          diag::err_constexpr_var_non_literal)) {
6637     NewVD->setInvalidDecl();
6638     return;
6639   }
6640 }
6641 
6642 /// \brief Perform semantic checking on a newly-created variable
6643 /// declaration.
6644 ///
6645 /// This routine performs all of the type-checking required for a
6646 /// variable declaration once it has been built. It is used both to
6647 /// check variables after they have been parsed and their declarators
6648 /// have been translated into a declaration, and to check variables
6649 /// that have been instantiated from a template.
6650 ///
6651 /// Sets NewVD->isInvalidDecl() if an error was encountered.
6652 ///
6653 /// Returns true if the variable declaration is a redeclaration.
6654 bool Sema::CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous) {
6655   CheckVariableDeclarationType(NewVD);
6656 
6657   // If the decl is already known invalid, don't check it.
6658   if (NewVD->isInvalidDecl())
6659     return false;
6660 
6661   // If we did not find anything by this name, look for a non-visible
6662   // extern "C" declaration with the same name.
6663   if (Previous.empty() &&
6664       checkForConflictWithNonVisibleExternC(*this, NewVD, Previous))
6665     Previous.setShadowed();
6666 
6667   if (!Previous.empty()) {
6668     MergeVarDecl(NewVD, Previous);
6669     return true;
6670   }
6671   return false;
6672 }
6673 
6674 namespace {
6675 struct FindOverriddenMethod {
6676   Sema *S;
6677   CXXMethodDecl *Method;
6678 
6679   /// Member lookup function that determines whether a given C++
6680   /// method overrides a method in a base class, to be used with
6681   /// CXXRecordDecl::lookupInBases().
6682   bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
6683     RecordDecl *BaseRecord =
6684         Specifier->getType()->getAs<RecordType>()->getDecl();
6685 
6686     DeclarationName Name = Method->getDeclName();
6687 
6688     // FIXME: Do we care about other names here too?
6689     if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
6690       // We really want to find the base class destructor here.
6691       QualType T = S->Context.getTypeDeclType(BaseRecord);
6692       CanQualType CT = S->Context.getCanonicalType(T);
6693 
6694       Name = S->Context.DeclarationNames.getCXXDestructorName(CT);
6695     }
6696 
6697     for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
6698          Path.Decls = Path.Decls.slice(1)) {
6699       NamedDecl *D = Path.Decls.front();
6700       if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
6701         if (MD->isVirtual() && !S->IsOverload(Method, MD, false))
6702           return true;
6703       }
6704     }
6705 
6706     return false;
6707   }
6708 };
6709 
6710 enum OverrideErrorKind { OEK_All, OEK_NonDeleted, OEK_Deleted };
6711 } // end anonymous namespace
6712 
6713 /// \brief Report an error regarding overriding, along with any relevant
6714 /// overriden methods.
6715 ///
6716 /// \param DiagID the primary error to report.
6717 /// \param MD the overriding method.
6718 /// \param OEK which overrides to include as notes.
6719 static void ReportOverrides(Sema& S, unsigned DiagID, const CXXMethodDecl *MD,
6720                             OverrideErrorKind OEK = OEK_All) {
6721   S.Diag(MD->getLocation(), DiagID) << MD->getDeclName();
6722   for (CXXMethodDecl::method_iterator I = MD->begin_overridden_methods(),
6723                                       E = MD->end_overridden_methods();
6724        I != E; ++I) {
6725     // This check (& the OEK parameter) could be replaced by a predicate, but
6726     // without lambdas that would be overkill. This is still nicer than writing
6727     // out the diag loop 3 times.
6728     if ((OEK == OEK_All) ||
6729         (OEK == OEK_NonDeleted && !(*I)->isDeleted()) ||
6730         (OEK == OEK_Deleted && (*I)->isDeleted()))
6731       S.Diag((*I)->getLocation(), diag::note_overridden_virtual_function);
6732   }
6733 }
6734 
6735 /// AddOverriddenMethods - See if a method overrides any in the base classes,
6736 /// and if so, check that it's a valid override and remember it.
6737 bool Sema::AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD) {
6738   // Look for methods in base classes that this method might override.
6739   CXXBasePaths Paths;
6740   FindOverriddenMethod FOM;
6741   FOM.Method = MD;
6742   FOM.S = this;
6743   bool hasDeletedOverridenMethods = false;
6744   bool hasNonDeletedOverridenMethods = false;
6745   bool AddedAny = false;
6746   if (DC->lookupInBases(FOM, Paths)) {
6747     for (auto *I : Paths.found_decls()) {
6748       if (CXXMethodDecl *OldMD = dyn_cast<CXXMethodDecl>(I)) {
6749         MD->addOverriddenMethod(OldMD->getCanonicalDecl());
6750         if (!CheckOverridingFunctionReturnType(MD, OldMD) &&
6751             !CheckOverridingFunctionAttributes(MD, OldMD) &&
6752             !CheckOverridingFunctionExceptionSpec(MD, OldMD) &&
6753             !CheckIfOverriddenFunctionIsMarkedFinal(MD, OldMD)) {
6754           hasDeletedOverridenMethods |= OldMD->isDeleted();
6755           hasNonDeletedOverridenMethods |= !OldMD->isDeleted();
6756           AddedAny = true;
6757         }
6758       }
6759     }
6760   }
6761 
6762   if (hasDeletedOverridenMethods && !MD->isDeleted()) {
6763     ReportOverrides(*this, diag::err_non_deleted_override, MD, OEK_Deleted);
6764   }
6765   if (hasNonDeletedOverridenMethods && MD->isDeleted()) {
6766     ReportOverrides(*this, diag::err_deleted_override, MD, OEK_NonDeleted);
6767   }
6768 
6769   return AddedAny;
6770 }
6771 
6772 namespace {
6773   // Struct for holding all of the extra arguments needed by
6774   // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
6775   struct ActOnFDArgs {
6776     Scope *S;
6777     Declarator &D;
6778     MultiTemplateParamsArg TemplateParamLists;
6779     bool AddToScope;
6780   };
6781 }
6782 
6783 namespace {
6784 
6785 // Callback to only accept typo corrections that have a non-zero edit distance.
6786 // Also only accept corrections that have the same parent decl.
6787 class DifferentNameValidatorCCC : public CorrectionCandidateCallback {
6788  public:
6789   DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
6790                             CXXRecordDecl *Parent)
6791       : Context(Context), OriginalFD(TypoFD),
6792         ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
6793 
6794   bool ValidateCandidate(const TypoCorrection &candidate) override {
6795     if (candidate.getEditDistance() == 0)
6796       return false;
6797 
6798     SmallVector<unsigned, 1> MismatchedParams;
6799     for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
6800                                           CDeclEnd = candidate.end();
6801          CDecl != CDeclEnd; ++CDecl) {
6802       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6803 
6804       if (FD && !FD->hasBody() &&
6805           hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
6806         if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
6807           CXXRecordDecl *Parent = MD->getParent();
6808           if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
6809             return true;
6810         } else if (!ExpectedParent) {
6811           return true;
6812         }
6813       }
6814     }
6815 
6816     return false;
6817   }
6818 
6819  private:
6820   ASTContext &Context;
6821   FunctionDecl *OriginalFD;
6822   CXXRecordDecl *ExpectedParent;
6823 };
6824 
6825 }
6826 
6827 /// \brief Generate diagnostics for an invalid function redeclaration.
6828 ///
6829 /// This routine handles generating the diagnostic messages for an invalid
6830 /// function redeclaration, including finding possible similar declarations
6831 /// or performing typo correction if there are no previous declarations with
6832 /// the same name.
6833 ///
6834 /// Returns a NamedDecl iff typo correction was performed and substituting in
6835 /// the new declaration name does not cause new errors.
6836 static NamedDecl *DiagnoseInvalidRedeclaration(
6837     Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
6838     ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
6839   DeclarationName Name = NewFD->getDeclName();
6840   DeclContext *NewDC = NewFD->getDeclContext();
6841   SmallVector<unsigned, 1> MismatchedParams;
6842   SmallVector<std::pair<FunctionDecl *, unsigned>, 1> NearMatches;
6843   TypoCorrection Correction;
6844   bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
6845   unsigned DiagMsg = IsLocalFriend ? diag::err_no_matching_local_friend
6846                                    : diag::err_member_decl_does_not_match;
6847   LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
6848                     IsLocalFriend ? Sema::LookupLocalFriendName
6849                                   : Sema::LookupOrdinaryName,
6850                     Sema::ForRedeclaration);
6851 
6852   NewFD->setInvalidDecl();
6853   if (IsLocalFriend)
6854     SemaRef.LookupName(Prev, S);
6855   else
6856     SemaRef.LookupQualifiedName(Prev, NewDC);
6857   assert(!Prev.isAmbiguous() &&
6858          "Cannot have an ambiguity in previous-declaration lookup");
6859   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
6860   if (!Prev.empty()) {
6861     for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
6862          Func != FuncEnd; ++Func) {
6863       FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
6864       if (FD &&
6865           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6866         // Add 1 to the index so that 0 can mean the mismatch didn't
6867         // involve a parameter
6868         unsigned ParamNum =
6869             MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
6870         NearMatches.push_back(std::make_pair(FD, ParamNum));
6871       }
6872     }
6873   // If the qualified name lookup yielded nothing, try typo correction
6874   } else if ((Correction = SemaRef.CorrectTypo(
6875                   Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
6876                   &ExtraArgs.D.getCXXScopeSpec(),
6877                   llvm::make_unique<DifferentNameValidatorCCC>(
6878                       SemaRef.Context, NewFD, MD ? MD->getParent() : nullptr),
6879                   Sema::CTK_ErrorRecovery, IsLocalFriend ? nullptr : NewDC))) {
6880     // Set up everything for the call to ActOnFunctionDeclarator
6881     ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
6882                               ExtraArgs.D.getIdentifierLoc());
6883     Previous.clear();
6884     Previous.setLookupName(Correction.getCorrection());
6885     for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
6886                                     CDeclEnd = Correction.end();
6887          CDecl != CDeclEnd; ++CDecl) {
6888       FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
6889       if (FD && !FD->hasBody() &&
6890           hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
6891         Previous.addDecl(FD);
6892       }
6893     }
6894     bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
6895 
6896     NamedDecl *Result;
6897     // Retry building the function declaration with the new previous
6898     // declarations, and with errors suppressed.
6899     {
6900       // Trap errors.
6901       Sema::SFINAETrap Trap(SemaRef);
6902 
6903       // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
6904       // pieces need to verify the typo-corrected C++ declaration and hopefully
6905       // eliminate the need for the parameter pack ExtraArgs.
6906       Result = SemaRef.ActOnFunctionDeclarator(
6907           ExtraArgs.S, ExtraArgs.D,
6908           Correction.getCorrectionDecl()->getDeclContext(),
6909           NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
6910           ExtraArgs.AddToScope);
6911 
6912       if (Trap.hasErrorOccurred())
6913         Result = nullptr;
6914     }
6915 
6916     if (Result) {
6917       // Determine which correction we picked.
6918       Decl *Canonical = Result->getCanonicalDecl();
6919       for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
6920            I != E; ++I)
6921         if ((*I)->getCanonicalDecl() == Canonical)
6922           Correction.setCorrectionDecl(*I);
6923 
6924       SemaRef.diagnoseTypo(
6925           Correction,
6926           SemaRef.PDiag(IsLocalFriend
6927                           ? diag::err_no_matching_local_friend_suggest
6928                           : diag::err_member_decl_does_not_match_suggest)
6929             << Name << NewDC << IsDefinition);
6930       return Result;
6931     }
6932 
6933     // Pretend the typo correction never occurred
6934     ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
6935                               ExtraArgs.D.getIdentifierLoc());
6936     ExtraArgs.D.setRedeclaration(wasRedeclaration);
6937     Previous.clear();
6938     Previous.setLookupName(Name);
6939   }
6940 
6941   SemaRef.Diag(NewFD->getLocation(), DiagMsg)
6942       << Name << NewDC << IsDefinition << NewFD->getLocation();
6943 
6944   bool NewFDisConst = false;
6945   if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
6946     NewFDisConst = NewMD->isConst();
6947 
6948   for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
6949        NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
6950        NearMatch != NearMatchEnd; ++NearMatch) {
6951     FunctionDecl *FD = NearMatch->first;
6952     CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6953     bool FDisConst = MD && MD->isConst();
6954     bool IsMember = MD || !IsLocalFriend;
6955 
6956     // FIXME: These notes are poorly worded for the local friend case.
6957     if (unsigned Idx = NearMatch->second) {
6958       ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
6959       SourceLocation Loc = FDParam->getTypeSpecStartLoc();
6960       if (Loc.isInvalid()) Loc = FD->getLocation();
6961       SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
6962                                  : diag::note_local_decl_close_param_match)
6963         << Idx << FDParam->getType()
6964         << NewFD->getParamDecl(Idx - 1)->getType();
6965     } else if (FDisConst != NewFDisConst) {
6966       SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
6967           << NewFDisConst << FD->getSourceRange().getEnd();
6968     } else
6969       SemaRef.Diag(FD->getLocation(),
6970                    IsMember ? diag::note_member_def_close_match
6971                             : diag::note_local_decl_close_match);
6972   }
6973   return nullptr;
6974 }
6975 
6976 static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D) {
6977   switch (D.getDeclSpec().getStorageClassSpec()) {
6978   default: llvm_unreachable("Unknown storage class!");
6979   case DeclSpec::SCS_auto:
6980   case DeclSpec::SCS_register:
6981   case DeclSpec::SCS_mutable:
6982     SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6983                  diag::err_typecheck_sclass_func);
6984     D.setInvalidType();
6985     break;
6986   case DeclSpec::SCS_unspecified: break;
6987   case DeclSpec::SCS_extern:
6988     if (D.getDeclSpec().isExternInLinkageSpec())
6989       return SC_None;
6990     return SC_Extern;
6991   case DeclSpec::SCS_static: {
6992     if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
6993       // C99 6.7.1p5:
6994       //   The declaration of an identifier for a function that has
6995       //   block scope shall have no explicit storage-class specifier
6996       //   other than extern
6997       // See also (C++ [dcl.stc]p4).
6998       SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
6999                    diag::err_static_block_func);
7000       break;
7001     } else
7002       return SC_Static;
7003   }
7004   case DeclSpec::SCS_private_extern: return SC_PrivateExtern;
7005   }
7006 
7007   // No explicit storage class has already been returned
7008   return SC_None;
7009 }
7010 
7011 static FunctionDecl* CreateNewFunctionDecl(Sema &SemaRef, Declarator &D,
7012                                            DeclContext *DC, QualType &R,
7013                                            TypeSourceInfo *TInfo,
7014                                            StorageClass SC,
7015                                            bool &IsVirtualOkay) {
7016   DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
7017   DeclarationName Name = NameInfo.getName();
7018 
7019   FunctionDecl *NewFD = nullptr;
7020   bool isInline = D.getDeclSpec().isInlineSpecified();
7021 
7022   if (!SemaRef.getLangOpts().CPlusPlus) {
7023     // Determine whether the function was written with a
7024     // prototype. This true when:
7025     //   - there is a prototype in the declarator, or
7026     //   - the type R of the function is some kind of typedef or other reference
7027     //     to a type name (which eventually refers to a function type).
7028     bool HasPrototype =
7029       (D.isFunctionDeclarator() && D.getFunctionTypeInfo().hasPrototype) ||
7030       (!isa<FunctionType>(R.getTypePtr()) && R->isFunctionProtoType());
7031 
7032     NewFD = FunctionDecl::Create(SemaRef.Context, DC,
7033                                  D.getLocStart(), NameInfo, R,
7034                                  TInfo, SC, isInline,
7035                                  HasPrototype, false);
7036     if (D.isInvalidType())
7037       NewFD->setInvalidDecl();
7038 
7039     return NewFD;
7040   }
7041 
7042   bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7043   bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7044 
7045   // Check that the return type is not an abstract class type.
7046   // For record types, this is done by the AbstractClassUsageDiagnoser once
7047   // the class has been completely parsed.
7048   if (!DC->isRecord() &&
7049       SemaRef.RequireNonAbstractType(
7050           D.getIdentifierLoc(), R->getAs<FunctionType>()->getReturnType(),
7051           diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
7052     D.setInvalidType();
7053 
7054   if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
7055     // This is a C++ constructor declaration.
7056     assert(DC->isRecord() &&
7057            "Constructors can only be declared in a member context");
7058 
7059     R = SemaRef.CheckConstructorDeclarator(D, R, SC);
7060     return CXXConstructorDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7061                                       D.getLocStart(), NameInfo,
7062                                       R, TInfo, isExplicit, isInline,
7063                                       /*isImplicitlyDeclared=*/false,
7064                                       isConstexpr);
7065 
7066   } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7067     // This is a C++ destructor declaration.
7068     if (DC->isRecord()) {
7069       R = SemaRef.CheckDestructorDeclarator(D, R, SC);
7070       CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
7071       CXXDestructorDecl *NewDD = CXXDestructorDecl::Create(
7072                                         SemaRef.Context, Record,
7073                                         D.getLocStart(),
7074                                         NameInfo, R, TInfo, isInline,
7075                                         /*isImplicitlyDeclared=*/false);
7076 
7077       // If the class is complete, then we now create the implicit exception
7078       // specification. If the class is incomplete or dependent, we can't do
7079       // it yet.
7080       if (SemaRef.getLangOpts().CPlusPlus11 && !Record->isDependentType() &&
7081           Record->getDefinition() && !Record->isBeingDefined() &&
7082           R->getAs<FunctionProtoType>()->getExceptionSpecType() == EST_None) {
7083         SemaRef.AdjustDestructorExceptionSpec(Record, NewDD);
7084       }
7085 
7086       IsVirtualOkay = true;
7087       return NewDD;
7088 
7089     } else {
7090       SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
7091       D.setInvalidType();
7092 
7093       // Create a FunctionDecl to satisfy the function definition parsing
7094       // code path.
7095       return FunctionDecl::Create(SemaRef.Context, DC,
7096                                   D.getLocStart(),
7097                                   D.getIdentifierLoc(), Name, R, TInfo,
7098                                   SC, isInline,
7099                                   /*hasPrototype=*/true, isConstexpr);
7100     }
7101 
7102   } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
7103     if (!DC->isRecord()) {
7104       SemaRef.Diag(D.getIdentifierLoc(),
7105            diag::err_conv_function_not_member);
7106       return nullptr;
7107     }
7108 
7109     SemaRef.CheckConversionDeclarator(D, R, SC);
7110     IsVirtualOkay = true;
7111     return CXXConversionDecl::Create(SemaRef.Context, cast<CXXRecordDecl>(DC),
7112                                      D.getLocStart(), NameInfo,
7113                                      R, TInfo, isInline, isExplicit,
7114                                      isConstexpr, SourceLocation());
7115 
7116   } else if (DC->isRecord()) {
7117     // If the name of the function is the same as the name of the record,
7118     // then this must be an invalid constructor that has a return type.
7119     // (The parser checks for a return type and makes the declarator a
7120     // constructor if it has no return type).
7121     if (Name.getAsIdentifierInfo() &&
7122         Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
7123       SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
7124         << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
7125         << SourceRange(D.getIdentifierLoc());
7126       return nullptr;
7127     }
7128 
7129     // This is a C++ method declaration.
7130     CXXMethodDecl *Ret = CXXMethodDecl::Create(SemaRef.Context,
7131                                                cast<CXXRecordDecl>(DC),
7132                                                D.getLocStart(), NameInfo, R,
7133                                                TInfo, SC, isInline,
7134                                                isConstexpr, SourceLocation());
7135     IsVirtualOkay = !Ret->isStatic();
7136     return Ret;
7137   } else {
7138     bool isFriend =
7139         SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
7140     if (!isFriend && SemaRef.CurContext->isRecord())
7141       return nullptr;
7142 
7143     // Determine whether the function was written with a
7144     // prototype. This true when:
7145     //   - we're in C++ (where every function has a prototype),
7146     return FunctionDecl::Create(SemaRef.Context, DC,
7147                                 D.getLocStart(),
7148                                 NameInfo, R, TInfo, SC, isInline,
7149                                 true/*HasPrototype*/, isConstexpr);
7150   }
7151 }
7152 
7153 enum OpenCLParamType {
7154   ValidKernelParam,
7155   PtrPtrKernelParam,
7156   PtrKernelParam,
7157   PrivatePtrKernelParam,
7158   InvalidKernelParam,
7159   RecordKernelParam
7160 };
7161 
7162 static OpenCLParamType getOpenCLKernelParameterType(QualType PT) {
7163   if (PT->isPointerType()) {
7164     QualType PointeeType = PT->getPointeeType();
7165     if (PointeeType->isPointerType())
7166       return PtrPtrKernelParam;
7167     return PointeeType.getAddressSpace() == 0 ? PrivatePtrKernelParam
7168                                               : PtrKernelParam;
7169   }
7170 
7171   // TODO: Forbid the other integer types (size_t, ptrdiff_t...) when they can
7172   // be used as builtin types.
7173 
7174   if (PT->isImageType())
7175     return PtrKernelParam;
7176 
7177   if (PT->isBooleanType())
7178     return InvalidKernelParam;
7179 
7180   if (PT->isEventT())
7181     return InvalidKernelParam;
7182 
7183   if (PT->isHalfType())
7184     return InvalidKernelParam;
7185 
7186   if (PT->isRecordType())
7187     return RecordKernelParam;
7188 
7189   return ValidKernelParam;
7190 }
7191 
7192 static void checkIsValidOpenCLKernelParameter(
7193   Sema &S,
7194   Declarator &D,
7195   ParmVarDecl *Param,
7196   llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
7197   QualType PT = Param->getType();
7198 
7199   // Cache the valid types we encounter to avoid rechecking structs that are
7200   // used again
7201   if (ValidTypes.count(PT.getTypePtr()))
7202     return;
7203 
7204   switch (getOpenCLKernelParameterType(PT)) {
7205   case PtrPtrKernelParam:
7206     // OpenCL v1.2 s6.9.a:
7207     // A kernel function argument cannot be declared as a
7208     // pointer to a pointer type.
7209     S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
7210     D.setInvalidType();
7211     return;
7212 
7213   case PrivatePtrKernelParam:
7214     // OpenCL v1.2 s6.9.a:
7215     // A kernel function argument cannot be declared as a
7216     // pointer to the private address space.
7217     S.Diag(Param->getLocation(), diag::err_opencl_private_ptr_kernel_param);
7218     D.setInvalidType();
7219     return;
7220 
7221     // OpenCL v1.2 s6.9.k:
7222     // Arguments to kernel functions in a program cannot be declared with the
7223     // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
7224     // uintptr_t or a struct and/or union that contain fields declared to be
7225     // one of these built-in scalar types.
7226 
7227   case InvalidKernelParam:
7228     // OpenCL v1.2 s6.8 n:
7229     // A kernel function argument cannot be declared
7230     // of event_t type.
7231     S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7232     D.setInvalidType();
7233     return;
7234 
7235   case PtrKernelParam:
7236   case ValidKernelParam:
7237     ValidTypes.insert(PT.getTypePtr());
7238     return;
7239 
7240   case RecordKernelParam:
7241     break;
7242   }
7243 
7244   // Track nested structs we will inspect
7245   SmallVector<const Decl *, 4> VisitStack;
7246 
7247   // Track where we are in the nested structs. Items will migrate from
7248   // VisitStack to HistoryStack as we do the DFS for bad field.
7249   SmallVector<const FieldDecl *, 4> HistoryStack;
7250   HistoryStack.push_back(nullptr);
7251 
7252   const RecordDecl *PD = PT->castAs<RecordType>()->getDecl();
7253   VisitStack.push_back(PD);
7254 
7255   assert(VisitStack.back() && "First decl null?");
7256 
7257   do {
7258     const Decl *Next = VisitStack.pop_back_val();
7259     if (!Next) {
7260       assert(!HistoryStack.empty());
7261       // Found a marker, we have gone up a level
7262       if (const FieldDecl *Hist = HistoryStack.pop_back_val())
7263         ValidTypes.insert(Hist->getType().getTypePtr());
7264 
7265       continue;
7266     }
7267 
7268     // Adds everything except the original parameter declaration (which is not a
7269     // field itself) to the history stack.
7270     const RecordDecl *RD;
7271     if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
7272       HistoryStack.push_back(Field);
7273       RD = Field->getType()->castAs<RecordType>()->getDecl();
7274     } else {
7275       RD = cast<RecordDecl>(Next);
7276     }
7277 
7278     // Add a null marker so we know when we've gone back up a level
7279     VisitStack.push_back(nullptr);
7280 
7281     for (const auto *FD : RD->fields()) {
7282       QualType QT = FD->getType();
7283 
7284       if (ValidTypes.count(QT.getTypePtr()))
7285         continue;
7286 
7287       OpenCLParamType ParamType = getOpenCLKernelParameterType(QT);
7288       if (ParamType == ValidKernelParam)
7289         continue;
7290 
7291       if (ParamType == RecordKernelParam) {
7292         VisitStack.push_back(FD);
7293         continue;
7294       }
7295 
7296       // OpenCL v1.2 s6.9.p:
7297       // Arguments to kernel functions that are declared to be a struct or union
7298       // do not allow OpenCL objects to be passed as elements of the struct or
7299       // union.
7300       if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
7301           ParamType == PrivatePtrKernelParam) {
7302         S.Diag(Param->getLocation(),
7303                diag::err_record_with_pointers_kernel_param)
7304           << PT->isUnionType()
7305           << PT;
7306       } else {
7307         S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
7308       }
7309 
7310       S.Diag(PD->getLocation(), diag::note_within_field_of_type)
7311         << PD->getDeclName();
7312 
7313       // We have an error, now let's go back up through history and show where
7314       // the offending field came from
7315       for (ArrayRef<const FieldDecl *>::const_iterator
7316                I = HistoryStack.begin() + 1,
7317                E = HistoryStack.end();
7318            I != E; ++I) {
7319         const FieldDecl *OuterField = *I;
7320         S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
7321           << OuterField->getType();
7322       }
7323 
7324       S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
7325         << QT->isPointerType()
7326         << QT;
7327       D.setInvalidType();
7328       return;
7329     }
7330   } while (!VisitStack.empty());
7331 }
7332 
7333 NamedDecl*
7334 Sema::ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC,
7335                               TypeSourceInfo *TInfo, LookupResult &Previous,
7336                               MultiTemplateParamsArg TemplateParamLists,
7337                               bool &AddToScope) {
7338   QualType R = TInfo->getType();
7339 
7340   assert(R.getTypePtr()->isFunctionType());
7341 
7342   // TODO: consider using NameInfo for diagnostic.
7343   DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
7344   DeclarationName Name = NameInfo.getName();
7345   StorageClass SC = getFunctionStorageClass(*this, D);
7346 
7347   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
7348     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
7349          diag::err_invalid_thread)
7350       << DeclSpec::getSpecifierName(TSCS);
7351 
7352   if (D.isFirstDeclarationOfMember())
7353     adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
7354                            D.getIdentifierLoc());
7355 
7356   bool isFriend = false;
7357   FunctionTemplateDecl *FunctionTemplate = nullptr;
7358   bool isExplicitSpecialization = false;
7359   bool isFunctionTemplateSpecialization = false;
7360 
7361   bool isDependentClassScopeExplicitSpecialization = false;
7362   bool HasExplicitTemplateArgs = false;
7363   TemplateArgumentListInfo TemplateArgs;
7364 
7365   bool isVirtualOkay = false;
7366 
7367   DeclContext *OriginalDC = DC;
7368   bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
7369 
7370   FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
7371                                               isVirtualOkay);
7372   if (!NewFD) return nullptr;
7373 
7374   if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
7375     NewFD->setTopLevelDeclInObjCContainer();
7376 
7377   // Set the lexical context. If this is a function-scope declaration, or has a
7378   // C++ scope specifier, or is the object of a friend declaration, the lexical
7379   // context will be different from the semantic context.
7380   NewFD->setLexicalDeclContext(CurContext);
7381 
7382   if (IsLocalExternDecl)
7383     NewFD->setLocalExternDecl();
7384 
7385   if (getLangOpts().CPlusPlus) {
7386     bool isInline = D.getDeclSpec().isInlineSpecified();
7387     bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7388     bool isExplicit = D.getDeclSpec().isExplicitSpecified();
7389     bool isConstexpr = D.getDeclSpec().isConstexprSpecified();
7390     bool isConcept = D.getDeclSpec().isConceptSpecified();
7391     isFriend = D.getDeclSpec().isFriendSpecified();
7392     if (isFriend && !isInline && D.isFunctionDefinition()) {
7393       // C++ [class.friend]p5
7394       //   A function can be defined in a friend declaration of a
7395       //   class . . . . Such a function is implicitly inline.
7396       NewFD->setImplicitlyInline();
7397     }
7398 
7399     // If this is a method defined in an __interface, and is not a constructor
7400     // or an overloaded operator, then set the pure flag (isVirtual will already
7401     // return true).
7402     if (const CXXRecordDecl *Parent =
7403           dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
7404       if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
7405         NewFD->setPure(true);
7406 
7407       // C++ [class.union]p2
7408       //   A union can have member functions, but not virtual functions.
7409       if (isVirtual && Parent->isUnion())
7410         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
7411     }
7412 
7413     SetNestedNameSpecifier(NewFD, D);
7414     isExplicitSpecialization = false;
7415     isFunctionTemplateSpecialization = false;
7416     if (D.isInvalidType())
7417       NewFD->setInvalidDecl();
7418 
7419     // Match up the template parameter lists with the scope specifier, then
7420     // determine whether we have a template or a template specialization.
7421     bool Invalid = false;
7422     if (TemplateParameterList *TemplateParams =
7423             MatchTemplateParametersToScopeSpecifier(
7424                 D.getDeclSpec().getLocStart(), D.getIdentifierLoc(),
7425                 D.getCXXScopeSpec(),
7426                 D.getName().getKind() == UnqualifiedId::IK_TemplateId
7427                     ? D.getName().TemplateId
7428                     : nullptr,
7429                 TemplateParamLists, isFriend, isExplicitSpecialization,
7430                 Invalid)) {
7431       if (TemplateParams->size() > 0) {
7432         // This is a function template
7433 
7434         // Check that we can declare a template here.
7435         if (CheckTemplateDeclScope(S, TemplateParams))
7436           NewFD->setInvalidDecl();
7437 
7438         // A destructor cannot be a template.
7439         if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
7440           Diag(NewFD->getLocation(), diag::err_destructor_template);
7441           NewFD->setInvalidDecl();
7442         }
7443 
7444         // If we're adding a template to a dependent context, we may need to
7445         // rebuilding some of the types used within the template parameter list,
7446         // now that we know what the current instantiation is.
7447         if (DC->isDependentContext()) {
7448           ContextRAII SavedContext(*this, DC);
7449           if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
7450             Invalid = true;
7451         }
7452 
7453 
7454         FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
7455                                                         NewFD->getLocation(),
7456                                                         Name, TemplateParams,
7457                                                         NewFD);
7458         FunctionTemplate->setLexicalDeclContext(CurContext);
7459         NewFD->setDescribedFunctionTemplate(FunctionTemplate);
7460 
7461         // For source fidelity, store the other template param lists.
7462         if (TemplateParamLists.size() > 1) {
7463           NewFD->setTemplateParameterListsInfo(Context,
7464                                                TemplateParamLists.drop_back(1));
7465         }
7466       } else {
7467         // This is a function template specialization.
7468         isFunctionTemplateSpecialization = true;
7469         // For source fidelity, store all the template param lists.
7470         if (TemplateParamLists.size() > 0)
7471           NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7472 
7473         // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
7474         if (isFriend) {
7475           // We want to remove the "template<>", found here.
7476           SourceRange RemoveRange = TemplateParams->getSourceRange();
7477 
7478           // If we remove the template<> and the name is not a
7479           // template-id, we're actually silently creating a problem:
7480           // the friend declaration will refer to an untemplated decl,
7481           // and clearly the user wants a template specialization.  So
7482           // we need to insert '<>' after the name.
7483           SourceLocation InsertLoc;
7484           if (D.getName().getKind() != UnqualifiedId::IK_TemplateId) {
7485             InsertLoc = D.getName().getSourceRange().getEnd();
7486             InsertLoc = getLocForEndOfToken(InsertLoc);
7487           }
7488 
7489           Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
7490             << Name << RemoveRange
7491             << FixItHint::CreateRemoval(RemoveRange)
7492             << FixItHint::CreateInsertion(InsertLoc, "<>");
7493         }
7494       }
7495     }
7496     else {
7497       // All template param lists were matched against the scope specifier:
7498       // this is NOT (an explicit specialization of) a template.
7499       if (TemplateParamLists.size() > 0)
7500         // For source fidelity, store all the template param lists.
7501         NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
7502     }
7503 
7504     if (Invalid) {
7505       NewFD->setInvalidDecl();
7506       if (FunctionTemplate)
7507         FunctionTemplate->setInvalidDecl();
7508     }
7509 
7510     // C++ [dcl.fct.spec]p5:
7511     //   The virtual specifier shall only be used in declarations of
7512     //   nonstatic class member functions that appear within a
7513     //   member-specification of a class declaration; see 10.3.
7514     //
7515     if (isVirtual && !NewFD->isInvalidDecl()) {
7516       if (!isVirtualOkay) {
7517         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7518              diag::err_virtual_non_function);
7519       } else if (!CurContext->isRecord()) {
7520         // 'virtual' was specified outside of the class.
7521         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7522              diag::err_virtual_out_of_class)
7523           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7524       } else if (NewFD->getDescribedFunctionTemplate()) {
7525         // C++ [temp.mem]p3:
7526         //  A member function template shall not be virtual.
7527         Diag(D.getDeclSpec().getVirtualSpecLoc(),
7528              diag::err_virtual_member_function_template)
7529           << FixItHint::CreateRemoval(D.getDeclSpec().getVirtualSpecLoc());
7530       } else {
7531         // Okay: Add virtual to the method.
7532         NewFD->setVirtualAsWritten(true);
7533       }
7534 
7535       if (getLangOpts().CPlusPlus14 &&
7536           NewFD->getReturnType()->isUndeducedType())
7537         Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
7538     }
7539 
7540     if (getLangOpts().CPlusPlus14 &&
7541         (NewFD->isDependentContext() ||
7542          (isFriend && CurContext->isDependentContext())) &&
7543         NewFD->getReturnType()->isUndeducedType()) {
7544       // If the function template is referenced directly (for instance, as a
7545       // member of the current instantiation), pretend it has a dependent type.
7546       // This is not really justified by the standard, but is the only sane
7547       // thing to do.
7548       // FIXME: For a friend function, we have not marked the function as being
7549       // a friend yet, so 'isDependentContext' on the FD doesn't work.
7550       const FunctionProtoType *FPT =
7551           NewFD->getType()->castAs<FunctionProtoType>();
7552       QualType Result =
7553           SubstAutoType(FPT->getReturnType(), Context.DependentTy);
7554       NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
7555                                              FPT->getExtProtoInfo()));
7556     }
7557 
7558     // C++ [dcl.fct.spec]p3:
7559     //  The inline specifier shall not appear on a block scope function
7560     //  declaration.
7561     if (isInline && !NewFD->isInvalidDecl()) {
7562       if (CurContext->isFunctionOrMethod()) {
7563         // 'inline' is not allowed on block scope function declaration.
7564         Diag(D.getDeclSpec().getInlineSpecLoc(),
7565              diag::err_inline_declaration_block_scope) << Name
7566           << FixItHint::CreateRemoval(D.getDeclSpec().getInlineSpecLoc());
7567       }
7568     }
7569 
7570     // C++ [dcl.fct.spec]p6:
7571     //  The explicit specifier shall be used only in the declaration of a
7572     //  constructor or conversion function within its class definition;
7573     //  see 12.3.1 and 12.3.2.
7574     if (isExplicit && !NewFD->isInvalidDecl()) {
7575       if (!CurContext->isRecord()) {
7576         // 'explicit' was specified outside of the class.
7577         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7578              diag::err_explicit_out_of_class)
7579           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7580       } else if (!isa<CXXConstructorDecl>(NewFD) &&
7581                  !isa<CXXConversionDecl>(NewFD)) {
7582         // 'explicit' was specified on a function that wasn't a constructor
7583         // or conversion function.
7584         Diag(D.getDeclSpec().getExplicitSpecLoc(),
7585              diag::err_explicit_non_ctor_or_conv_function)
7586           << FixItHint::CreateRemoval(D.getDeclSpec().getExplicitSpecLoc());
7587       }
7588     }
7589 
7590     if (isConstexpr) {
7591       // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
7592       // are implicitly inline.
7593       NewFD->setImplicitlyInline();
7594 
7595       // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
7596       // be either constructors or to return a literal type. Therefore,
7597       // destructors cannot be declared constexpr.
7598       if (isa<CXXDestructorDecl>(NewFD))
7599         Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor);
7600     }
7601 
7602     if (isConcept) {
7603       // C++ Concepts TS [dcl.spec.concept]p1: The concept specifier shall be
7604       // applied only to the definition of a function template [...]
7605       if (!D.isFunctionDefinition()) {
7606         Diag(D.getDeclSpec().getConceptSpecLoc(),
7607              diag::err_function_concept_not_defined);
7608         NewFD->setInvalidDecl();
7609       }
7610 
7611       // C++ Concepts TS [dcl.spec.concept]p1: [...] A function concept shall
7612       // have no exception-specification and is treated as if it were specified
7613       // with noexcept(true) (15.4). [...]
7614       if (const FunctionProtoType *FPT = R->getAs<FunctionProtoType>()) {
7615         if (FPT->hasExceptionSpec()) {
7616           SourceRange Range;
7617           if (D.isFunctionDeclarator())
7618             Range = D.getFunctionTypeInfo().getExceptionSpecRange();
7619           Diag(NewFD->getLocation(), diag::err_function_concept_exception_spec)
7620               << FixItHint::CreateRemoval(Range);
7621           NewFD->setInvalidDecl();
7622         } else {
7623           Context.adjustExceptionSpec(NewFD, EST_BasicNoexcept);
7624         }
7625 
7626         // C++ Concepts TS [dcl.spec.concept]p5: A function concept has the
7627         // following restrictions:
7628         // - The declaration's parameter list shall be equivalent to an empty
7629         //   parameter list.
7630         if (FPT->getNumParams() > 0 || FPT->isVariadic())
7631           Diag(NewFD->getLocation(), diag::err_function_concept_with_params);
7632       }
7633 
7634       // C++ Concepts TS [dcl.spec.concept]p2: Every concept definition is
7635       // implicity defined to be a constexpr declaration (implicitly inline)
7636       NewFD->setImplicitlyInline();
7637 
7638       // C++ Concepts TS [dcl.spec.concept]p2: A concept definition shall not
7639       // be declared with the thread_local, inline, friend, or constexpr
7640       // specifiers, [...]
7641       if (isInline) {
7642         Diag(D.getDeclSpec().getInlineSpecLoc(),
7643              diag::err_concept_decl_invalid_specifiers)
7644             << 1 << 1;
7645         NewFD->setInvalidDecl(true);
7646       }
7647 
7648       if (isFriend) {
7649         Diag(D.getDeclSpec().getFriendSpecLoc(),
7650              diag::err_concept_decl_invalid_specifiers)
7651             << 1 << 2;
7652         NewFD->setInvalidDecl(true);
7653       }
7654 
7655       if (isConstexpr) {
7656         Diag(D.getDeclSpec().getConstexprSpecLoc(),
7657              diag::err_concept_decl_invalid_specifiers)
7658             << 1 << 3;
7659         NewFD->setInvalidDecl(true);
7660       }
7661     }
7662 
7663     // If __module_private__ was specified, mark the function accordingly.
7664     if (D.getDeclSpec().isModulePrivateSpecified()) {
7665       if (isFunctionTemplateSpecialization) {
7666         SourceLocation ModulePrivateLoc
7667           = D.getDeclSpec().getModulePrivateSpecLoc();
7668         Diag(ModulePrivateLoc, diag::err_module_private_specialization)
7669           << 0
7670           << FixItHint::CreateRemoval(ModulePrivateLoc);
7671       } else {
7672         NewFD->setModulePrivate();
7673         if (FunctionTemplate)
7674           FunctionTemplate->setModulePrivate();
7675       }
7676     }
7677 
7678     if (isFriend) {
7679       if (FunctionTemplate) {
7680         FunctionTemplate->setObjectOfFriendDecl();
7681         FunctionTemplate->setAccess(AS_public);
7682       }
7683       NewFD->setObjectOfFriendDecl();
7684       NewFD->setAccess(AS_public);
7685     }
7686 
7687     // If a function is defined as defaulted or deleted, mark it as such now.
7688     // FIXME: Does this ever happen? ActOnStartOfFunctionDef forces the function
7689     // definition kind to FDK_Definition.
7690     switch (D.getFunctionDefinitionKind()) {
7691       case FDK_Declaration:
7692       case FDK_Definition:
7693         break;
7694 
7695       case FDK_Defaulted:
7696         NewFD->setDefaulted();
7697         break;
7698 
7699       case FDK_Deleted:
7700         NewFD->setDeletedAsWritten();
7701         break;
7702     }
7703 
7704     if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
7705         D.isFunctionDefinition()) {
7706       // C++ [class.mfct]p2:
7707       //   A member function may be defined (8.4) in its class definition, in
7708       //   which case it is an inline member function (7.1.2)
7709       NewFD->setImplicitlyInline();
7710     }
7711 
7712     if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
7713         !CurContext->isRecord()) {
7714       // C++ [class.static]p1:
7715       //   A data or function member of a class may be declared static
7716       //   in a class definition, in which case it is a static member of
7717       //   the class.
7718 
7719       // Complain about the 'static' specifier if it's on an out-of-line
7720       // member function definition.
7721       Diag(D.getDeclSpec().getStorageClassSpecLoc(),
7722            diag::err_static_out_of_line)
7723         << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7724     }
7725 
7726     // C++11 [except.spec]p15:
7727     //   A deallocation function with no exception-specification is treated
7728     //   as if it were specified with noexcept(true).
7729     const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
7730     if ((Name.getCXXOverloadedOperator() == OO_Delete ||
7731          Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
7732         getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
7733       NewFD->setType(Context.getFunctionType(
7734           FPT->getReturnType(), FPT->getParamTypes(),
7735           FPT->getExtProtoInfo().withExceptionSpec(EST_BasicNoexcept)));
7736   }
7737 
7738   // Filter out previous declarations that don't match the scope.
7739   FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
7740                        D.getCXXScopeSpec().isNotEmpty() ||
7741                        isExplicitSpecialization ||
7742                        isFunctionTemplateSpecialization);
7743 
7744   // Handle GNU asm-label extension (encoded as an attribute).
7745   if (Expr *E = (Expr*) D.getAsmLabel()) {
7746     // The parser guarantees this is a string.
7747     StringLiteral *SE = cast<StringLiteral>(E);
7748     NewFD->addAttr(::new (Context) AsmLabelAttr(SE->getStrTokenLoc(0), Context,
7749                                                 SE->getString(), 0));
7750   } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7751     llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7752       ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
7753     if (I != ExtnameUndeclaredIdentifiers.end()) {
7754       if (isDeclExternC(NewFD)) {
7755         NewFD->addAttr(I->second);
7756         ExtnameUndeclaredIdentifiers.erase(I);
7757       } else
7758         Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
7759             << /*Variable*/0 << NewFD;
7760     }
7761   }
7762 
7763   // Copy the parameter declarations from the declarator D to the function
7764   // declaration NewFD, if they are available.  First scavenge them into Params.
7765   SmallVector<ParmVarDecl*, 16> Params;
7766   if (D.isFunctionDeclarator()) {
7767     DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7768 
7769     // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
7770     // function that takes no arguments, not a function that takes a
7771     // single void argument.
7772     // We let through "const void" here because Sema::GetTypeForDeclarator
7773     // already checks for that case.
7774     if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
7775       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
7776         ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
7777         assert(Param->getDeclContext() != NewFD && "Was set before ?");
7778         Param->setDeclContext(NewFD);
7779         Params.push_back(Param);
7780 
7781         if (Param->isInvalidDecl())
7782           NewFD->setInvalidDecl();
7783       }
7784     }
7785 
7786   } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
7787     // When we're declaring a function with a typedef, typeof, etc as in the
7788     // following example, we'll need to synthesize (unnamed)
7789     // parameters for use in the declaration.
7790     //
7791     // @code
7792     // typedef void fn(int);
7793     // fn f;
7794     // @endcode
7795 
7796     // Synthesize a parameter for each argument type.
7797     for (const auto &AI : FT->param_types()) {
7798       ParmVarDecl *Param =
7799           BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
7800       Param->setScopeInfo(0, Params.size());
7801       Params.push_back(Param);
7802     }
7803   } else {
7804     assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
7805            "Should not need args for typedef of non-prototype fn");
7806   }
7807 
7808   // Finally, we know we have the right number of parameters, install them.
7809   NewFD->setParams(Params);
7810 
7811   // Find all anonymous symbols defined during the declaration of this function
7812   // and add to NewFD. This lets us track decls such 'enum Y' in:
7813   //
7814   //   void f(enum Y {AA} x) {}
7815   //
7816   // which would otherwise incorrectly end up in the translation unit scope.
7817   NewFD->setDeclsInPrototypeScope(DeclsInPrototypeScope);
7818   DeclsInPrototypeScope.clear();
7819 
7820   if (D.getDeclSpec().isNoreturnSpecified())
7821     NewFD->addAttr(
7822         ::new(Context) C11NoReturnAttr(D.getDeclSpec().getNoreturnSpecLoc(),
7823                                        Context, 0));
7824 
7825   // Functions returning a variably modified type violate C99 6.7.5.2p2
7826   // because all functions have linkage.
7827   if (!NewFD->isInvalidDecl() &&
7828       NewFD->getReturnType()->isVariablyModifiedType()) {
7829     Diag(NewFD->getLocation(), diag::err_vm_func_decl);
7830     NewFD->setInvalidDecl();
7831   }
7832 
7833   // Apply an implicit SectionAttr if #pragma code_seg is active.
7834   if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
7835       !NewFD->hasAttr<SectionAttr>()) {
7836     NewFD->addAttr(
7837         SectionAttr::CreateImplicit(Context, SectionAttr::Declspec_allocate,
7838                                     CodeSegStack.CurrentValue->getString(),
7839                                     CodeSegStack.CurrentPragmaLocation));
7840     if (UnifySection(CodeSegStack.CurrentValue->getString(),
7841                      ASTContext::PSF_Implicit | ASTContext::PSF_Execute |
7842                          ASTContext::PSF_Read,
7843                      NewFD))
7844       NewFD->dropAttr<SectionAttr>();
7845   }
7846 
7847   // Handle attributes.
7848   ProcessDeclAttributes(S, NewFD, D);
7849 
7850   if (getLangOpts().OpenCL) {
7851     // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
7852     // type declaration will generate a compilation error.
7853     unsigned AddressSpace = NewFD->getReturnType().getAddressSpace();
7854     if (AddressSpace == LangAS::opencl_local ||
7855         AddressSpace == LangAS::opencl_global ||
7856         AddressSpace == LangAS::opencl_constant) {
7857       Diag(NewFD->getLocation(),
7858            diag::err_opencl_return_value_with_address_space);
7859       NewFD->setInvalidDecl();
7860     }
7861   }
7862 
7863   if (!getLangOpts().CPlusPlus) {
7864     // Perform semantic checking on the function declaration.
7865     bool isExplicitSpecialization=false;
7866     if (!NewFD->isInvalidDecl() && NewFD->isMain())
7867       CheckMain(NewFD, D.getDeclSpec());
7868 
7869     if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
7870       CheckMSVCRTEntryPoint(NewFD);
7871 
7872     if (!NewFD->isInvalidDecl())
7873       D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
7874                                                   isExplicitSpecialization));
7875     else if (!Previous.empty())
7876       // Recover gracefully from an invalid redeclaration.
7877       D.setRedeclaration(true);
7878     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
7879             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
7880            "previous declaration set still overloaded");
7881 
7882     // Diagnose no-prototype function declarations with calling conventions that
7883     // don't support variadic calls. Only do this in C and do it after merging
7884     // possibly prototyped redeclarations.
7885     const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
7886     if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
7887       CallingConv CC = FT->getExtInfo().getCC();
7888       if (!supportsVariadicCall(CC)) {
7889         // Windows system headers sometimes accidentally use stdcall without
7890         // (void) parameters, so we relax this to a warning.
7891         int DiagID =
7892             CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
7893         Diag(NewFD->getLocation(), DiagID)
7894             << FunctionType::getNameForCallConv(CC);
7895       }
7896     }
7897   } else {
7898     // C++11 [replacement.functions]p3:
7899     //  The program's definitions shall not be specified as inline.
7900     //
7901     // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
7902     //
7903     // Suppress the diagnostic if the function is __attribute__((used)), since
7904     // that forces an external definition to be emitted.
7905     if (D.getDeclSpec().isInlineSpecified() &&
7906         NewFD->isReplaceableGlobalAllocationFunction() &&
7907         !NewFD->hasAttr<UsedAttr>())
7908       Diag(D.getDeclSpec().getInlineSpecLoc(),
7909            diag::ext_operator_new_delete_declared_inline)
7910         << NewFD->getDeclName();
7911 
7912     // If the declarator is a template-id, translate the parser's template
7913     // argument list into our AST format.
7914     if (D.getName().getKind() == UnqualifiedId::IK_TemplateId) {
7915       TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
7916       TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
7917       TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
7918       ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
7919                                          TemplateId->NumArgs);
7920       translateTemplateArguments(TemplateArgsPtr,
7921                                  TemplateArgs);
7922 
7923       HasExplicitTemplateArgs = true;
7924 
7925       if (NewFD->isInvalidDecl()) {
7926         HasExplicitTemplateArgs = false;
7927       } else if (FunctionTemplate) {
7928         // Function template with explicit template arguments.
7929         Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
7930           << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
7931 
7932         HasExplicitTemplateArgs = false;
7933       } else {
7934         assert((isFunctionTemplateSpecialization ||
7935                 D.getDeclSpec().isFriendSpecified()) &&
7936                "should have a 'template<>' for this decl");
7937         // "friend void foo<>(int);" is an implicit specialization decl.
7938         isFunctionTemplateSpecialization = true;
7939       }
7940     } else if (isFriend && isFunctionTemplateSpecialization) {
7941       // This combination is only possible in a recovery case;  the user
7942       // wrote something like:
7943       //   template <> friend void foo(int);
7944       // which we're recovering from as if the user had written:
7945       //   friend void foo<>(int);
7946       // Go ahead and fake up a template id.
7947       HasExplicitTemplateArgs = true;
7948       TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
7949       TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
7950     }
7951 
7952     // If it's a friend (and only if it's a friend), it's possible
7953     // that either the specialized function type or the specialized
7954     // template is dependent, and therefore matching will fail.  In
7955     // this case, don't check the specialization yet.
7956     bool InstantiationDependent = false;
7957     if (isFunctionTemplateSpecialization && isFriend &&
7958         (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
7959          TemplateSpecializationType::anyDependentTemplateArguments(
7960             TemplateArgs.getArgumentArray(), TemplateArgs.size(),
7961             InstantiationDependent))) {
7962       assert(HasExplicitTemplateArgs &&
7963              "friend function specialization without template args");
7964       if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
7965                                                        Previous))
7966         NewFD->setInvalidDecl();
7967     } else if (isFunctionTemplateSpecialization) {
7968       if (CurContext->isDependentContext() && CurContext->isRecord()
7969           && !isFriend) {
7970         isDependentClassScopeExplicitSpecialization = true;
7971         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
7972           diag::ext_function_specialization_in_class :
7973           diag::err_function_specialization_in_class)
7974           << NewFD->getDeclName();
7975       } else if (CheckFunctionTemplateSpecialization(NewFD,
7976                                   (HasExplicitTemplateArgs ? &TemplateArgs
7977                                                            : nullptr),
7978                                                      Previous))
7979         NewFD->setInvalidDecl();
7980 
7981       // C++ [dcl.stc]p1:
7982       //   A storage-class-specifier shall not be specified in an explicit
7983       //   specialization (14.7.3)
7984       FunctionTemplateSpecializationInfo *Info =
7985           NewFD->getTemplateSpecializationInfo();
7986       if (Info && SC != SC_None) {
7987         if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
7988           Diag(NewFD->getLocation(),
7989                diag::err_explicit_specialization_inconsistent_storage_class)
7990             << SC
7991             << FixItHint::CreateRemoval(
7992                                       D.getDeclSpec().getStorageClassSpecLoc());
7993 
7994         else
7995           Diag(NewFD->getLocation(),
7996                diag::ext_explicit_specialization_storage_class)
7997             << FixItHint::CreateRemoval(
7998                                       D.getDeclSpec().getStorageClassSpecLoc());
7999       }
8000 
8001     } else if (isExplicitSpecialization && isa<CXXMethodDecl>(NewFD)) {
8002       if (CheckMemberSpecialization(NewFD, Previous))
8003           NewFD->setInvalidDecl();
8004     }
8005 
8006     // Perform semantic checking on the function declaration.
8007     if (!isDependentClassScopeExplicitSpecialization) {
8008       if (!NewFD->isInvalidDecl() && NewFD->isMain())
8009         CheckMain(NewFD, D.getDeclSpec());
8010 
8011       if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
8012         CheckMSVCRTEntryPoint(NewFD);
8013 
8014       if (!NewFD->isInvalidDecl())
8015         D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
8016                                                     isExplicitSpecialization));
8017       else if (!Previous.empty())
8018         // Recover gracefully from an invalid redeclaration.
8019         D.setRedeclaration(true);
8020     }
8021 
8022     assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
8023             Previous.getResultKind() != LookupResult::FoundOverloaded) &&
8024            "previous declaration set still overloaded");
8025 
8026     NamedDecl *PrincipalDecl = (FunctionTemplate
8027                                 ? cast<NamedDecl>(FunctionTemplate)
8028                                 : NewFD);
8029 
8030     if (isFriend && D.isRedeclaration()) {
8031       AccessSpecifier Access = AS_public;
8032       if (!NewFD->isInvalidDecl())
8033         Access = NewFD->getPreviousDecl()->getAccess();
8034 
8035       NewFD->setAccess(Access);
8036       if (FunctionTemplate) FunctionTemplate->setAccess(Access);
8037     }
8038 
8039     if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
8040         PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
8041       PrincipalDecl->setNonMemberOperator();
8042 
8043     // If we have a function template, check the template parameter
8044     // list. This will check and merge default template arguments.
8045     if (FunctionTemplate) {
8046       FunctionTemplateDecl *PrevTemplate =
8047                                      FunctionTemplate->getPreviousDecl();
8048       CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
8049                        PrevTemplate ? PrevTemplate->getTemplateParameters()
8050                                     : nullptr,
8051                             D.getDeclSpec().isFriendSpecified()
8052                               ? (D.isFunctionDefinition()
8053                                    ? TPC_FriendFunctionTemplateDefinition
8054                                    : TPC_FriendFunctionTemplate)
8055                               : (D.getCXXScopeSpec().isSet() &&
8056                                  DC && DC->isRecord() &&
8057                                  DC->isDependentContext())
8058                                   ? TPC_ClassTemplateMember
8059                                   : TPC_FunctionTemplate);
8060     }
8061 
8062     if (NewFD->isInvalidDecl()) {
8063       // Ignore all the rest of this.
8064     } else if (!D.isRedeclaration()) {
8065       struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
8066                                        AddToScope };
8067       // Fake up an access specifier if it's supposed to be a class member.
8068       if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
8069         NewFD->setAccess(AS_public);
8070 
8071       // Qualified decls generally require a previous declaration.
8072       if (D.getCXXScopeSpec().isSet()) {
8073         // ...with the major exception of templated-scope or
8074         // dependent-scope friend declarations.
8075 
8076         // TODO: we currently also suppress this check in dependent
8077         // contexts because (1) the parameter depth will be off when
8078         // matching friend templates and (2) we might actually be
8079         // selecting a friend based on a dependent factor.  But there
8080         // are situations where these conditions don't apply and we
8081         // can actually do this check immediately.
8082         if (isFriend &&
8083             (TemplateParamLists.size() ||
8084              D.getCXXScopeSpec().getScopeRep()->isDependent() ||
8085              CurContext->isDependentContext())) {
8086           // ignore these
8087         } else {
8088           // The user tried to provide an out-of-line definition for a
8089           // function that is a member of a class or namespace, but there
8090           // was no such member function declared (C++ [class.mfct]p2,
8091           // C++ [namespace.memdef]p2). For example:
8092           //
8093           // class X {
8094           //   void f() const;
8095           // };
8096           //
8097           // void X::f() { } // ill-formed
8098           //
8099           // Complain about this problem, and attempt to suggest close
8100           // matches (e.g., those that differ only in cv-qualifiers and
8101           // whether the parameter types are references).
8102 
8103           if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8104                   *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
8105             AddToScope = ExtraArgs.AddToScope;
8106             return Result;
8107           }
8108         }
8109 
8110         // Unqualified local friend declarations are required to resolve
8111         // to something.
8112       } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
8113         if (NamedDecl *Result = DiagnoseInvalidRedeclaration(
8114                 *this, Previous, NewFD, ExtraArgs, true, S)) {
8115           AddToScope = ExtraArgs.AddToScope;
8116           return Result;
8117         }
8118       }
8119 
8120     } else if (!D.isFunctionDefinition() &&
8121                isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
8122                !isFriend && !isFunctionTemplateSpecialization &&
8123                !isExplicitSpecialization) {
8124       // An out-of-line member function declaration must also be a
8125       // definition (C++ [class.mfct]p2).
8126       // Note that this is not the case for explicit specializations of
8127       // function templates or member functions of class templates, per
8128       // C++ [temp.expl.spec]p2. We also allow these declarations as an
8129       // extension for compatibility with old SWIG code which likes to
8130       // generate them.
8131       Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
8132         << D.getCXXScopeSpec().getRange();
8133     }
8134   }
8135 
8136   ProcessPragmaWeak(S, NewFD);
8137   checkAttributesAfterMerging(*this, *NewFD);
8138 
8139   AddKnownFunctionAttributes(NewFD);
8140 
8141   if (NewFD->hasAttr<OverloadableAttr>() &&
8142       !NewFD->getType()->getAs<FunctionProtoType>()) {
8143     Diag(NewFD->getLocation(),
8144          diag::err_attribute_overloadable_no_prototype)
8145       << NewFD;
8146 
8147     // Turn this into a variadic function with no parameters.
8148     const FunctionType *FT = NewFD->getType()->getAs<FunctionType>();
8149     FunctionProtoType::ExtProtoInfo EPI(
8150         Context.getDefaultCallingConvention(true, false));
8151     EPI.Variadic = true;
8152     EPI.ExtInfo = FT->getExtInfo();
8153 
8154     QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
8155     NewFD->setType(R);
8156   }
8157 
8158   // If there's a #pragma GCC visibility in scope, and this isn't a class
8159   // member, set the visibility of this function.
8160   if (!DC->isRecord() && NewFD->isExternallyVisible())
8161     AddPushedVisibilityAttribute(NewFD);
8162 
8163   // If there's a #pragma clang arc_cf_code_audited in scope, consider
8164   // marking the function.
8165   AddCFAuditedAttribute(NewFD);
8166 
8167   // If this is a function definition, check if we have to apply optnone due to
8168   // a pragma.
8169   if(D.isFunctionDefinition())
8170     AddRangeBasedOptnone(NewFD);
8171 
8172   // If this is the first declaration of an extern C variable, update
8173   // the map of such variables.
8174   if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
8175       isIncompleteDeclExternC(*this, NewFD))
8176     RegisterLocallyScopedExternCDecl(NewFD, S);
8177 
8178   // Set this FunctionDecl's range up to the right paren.
8179   NewFD->setRangeEnd(D.getSourceRange().getEnd());
8180 
8181   if (D.isRedeclaration() && !Previous.empty()) {
8182     checkDLLAttributeRedeclaration(
8183         *this, dyn_cast<NamedDecl>(Previous.getRepresentativeDecl()), NewFD,
8184         isExplicitSpecialization || isFunctionTemplateSpecialization);
8185   }
8186 
8187   if (getLangOpts().CPlusPlus) {
8188     if (FunctionTemplate) {
8189       if (NewFD->isInvalidDecl())
8190         FunctionTemplate->setInvalidDecl();
8191       return FunctionTemplate;
8192     }
8193   }
8194 
8195   if (NewFD->hasAttr<OpenCLKernelAttr>()) {
8196     // OpenCL v1.2 s6.8 static is invalid for kernel functions.
8197     if ((getLangOpts().OpenCLVersion >= 120)
8198         && (SC == SC_Static)) {
8199       Diag(D.getIdentifierLoc(), diag::err_static_kernel);
8200       D.setInvalidType();
8201     }
8202 
8203     // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
8204     if (!NewFD->getReturnType()->isVoidType()) {
8205       SourceRange RTRange = NewFD->getReturnTypeSourceRange();
8206       Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
8207           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
8208                                 : FixItHint());
8209       D.setInvalidType();
8210     }
8211 
8212     llvm::SmallPtrSet<const Type *, 16> ValidTypes;
8213     for (auto Param : NewFD->params())
8214       checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
8215   }
8216 
8217   MarkUnusedFileScopedDecl(NewFD);
8218 
8219   if (getLangOpts().CUDA)
8220     if (IdentifierInfo *II = NewFD->getIdentifier())
8221       if (!NewFD->isInvalidDecl() &&
8222           NewFD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8223         if (II->isStr("cudaConfigureCall")) {
8224           if (!R->getAs<FunctionType>()->getReturnType()->isScalarType())
8225             Diag(NewFD->getLocation(), diag::err_config_scalar_return);
8226 
8227           Context.setcudaConfigureCallDecl(NewFD);
8228         }
8229       }
8230 
8231   // Here we have an function template explicit specialization at class scope.
8232   // The actually specialization will be postponed to template instatiation
8233   // time via the ClassScopeFunctionSpecializationDecl node.
8234   if (isDependentClassScopeExplicitSpecialization) {
8235     ClassScopeFunctionSpecializationDecl *NewSpec =
8236                          ClassScopeFunctionSpecializationDecl::Create(
8237                                 Context, CurContext, SourceLocation(),
8238                                 cast<CXXMethodDecl>(NewFD),
8239                                 HasExplicitTemplateArgs, TemplateArgs);
8240     CurContext->addDecl(NewSpec);
8241     AddToScope = false;
8242   }
8243 
8244   return NewFD;
8245 }
8246 
8247 /// \brief Perform semantic checking of a new function declaration.
8248 ///
8249 /// Performs semantic analysis of the new function declaration
8250 /// NewFD. This routine performs all semantic checking that does not
8251 /// require the actual declarator involved in the declaration, and is
8252 /// used both for the declaration of functions as they are parsed
8253 /// (called via ActOnDeclarator) and for the declaration of functions
8254 /// that have been instantiated via C++ template instantiation (called
8255 /// via InstantiateDecl).
8256 ///
8257 /// \param IsExplicitSpecialization whether this new function declaration is
8258 /// an explicit specialization of the previous declaration.
8259 ///
8260 /// This sets NewFD->isInvalidDecl() to true if there was an error.
8261 ///
8262 /// \returns true if the function declaration is a redeclaration.
8263 bool Sema::CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD,
8264                                     LookupResult &Previous,
8265                                     bool IsExplicitSpecialization) {
8266   assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
8267          "Variably modified return types are not handled here");
8268 
8269   // Determine whether the type of this function should be merged with
8270   // a previous visible declaration. This never happens for functions in C++,
8271   // and always happens in C if the previous declaration was visible.
8272   bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
8273                                !Previous.isShadowed();
8274 
8275   bool Redeclaration = false;
8276   NamedDecl *OldDecl = nullptr;
8277 
8278   // Merge or overload the declaration with an existing declaration of
8279   // the same name, if appropriate.
8280   if (!Previous.empty()) {
8281     // Determine whether NewFD is an overload of PrevDecl or
8282     // a declaration that requires merging. If it's an overload,
8283     // there's no more work to do here; we'll just add the new
8284     // function to the scope.
8285     if (!AllowOverloadingOfFunction(Previous, Context)) {
8286       NamedDecl *Candidate = Previous.getRepresentativeDecl();
8287       if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
8288         Redeclaration = true;
8289         OldDecl = Candidate;
8290       }
8291     } else {
8292       switch (CheckOverload(S, NewFD, Previous, OldDecl,
8293                             /*NewIsUsingDecl*/ false)) {
8294       case Ovl_Match:
8295         Redeclaration = true;
8296         break;
8297 
8298       case Ovl_NonFunction:
8299         Redeclaration = true;
8300         break;
8301 
8302       case Ovl_Overload:
8303         Redeclaration = false;
8304         break;
8305       }
8306 
8307       if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8308         // If a function name is overloadable in C, then every function
8309         // with that name must be marked "overloadable".
8310         Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8311           << Redeclaration << NewFD;
8312         NamedDecl *OverloadedDecl = nullptr;
8313         if (Redeclaration)
8314           OverloadedDecl = OldDecl;
8315         else if (!Previous.empty())
8316           OverloadedDecl = Previous.getRepresentativeDecl();
8317         if (OverloadedDecl)
8318           Diag(OverloadedDecl->getLocation(),
8319                diag::note_attribute_overloadable_prev_overload);
8320         NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8321       }
8322     }
8323   }
8324 
8325   // Check for a previous extern "C" declaration with this name.
8326   if (!Redeclaration &&
8327       checkForConflictWithNonVisibleExternC(*this, NewFD, Previous)) {
8328     if (!Previous.empty()) {
8329       // This is an extern "C" declaration with the same name as a previous
8330       // declaration, and thus redeclares that entity...
8331       Redeclaration = true;
8332       OldDecl = Previous.getFoundDecl();
8333       MergeTypeWithPrevious = false;
8334 
8335       // ... except in the presence of __attribute__((overloadable)).
8336       if (OldDecl->hasAttr<OverloadableAttr>()) {
8337         if (!getLangOpts().CPlusPlus && !NewFD->hasAttr<OverloadableAttr>()) {
8338           Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
8339             << Redeclaration << NewFD;
8340           Diag(Previous.getFoundDecl()->getLocation(),
8341                diag::note_attribute_overloadable_prev_overload);
8342           NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
8343         }
8344         if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
8345           Redeclaration = false;
8346           OldDecl = nullptr;
8347         }
8348       }
8349     }
8350   }
8351 
8352   // C++11 [dcl.constexpr]p8:
8353   //   A constexpr specifier for a non-static member function that is not
8354   //   a constructor declares that member function to be const.
8355   //
8356   // This needs to be delayed until we know whether this is an out-of-line
8357   // definition of a static member function.
8358   //
8359   // This rule is not present in C++1y, so we produce a backwards
8360   // compatibility warning whenever it happens in C++11.
8361   CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8362   if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
8363       !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
8364       (MD->getTypeQualifiers() & Qualifiers::Const) == 0) {
8365     CXXMethodDecl *OldMD = nullptr;
8366     if (OldDecl)
8367       OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
8368     if (!OldMD || !OldMD->isStatic()) {
8369       const FunctionProtoType *FPT =
8370         MD->getType()->castAs<FunctionProtoType>();
8371       FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8372       EPI.TypeQuals |= Qualifiers::Const;
8373       MD->setType(Context.getFunctionType(FPT->getReturnType(),
8374                                           FPT->getParamTypes(), EPI));
8375 
8376       // Warn that we did this, if we're not performing template instantiation.
8377       // In that case, we'll have warned already when the template was defined.
8378       if (ActiveTemplateInstantiations.empty()) {
8379         SourceLocation AddConstLoc;
8380         if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
8381                 .IgnoreParens().getAs<FunctionTypeLoc>())
8382           AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
8383 
8384         Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
8385           << FixItHint::CreateInsertion(AddConstLoc, " const");
8386       }
8387     }
8388   }
8389 
8390   if (Redeclaration) {
8391     // NewFD and OldDecl represent declarations that need to be
8392     // merged.
8393     if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
8394       NewFD->setInvalidDecl();
8395       return Redeclaration;
8396     }
8397 
8398     Previous.clear();
8399     Previous.addDecl(OldDecl);
8400 
8401     if (FunctionTemplateDecl *OldTemplateDecl
8402                                   = dyn_cast<FunctionTemplateDecl>(OldDecl)) {
8403       NewFD->setPreviousDeclaration(OldTemplateDecl->getTemplatedDecl());
8404       FunctionTemplateDecl *NewTemplateDecl
8405         = NewFD->getDescribedFunctionTemplate();
8406       assert(NewTemplateDecl && "Template/non-template mismatch");
8407       if (CXXMethodDecl *Method
8408             = dyn_cast<CXXMethodDecl>(NewTemplateDecl->getTemplatedDecl())) {
8409         Method->setAccess(OldTemplateDecl->getAccess());
8410         NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
8411       }
8412 
8413       // If this is an explicit specialization of a member that is a function
8414       // template, mark it as a member specialization.
8415       if (IsExplicitSpecialization &&
8416           NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
8417         NewTemplateDecl->setMemberSpecialization();
8418         assert(OldTemplateDecl->isMemberSpecialization());
8419       }
8420 
8421     } else {
8422       // This needs to happen first so that 'inline' propagates.
8423       NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
8424 
8425       if (isa<CXXMethodDecl>(NewFD))
8426         NewFD->setAccess(OldDecl->getAccess());
8427     }
8428   }
8429 
8430   // Semantic checking for this function declaration (in isolation).
8431 
8432   if (getLangOpts().CPlusPlus) {
8433     // C++-specific checks.
8434     if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
8435       CheckConstructor(Constructor);
8436     } else if (CXXDestructorDecl *Destructor =
8437                 dyn_cast<CXXDestructorDecl>(NewFD)) {
8438       CXXRecordDecl *Record = Destructor->getParent();
8439       QualType ClassType = Context.getTypeDeclType(Record);
8440 
8441       // FIXME: Shouldn't we be able to perform this check even when the class
8442       // type is dependent? Both gcc and edg can handle that.
8443       if (!ClassType->isDependentType()) {
8444         DeclarationName Name
8445           = Context.DeclarationNames.getCXXDestructorName(
8446                                         Context.getCanonicalType(ClassType));
8447         if (NewFD->getDeclName() != Name) {
8448           Diag(NewFD->getLocation(), diag::err_destructor_name);
8449           NewFD->setInvalidDecl();
8450           return Redeclaration;
8451         }
8452       }
8453     } else if (CXXConversionDecl *Conversion
8454                = dyn_cast<CXXConversionDecl>(NewFD)) {
8455       ActOnConversionDeclarator(Conversion);
8456     }
8457 
8458     // Find any virtual functions that this function overrides.
8459     if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
8460       if (!Method->isFunctionTemplateSpecialization() &&
8461           !Method->getDescribedFunctionTemplate() &&
8462           Method->isCanonicalDecl()) {
8463         if (AddOverriddenMethods(Method->getParent(), Method)) {
8464           // If the function was marked as "static", we have a problem.
8465           if (NewFD->getStorageClass() == SC_Static) {
8466             ReportOverrides(*this, diag::err_static_overrides_virtual, Method);
8467           }
8468         }
8469       }
8470 
8471       if (Method->isStatic())
8472         checkThisInStaticMemberFunctionType(Method);
8473     }
8474 
8475     // Extra checking for C++ overloaded operators (C++ [over.oper]).
8476     if (NewFD->isOverloadedOperator() &&
8477         CheckOverloadedOperatorDeclaration(NewFD)) {
8478       NewFD->setInvalidDecl();
8479       return Redeclaration;
8480     }
8481 
8482     // Extra checking for C++0x literal operators (C++0x [over.literal]).
8483     if (NewFD->getLiteralIdentifier() &&
8484         CheckLiteralOperatorDeclaration(NewFD)) {
8485       NewFD->setInvalidDecl();
8486       return Redeclaration;
8487     }
8488 
8489     // In C++, check default arguments now that we have merged decls. Unless
8490     // the lexical context is the class, because in this case this is done
8491     // during delayed parsing anyway.
8492     if (!CurContext->isRecord())
8493       CheckCXXDefaultArguments(NewFD);
8494 
8495     // If this function declares a builtin function, check the type of this
8496     // declaration against the expected type for the builtin.
8497     if (unsigned BuiltinID = NewFD->getBuiltinID()) {
8498       ASTContext::GetBuiltinTypeError Error;
8499       LookupPredefedObjCSuperType(*this, S, NewFD->getIdentifier());
8500       QualType T = Context.GetBuiltinType(BuiltinID, Error);
8501       if (!T.isNull() && !Context.hasSameType(T, NewFD->getType())) {
8502         // The type of this function differs from the type of the builtin,
8503         // so forget about the builtin entirely.
8504         Context.BuiltinInfo.forgetBuiltin(BuiltinID, Context.Idents);
8505       }
8506     }
8507 
8508     // If this function is declared as being extern "C", then check to see if
8509     // the function returns a UDT (class, struct, or union type) that is not C
8510     // compatible, and if it does, warn the user.
8511     // But, issue any diagnostic on the first declaration only.
8512     if (Previous.empty() && NewFD->isExternC()) {
8513       QualType R = NewFD->getReturnType();
8514       if (R->isIncompleteType() && !R->isVoidType())
8515         Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
8516             << NewFD << R;
8517       else if (!R.isPODType(Context) && !R->isVoidType() &&
8518                !R->isObjCObjectPointerType())
8519         Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
8520     }
8521   }
8522   return Redeclaration;
8523 }
8524 
8525 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
8526   // C++11 [basic.start.main]p3:
8527   //   A program that [...] declares main to be inline, static or
8528   //   constexpr is ill-formed.
8529   // C11 6.7.4p4:  In a hosted environment, no function specifier(s) shall
8530   //   appear in a declaration of main.
8531   // static main is not an error under C99, but we should warn about it.
8532   // We accept _Noreturn main as an extension.
8533   if (FD->getStorageClass() == SC_Static)
8534     Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
8535          ? diag::err_static_main : diag::warn_static_main)
8536       << FixItHint::CreateRemoval(DS.getStorageClassSpecLoc());
8537   if (FD->isInlineSpecified())
8538     Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
8539       << FixItHint::CreateRemoval(DS.getInlineSpecLoc());
8540   if (DS.isNoreturnSpecified()) {
8541     SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
8542     SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
8543     Diag(NoreturnLoc, diag::ext_noreturn_main);
8544     Diag(NoreturnLoc, diag::note_main_remove_noreturn)
8545       << FixItHint::CreateRemoval(NoreturnRange);
8546   }
8547   if (FD->isConstexpr()) {
8548     Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
8549       << FixItHint::CreateRemoval(DS.getConstexprSpecLoc());
8550     FD->setConstexpr(false);
8551   }
8552 
8553   if (getLangOpts().OpenCL) {
8554     Diag(FD->getLocation(), diag::err_opencl_no_main)
8555         << FD->hasAttr<OpenCLKernelAttr>();
8556     FD->setInvalidDecl();
8557     return;
8558   }
8559 
8560   QualType T = FD->getType();
8561   assert(T->isFunctionType() && "function decl is not of function type");
8562   const FunctionType* FT = T->castAs<FunctionType>();
8563 
8564   if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
8565     // In C with GNU extensions we allow main() to have non-integer return
8566     // type, but we should warn about the extension, and we disable the
8567     // implicit-return-zero rule.
8568 
8569     // GCC in C mode accepts qualified 'int'.
8570     if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
8571       FD->setHasImplicitReturnZero(true);
8572     else {
8573       Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
8574       SourceRange RTRange = FD->getReturnTypeSourceRange();
8575       if (RTRange.isValid())
8576         Diag(RTRange.getBegin(), diag::note_main_change_return_type)
8577             << FixItHint::CreateReplacement(RTRange, "int");
8578     }
8579   } else {
8580     // In C and C++, main magically returns 0 if you fall off the end;
8581     // set the flag which tells us that.
8582     // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
8583 
8584     // All the standards say that main() should return 'int'.
8585     if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
8586       FD->setHasImplicitReturnZero(true);
8587     else {
8588       // Otherwise, this is just a flat-out error.
8589       SourceRange RTRange = FD->getReturnTypeSourceRange();
8590       Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
8591           << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
8592                                 : FixItHint());
8593       FD->setInvalidDecl(true);
8594     }
8595   }
8596 
8597   // Treat protoless main() as nullary.
8598   if (isa<FunctionNoProtoType>(FT)) return;
8599 
8600   const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
8601   unsigned nparams = FTP->getNumParams();
8602   assert(FD->getNumParams() == nparams);
8603 
8604   bool HasExtraParameters = (nparams > 3);
8605 
8606   if (FTP->isVariadic()) {
8607     Diag(FD->getLocation(), diag::ext_variadic_main);
8608     // FIXME: if we had information about the location of the ellipsis, we
8609     // could add a FixIt hint to remove it as a parameter.
8610   }
8611 
8612   // Darwin passes an undocumented fourth argument of type char**.  If
8613   // other platforms start sprouting these, the logic below will start
8614   // getting shifty.
8615   if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
8616     HasExtraParameters = false;
8617 
8618   if (HasExtraParameters) {
8619     Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
8620     FD->setInvalidDecl(true);
8621     nparams = 3;
8622   }
8623 
8624   // FIXME: a lot of the following diagnostics would be improved
8625   // if we had some location information about types.
8626 
8627   QualType CharPP =
8628     Context.getPointerType(Context.getPointerType(Context.CharTy));
8629   QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
8630 
8631   for (unsigned i = 0; i < nparams; ++i) {
8632     QualType AT = FTP->getParamType(i);
8633 
8634     bool mismatch = true;
8635 
8636     if (Context.hasSameUnqualifiedType(AT, Expected[i]))
8637       mismatch = false;
8638     else if (Expected[i] == CharPP) {
8639       // As an extension, the following forms are okay:
8640       //   char const **
8641       //   char const * const *
8642       //   char * const *
8643 
8644       QualifierCollector qs;
8645       const PointerType* PT;
8646       if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
8647           (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
8648           Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
8649                               Context.CharTy)) {
8650         qs.removeConst();
8651         mismatch = !qs.empty();
8652       }
8653     }
8654 
8655     if (mismatch) {
8656       Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
8657       // TODO: suggest replacing given type with expected type
8658       FD->setInvalidDecl(true);
8659     }
8660   }
8661 
8662   if (nparams == 1 && !FD->isInvalidDecl()) {
8663     Diag(FD->getLocation(), diag::warn_main_one_arg);
8664   }
8665 
8666   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8667     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8668     FD->setInvalidDecl();
8669   }
8670 }
8671 
8672 void Sema::CheckMSVCRTEntryPoint(FunctionDecl *FD) {
8673   QualType T = FD->getType();
8674   assert(T->isFunctionType() && "function decl is not of function type");
8675   const FunctionType *FT = T->castAs<FunctionType>();
8676 
8677   // Set an implicit return of 'zero' if the function can return some integral,
8678   // enumeration, pointer or nullptr type.
8679   if (FT->getReturnType()->isIntegralOrEnumerationType() ||
8680       FT->getReturnType()->isAnyPointerType() ||
8681       FT->getReturnType()->isNullPtrType())
8682     // DllMain is exempt because a return value of zero means it failed.
8683     if (FD->getName() != "DllMain")
8684       FD->setHasImplicitReturnZero(true);
8685 
8686   if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
8687     Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
8688     FD->setInvalidDecl();
8689   }
8690 }
8691 
8692 bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
8693   // FIXME: Need strict checking.  In C89, we need to check for
8694   // any assignment, increment, decrement, function-calls, or
8695   // commas outside of a sizeof.  In C99, it's the same list,
8696   // except that the aforementioned are allowed in unevaluated
8697   // expressions.  Everything else falls under the
8698   // "may accept other forms of constant expressions" exception.
8699   // (We never end up here for C++, so the constant expression
8700   // rules there don't matter.)
8701   const Expr *Culprit;
8702   if (Init->isConstantInitializer(Context, false, &Culprit))
8703     return false;
8704   Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
8705     << Culprit->getSourceRange();
8706   return true;
8707 }
8708 
8709 namespace {
8710   // Visits an initialization expression to see if OrigDecl is evaluated in
8711   // its own initialization and throws a warning if it does.
8712   class SelfReferenceChecker
8713       : public EvaluatedExprVisitor<SelfReferenceChecker> {
8714     Sema &S;
8715     Decl *OrigDecl;
8716     bool isRecordType;
8717     bool isPODType;
8718     bool isReferenceType;
8719 
8720     bool isInitList;
8721     llvm::SmallVector<unsigned, 4> InitFieldIndex;
8722   public:
8723     typedef EvaluatedExprVisitor<SelfReferenceChecker> Inherited;
8724 
8725     SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
8726                                                     S(S), OrigDecl(OrigDecl) {
8727       isPODType = false;
8728       isRecordType = false;
8729       isReferenceType = false;
8730       isInitList = false;
8731       if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
8732         isPODType = VD->getType().isPODType(S.Context);
8733         isRecordType = VD->getType()->isRecordType();
8734         isReferenceType = VD->getType()->isReferenceType();
8735       }
8736     }
8737 
8738     // For most expressions, just call the visitor.  For initializer lists,
8739     // track the index of the field being initialized since fields are
8740     // initialized in order allowing use of previously initialized fields.
8741     void CheckExpr(Expr *E) {
8742       InitListExpr *InitList = dyn_cast<InitListExpr>(E);
8743       if (!InitList) {
8744         Visit(E);
8745         return;
8746       }
8747 
8748       // Track and increment the index here.
8749       isInitList = true;
8750       InitFieldIndex.push_back(0);
8751       for (auto Child : InitList->children()) {
8752         CheckExpr(cast<Expr>(Child));
8753         ++InitFieldIndex.back();
8754       }
8755       InitFieldIndex.pop_back();
8756     }
8757 
8758     // Returns true if MemberExpr is checked and no futher checking is needed.
8759     // Returns false if additional checking is required.
8760     bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
8761       llvm::SmallVector<FieldDecl*, 4> Fields;
8762       Expr *Base = E;
8763       bool ReferenceField = false;
8764 
8765       // Get the field memebers used.
8766       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8767         FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
8768         if (!FD)
8769           return false;
8770         Fields.push_back(FD);
8771         if (FD->getType()->isReferenceType())
8772           ReferenceField = true;
8773         Base = ME->getBase()->IgnoreParenImpCasts();
8774       }
8775 
8776       // Keep checking only if the base Decl is the same.
8777       DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
8778       if (!DRE || DRE->getDecl() != OrigDecl)
8779         return false;
8780 
8781       // A reference field can be bound to an unininitialized field.
8782       if (CheckReference && !ReferenceField)
8783         return true;
8784 
8785       // Convert FieldDecls to their index number.
8786       llvm::SmallVector<unsigned, 4> UsedFieldIndex;
8787       for (const FieldDecl *I : llvm::reverse(Fields))
8788         UsedFieldIndex.push_back(I->getFieldIndex());
8789 
8790       // See if a warning is needed by checking the first difference in index
8791       // numbers.  If field being used has index less than the field being
8792       // initialized, then the use is safe.
8793       for (auto UsedIter = UsedFieldIndex.begin(),
8794                 UsedEnd = UsedFieldIndex.end(),
8795                 OrigIter = InitFieldIndex.begin(),
8796                 OrigEnd = InitFieldIndex.end();
8797            UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
8798         if (*UsedIter < *OrigIter)
8799           return true;
8800         if (*UsedIter > *OrigIter)
8801           break;
8802       }
8803 
8804       // TODO: Add a different warning which will print the field names.
8805       HandleDeclRefExpr(DRE);
8806       return true;
8807     }
8808 
8809     // For most expressions, the cast is directly above the DeclRefExpr.
8810     // For conditional operators, the cast can be outside the conditional
8811     // operator if both expressions are DeclRefExpr's.
8812     void HandleValue(Expr *E) {
8813       E = E->IgnoreParens();
8814       if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
8815         HandleDeclRefExpr(DRE);
8816         return;
8817       }
8818 
8819       if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8820         Visit(CO->getCond());
8821         HandleValue(CO->getTrueExpr());
8822         HandleValue(CO->getFalseExpr());
8823         return;
8824       }
8825 
8826       if (BinaryConditionalOperator *BCO =
8827               dyn_cast<BinaryConditionalOperator>(E)) {
8828         Visit(BCO->getCond());
8829         HandleValue(BCO->getFalseExpr());
8830         return;
8831       }
8832 
8833       if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
8834         HandleValue(OVE->getSourceExpr());
8835         return;
8836       }
8837 
8838       if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
8839         if (BO->getOpcode() == BO_Comma) {
8840           Visit(BO->getLHS());
8841           HandleValue(BO->getRHS());
8842           return;
8843         }
8844       }
8845 
8846       if (isa<MemberExpr>(E)) {
8847         if (isInitList) {
8848           if (CheckInitListMemberExpr(cast<MemberExpr>(E),
8849                                       false /*CheckReference*/))
8850             return;
8851         }
8852 
8853         Expr *Base = E->IgnoreParenImpCasts();
8854         while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8855           // Check for static member variables and don't warn on them.
8856           if (!isa<FieldDecl>(ME->getMemberDecl()))
8857             return;
8858           Base = ME->getBase()->IgnoreParenImpCasts();
8859         }
8860         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
8861           HandleDeclRefExpr(DRE);
8862         return;
8863       }
8864 
8865       Visit(E);
8866     }
8867 
8868     // Reference types not handled in HandleValue are handled here since all
8869     // uses of references are bad, not just r-value uses.
8870     void VisitDeclRefExpr(DeclRefExpr *E) {
8871       if (isReferenceType)
8872         HandleDeclRefExpr(E);
8873     }
8874 
8875     void VisitImplicitCastExpr(ImplicitCastExpr *E) {
8876       if (E->getCastKind() == CK_LValueToRValue) {
8877         HandleValue(E->getSubExpr());
8878         return;
8879       }
8880 
8881       Inherited::VisitImplicitCastExpr(E);
8882     }
8883 
8884     void VisitMemberExpr(MemberExpr *E) {
8885       if (isInitList) {
8886         if (CheckInitListMemberExpr(E, true /*CheckReference*/))
8887           return;
8888       }
8889 
8890       // Don't warn on arrays since they can be treated as pointers.
8891       if (E->getType()->canDecayToPointerType()) return;
8892 
8893       // Warn when a non-static method call is followed by non-static member
8894       // field accesses, which is followed by a DeclRefExpr.
8895       CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
8896       bool Warn = (MD && !MD->isStatic());
8897       Expr *Base = E->getBase()->IgnoreParenImpCasts();
8898       while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
8899         if (!isa<FieldDecl>(ME->getMemberDecl()))
8900           Warn = false;
8901         Base = ME->getBase()->IgnoreParenImpCasts();
8902       }
8903 
8904       if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
8905         if (Warn)
8906           HandleDeclRefExpr(DRE);
8907         return;
8908       }
8909 
8910       // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
8911       // Visit that expression.
8912       Visit(Base);
8913     }
8914 
8915     void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
8916       Expr *Callee = E->getCallee();
8917 
8918       if (isa<UnresolvedLookupExpr>(Callee))
8919         return Inherited::VisitCXXOperatorCallExpr(E);
8920 
8921       Visit(Callee);
8922       for (auto Arg: E->arguments())
8923         HandleValue(Arg->IgnoreParenImpCasts());
8924     }
8925 
8926     void VisitUnaryOperator(UnaryOperator *E) {
8927       // For POD record types, addresses of its own members are well-defined.
8928       if (E->getOpcode() == UO_AddrOf && isRecordType &&
8929           isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
8930         if (!isPODType)
8931           HandleValue(E->getSubExpr());
8932         return;
8933       }
8934 
8935       if (E->isIncrementDecrementOp()) {
8936         HandleValue(E->getSubExpr());
8937         return;
8938       }
8939 
8940       Inherited::VisitUnaryOperator(E);
8941     }
8942 
8943     void VisitObjCMessageExpr(ObjCMessageExpr *E) { return; }
8944 
8945     void VisitCXXConstructExpr(CXXConstructExpr *E) {
8946       if (E->getConstructor()->isCopyConstructor()) {
8947         Expr *ArgExpr = E->getArg(0);
8948         if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
8949           if (ILE->getNumInits() == 1)
8950             ArgExpr = ILE->getInit(0);
8951         if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
8952           if (ICE->getCastKind() == CK_NoOp)
8953             ArgExpr = ICE->getSubExpr();
8954         HandleValue(ArgExpr);
8955         return;
8956       }
8957       Inherited::VisitCXXConstructExpr(E);
8958     }
8959 
8960     void VisitCallExpr(CallExpr *E) {
8961       // Treat std::move as a use.
8962       if (E->getNumArgs() == 1) {
8963         if (FunctionDecl *FD = E->getDirectCallee()) {
8964           if (FD->isInStdNamespace() && FD->getIdentifier() &&
8965               FD->getIdentifier()->isStr("move")) {
8966             HandleValue(E->getArg(0));
8967             return;
8968           }
8969         }
8970       }
8971 
8972       Inherited::VisitCallExpr(E);
8973     }
8974 
8975     void VisitBinaryOperator(BinaryOperator *E) {
8976       if (E->isCompoundAssignmentOp()) {
8977         HandleValue(E->getLHS());
8978         Visit(E->getRHS());
8979         return;
8980       }
8981 
8982       Inherited::VisitBinaryOperator(E);
8983     }
8984 
8985     // A custom visitor for BinaryConditionalOperator is needed because the
8986     // regular visitor would check the condition and true expression separately
8987     // but both point to the same place giving duplicate diagnostics.
8988     void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
8989       Visit(E->getCond());
8990       Visit(E->getFalseExpr());
8991     }
8992 
8993     void HandleDeclRefExpr(DeclRefExpr *DRE) {
8994       Decl* ReferenceDecl = DRE->getDecl();
8995       if (OrigDecl != ReferenceDecl) return;
8996       unsigned diag;
8997       if (isReferenceType) {
8998         diag = diag::warn_uninit_self_reference_in_reference_init;
8999       } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
9000         diag = diag::warn_static_self_reference_in_init;
9001       } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
9002                  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
9003                  DRE->getDecl()->getType()->isRecordType()) {
9004         diag = diag::warn_uninit_self_reference_in_init;
9005       } else {
9006         // Local variables will be handled by the CFG analysis.
9007         return;
9008       }
9009 
9010       S.DiagRuntimeBehavior(DRE->getLocStart(), DRE,
9011                             S.PDiag(diag)
9012                               << DRE->getNameInfo().getName()
9013                               << OrigDecl->getLocation()
9014                               << DRE->getSourceRange());
9015     }
9016   };
9017 
9018   /// CheckSelfReference - Warns if OrigDecl is used in expression E.
9019   static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
9020                                  bool DirectInit) {
9021     // Parameters arguments are occassionially constructed with itself,
9022     // for instance, in recursive functions.  Skip them.
9023     if (isa<ParmVarDecl>(OrigDecl))
9024       return;
9025 
9026     E = E->IgnoreParens();
9027 
9028     // Skip checking T a = a where T is not a record or reference type.
9029     // Doing so is a way to silence uninitialized warnings.
9030     if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
9031       if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
9032         if (ICE->getCastKind() == CK_LValueToRValue)
9033           if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
9034             if (DRE->getDecl() == OrigDecl)
9035               return;
9036 
9037     SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
9038   }
9039 }
9040 
9041 QualType Sema::deduceVarTypeFromInitializer(VarDecl *VDecl,
9042                                             DeclarationName Name, QualType Type,
9043                                             TypeSourceInfo *TSI,
9044                                             SourceRange Range, bool DirectInit,
9045                                             Expr *Init) {
9046   bool IsInitCapture = !VDecl;
9047   assert((!VDecl || !VDecl->isInitCapture()) &&
9048          "init captures are expected to be deduced prior to initialization");
9049 
9050   ArrayRef<Expr *> DeduceInits = Init;
9051   if (DirectInit) {
9052     if (auto *PL = dyn_cast<ParenListExpr>(Init))
9053       DeduceInits = PL->exprs();
9054     else if (auto *IL = dyn_cast<InitListExpr>(Init))
9055       DeduceInits = IL->inits();
9056   }
9057 
9058   // Deduction only works if we have exactly one source expression.
9059   if (DeduceInits.empty()) {
9060     // It isn't possible to write this directly, but it is possible to
9061     // end up in this situation with "auto x(some_pack...);"
9062     Diag(Init->getLocStart(), IsInitCapture
9063                                   ? diag::err_init_capture_no_expression
9064                                   : diag::err_auto_var_init_no_expression)
9065         << Name << Type << Range;
9066     return QualType();
9067   }
9068 
9069   if (DeduceInits.size() > 1) {
9070     Diag(DeduceInits[1]->getLocStart(),
9071          IsInitCapture ? diag::err_init_capture_multiple_expressions
9072                        : diag::err_auto_var_init_multiple_expressions)
9073         << Name << Type << Range;
9074     return QualType();
9075   }
9076 
9077   Expr *DeduceInit = DeduceInits[0];
9078   if (DirectInit && isa<InitListExpr>(DeduceInit)) {
9079     Diag(Init->getLocStart(), IsInitCapture
9080                                   ? diag::err_init_capture_paren_braces
9081                                   : diag::err_auto_var_init_paren_braces)
9082         << isa<InitListExpr>(Init) << Name << Type << Range;
9083     return QualType();
9084   }
9085 
9086   // Expressions default to 'id' when we're in a debugger.
9087   bool DefaultedAnyToId = false;
9088   if (getLangOpts().DebuggerCastResultToId &&
9089       Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
9090     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9091     if (Result.isInvalid()) {
9092       return QualType();
9093     }
9094     Init = Result.get();
9095     DefaultedAnyToId = true;
9096   }
9097 
9098   QualType DeducedType;
9099   if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
9100     if (!IsInitCapture)
9101       DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
9102     else if (isa<InitListExpr>(Init))
9103       Diag(Range.getBegin(),
9104            diag::err_init_capture_deduction_failure_from_init_list)
9105           << Name
9106           << (DeduceInit->getType().isNull() ? TSI->getType()
9107                                              : DeduceInit->getType())
9108           << DeduceInit->getSourceRange();
9109     else
9110       Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
9111           << Name << TSI->getType()
9112           << (DeduceInit->getType().isNull() ? TSI->getType()
9113                                              : DeduceInit->getType())
9114           << DeduceInit->getSourceRange();
9115   }
9116 
9117   // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
9118   // 'id' instead of a specific object type prevents most of our usual
9119   // checks.
9120   // We only want to warn outside of template instantiations, though:
9121   // inside a template, the 'id' could have come from a parameter.
9122   if (ActiveTemplateInstantiations.empty() && !DefaultedAnyToId &&
9123       !IsInitCapture && !DeducedType.isNull() && DeducedType->isObjCIdType()) {
9124     SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
9125     Diag(Loc, diag::warn_auto_var_is_id) << Name << Range;
9126   }
9127 
9128   return DeducedType;
9129 }
9130 
9131 /// AddInitializerToDecl - Adds the initializer Init to the
9132 /// declaration dcl. If DirectInit is true, this is C++ direct
9133 /// initialization rather than copy initialization.
9134 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init,
9135                                 bool DirectInit, bool TypeMayContainAuto) {
9136   // If there is no declaration, there was an error parsing it.  Just ignore
9137   // the initializer.
9138   if (!RealDecl || RealDecl->isInvalidDecl()) {
9139     CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
9140     return;
9141   }
9142 
9143   if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
9144     // Pure-specifiers are handled in ActOnPureSpecifier.
9145     Diag(Method->getLocation(), diag::err_member_function_initialization)
9146       << Method->getDeclName() << Init->getSourceRange();
9147     Method->setInvalidDecl();
9148     return;
9149   }
9150 
9151   VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
9152   if (!VDecl) {
9153     assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
9154     Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
9155     RealDecl->setInvalidDecl();
9156     return;
9157   }
9158 
9159   // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
9160   if (TypeMayContainAuto && VDecl->getType()->isUndeducedType()) {
9161     // Attempt typo correction early so that the type of the init expression can
9162     // be deduced based on the chosen correction if the original init contains a
9163     // TypoExpr.
9164     ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
9165     if (!Res.isUsable()) {
9166       RealDecl->setInvalidDecl();
9167       return;
9168     }
9169     Init = Res.get();
9170 
9171     QualType DeducedType = deduceVarTypeFromInitializer(
9172         VDecl, VDecl->getDeclName(), VDecl->getType(),
9173         VDecl->getTypeSourceInfo(), VDecl->getSourceRange(), DirectInit, Init);
9174     if (DeducedType.isNull()) {
9175       RealDecl->setInvalidDecl();
9176       return;
9177     }
9178 
9179     VDecl->setType(DeducedType);
9180     assert(VDecl->isLinkageValid());
9181 
9182     // In ARC, infer lifetime.
9183     if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
9184       VDecl->setInvalidDecl();
9185 
9186     // If this is a redeclaration, check that the type we just deduced matches
9187     // the previously declared type.
9188     if (VarDecl *Old = VDecl->getPreviousDecl()) {
9189       // We never need to merge the type, because we cannot form an incomplete
9190       // array of auto, nor deduce such a type.
9191       MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
9192     }
9193 
9194     // Check the deduced type is valid for a variable declaration.
9195     CheckVariableDeclarationType(VDecl);
9196     if (VDecl->isInvalidDecl())
9197       return;
9198   }
9199 
9200   // dllimport cannot be used on variable definitions.
9201   if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
9202     Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
9203     VDecl->setInvalidDecl();
9204     return;
9205   }
9206 
9207   if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
9208     // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
9209     Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
9210     VDecl->setInvalidDecl();
9211     return;
9212   }
9213 
9214   if (!VDecl->getType()->isDependentType()) {
9215     // A definition must end up with a complete type, which means it must be
9216     // complete with the restriction that an array type might be completed by
9217     // the initializer; note that later code assumes this restriction.
9218     QualType BaseDeclType = VDecl->getType();
9219     if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
9220       BaseDeclType = Array->getElementType();
9221     if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
9222                             diag::err_typecheck_decl_incomplete_type)) {
9223       RealDecl->setInvalidDecl();
9224       return;
9225     }
9226 
9227     // The variable can not have an abstract class type.
9228     if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
9229                                diag::err_abstract_type_in_decl,
9230                                AbstractVariableType))
9231       VDecl->setInvalidDecl();
9232   }
9233 
9234   VarDecl *Def;
9235   if ((Def = VDecl->getDefinition()) && Def != VDecl) {
9236     NamedDecl *Hidden = nullptr;
9237     if (!hasVisibleDefinition(Def, &Hidden) &&
9238         (VDecl->getFormalLinkage() == InternalLinkage ||
9239          VDecl->getDescribedVarTemplate() ||
9240          VDecl->getNumTemplateParameterLists() ||
9241          VDecl->getDeclContext()->isDependentContext())) {
9242       // The previous definition is hidden, and multiple definitions are
9243       // permitted (in separate TUs). Form another definition of it.
9244     } else {
9245       Diag(VDecl->getLocation(), diag::err_redefinition)
9246         << VDecl->getDeclName();
9247       Diag(Def->getLocation(), diag::note_previous_definition);
9248       VDecl->setInvalidDecl();
9249       return;
9250     }
9251   }
9252 
9253   if (getLangOpts().CPlusPlus) {
9254     // C++ [class.static.data]p4
9255     //   If a static data member is of const integral or const
9256     //   enumeration type, its declaration in the class definition can
9257     //   specify a constant-initializer which shall be an integral
9258     //   constant expression (5.19). In that case, the member can appear
9259     //   in integral constant expressions. The member shall still be
9260     //   defined in a namespace scope if it is used in the program and the
9261     //   namespace scope definition shall not contain an initializer.
9262     //
9263     // We already performed a redefinition check above, but for static
9264     // data members we also need to check whether there was an in-class
9265     // declaration with an initializer.
9266     if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
9267       Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
9268           << VDecl->getDeclName();
9269       Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
9270            diag::note_previous_initializer)
9271           << 0;
9272       return;
9273     }
9274 
9275     if (VDecl->hasLocalStorage())
9276       getCurFunction()->setHasBranchProtectedScope();
9277 
9278     if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
9279       VDecl->setInvalidDecl();
9280       return;
9281     }
9282   }
9283 
9284   // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
9285   // a kernel function cannot be initialized."
9286   if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
9287     Diag(VDecl->getLocation(), diag::err_local_cant_init);
9288     VDecl->setInvalidDecl();
9289     return;
9290   }
9291 
9292   // Get the decls type and save a reference for later, since
9293   // CheckInitializerTypes may change it.
9294   QualType DclT = VDecl->getType(), SavT = DclT;
9295 
9296   // Expressions default to 'id' when we're in a debugger
9297   // and we are assigning it to a variable of Objective-C pointer type.
9298   if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
9299       Init->getType() == Context.UnknownAnyTy) {
9300     ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
9301     if (Result.isInvalid()) {
9302       VDecl->setInvalidDecl();
9303       return;
9304     }
9305     Init = Result.get();
9306   }
9307 
9308   // Perform the initialization.
9309   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
9310   if (!VDecl->isInvalidDecl()) {
9311     InitializedEntity Entity = InitializedEntity::InitializeVariable(VDecl);
9312     InitializationKind Kind =
9313         DirectInit
9314             ? CXXDirectInit
9315                   ? InitializationKind::CreateDirect(VDecl->getLocation(),
9316                                                      Init->getLocStart(),
9317                                                      Init->getLocEnd())
9318                   : InitializationKind::CreateDirectList(VDecl->getLocation())
9319             : InitializationKind::CreateCopy(VDecl->getLocation(),
9320                                              Init->getLocStart());
9321 
9322     MultiExprArg Args = Init;
9323     if (CXXDirectInit)
9324       Args = MultiExprArg(CXXDirectInit->getExprs(),
9325                           CXXDirectInit->getNumExprs());
9326 
9327     // Try to correct any TypoExprs in the initialization arguments.
9328     for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
9329       ExprResult Res = CorrectDelayedTyposInExpr(
9330           Args[Idx], VDecl, [this, Entity, Kind](Expr *E) {
9331             InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
9332             return Init.Failed() ? ExprError() : E;
9333           });
9334       if (Res.isInvalid()) {
9335         VDecl->setInvalidDecl();
9336       } else if (Res.get() != Args[Idx]) {
9337         Args[Idx] = Res.get();
9338       }
9339     }
9340     if (VDecl->isInvalidDecl())
9341       return;
9342 
9343     InitializationSequence InitSeq(*this, Entity, Kind, Args);
9344     ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
9345     if (Result.isInvalid()) {
9346       VDecl->setInvalidDecl();
9347       return;
9348     }
9349 
9350     Init = Result.getAs<Expr>();
9351   }
9352 
9353   // Check for self-references within variable initializers.
9354   // Variables declared within a function/method body (except for references)
9355   // are handled by a dataflow analysis.
9356   if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
9357       VDecl->getType()->isReferenceType()) {
9358     CheckSelfReference(*this, RealDecl, Init, DirectInit);
9359   }
9360 
9361   // If the type changed, it means we had an incomplete type that was
9362   // completed by the initializer. For example:
9363   //   int ary[] = { 1, 3, 5 };
9364   // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
9365   if (!VDecl->isInvalidDecl() && (DclT != SavT))
9366     VDecl->setType(DclT);
9367 
9368   if (!VDecl->isInvalidDecl()) {
9369     checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
9370 
9371     if (VDecl->hasAttr<BlocksAttr>())
9372       checkRetainCycles(VDecl, Init);
9373 
9374     // It is safe to assign a weak reference into a strong variable.
9375     // Although this code can still have problems:
9376     //   id x = self.weakProp;
9377     //   id y = self.weakProp;
9378     // we do not warn to warn spuriously when 'x' and 'y' are on separate
9379     // paths through the function. This should be revisited if
9380     // -Wrepeated-use-of-weak is made flow-sensitive.
9381     if (VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong &&
9382         !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
9383                          Init->getLocStart()))
9384       getCurFunction()->markSafeWeakUse(Init);
9385   }
9386 
9387   // The initialization is usually a full-expression.
9388   //
9389   // FIXME: If this is a braced initialization of an aggregate, it is not
9390   // an expression, and each individual field initializer is a separate
9391   // full-expression. For instance, in:
9392   //
9393   //   struct Temp { ~Temp(); };
9394   //   struct S { S(Temp); };
9395   //   struct T { S a, b; } t = { Temp(), Temp() }
9396   //
9397   // we should destroy the first Temp before constructing the second.
9398   ExprResult Result = ActOnFinishFullExpr(Init, VDecl->getLocation(),
9399                                           false,
9400                                           VDecl->isConstexpr());
9401   if (Result.isInvalid()) {
9402     VDecl->setInvalidDecl();
9403     return;
9404   }
9405   Init = Result.get();
9406 
9407   // Attach the initializer to the decl.
9408   VDecl->setInit(Init);
9409 
9410   if (VDecl->isLocalVarDecl()) {
9411     // C99 6.7.8p4: All the expressions in an initializer for an object that has
9412     // static storage duration shall be constant expressions or string literals.
9413     // C++ does not have this restriction.
9414     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl()) {
9415       const Expr *Culprit;
9416       if (VDecl->getStorageClass() == SC_Static)
9417         CheckForConstantInitializer(Init, DclT);
9418       // C89 is stricter than C99 for non-static aggregate types.
9419       // C89 6.5.7p3: All the expressions [...] in an initializer list
9420       // for an object that has aggregate or union type shall be
9421       // constant expressions.
9422       else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
9423                isa<InitListExpr>(Init) &&
9424                !Init->isConstantInitializer(Context, false, &Culprit))
9425         Diag(Culprit->getExprLoc(),
9426              diag::ext_aggregate_init_not_constant)
9427           << Culprit->getSourceRange();
9428     }
9429   } else if (VDecl->isStaticDataMember() &&
9430              VDecl->getLexicalDeclContext()->isRecord()) {
9431     // This is an in-class initialization for a static data member, e.g.,
9432     //
9433     // struct S {
9434     //   static const int value = 17;
9435     // };
9436 
9437     // C++ [class.mem]p4:
9438     //   A member-declarator can contain a constant-initializer only
9439     //   if it declares a static member (9.4) of const integral or
9440     //   const enumeration type, see 9.4.2.
9441     //
9442     // C++11 [class.static.data]p3:
9443     //   If a non-volatile const static data member is of integral or
9444     //   enumeration type, its declaration in the class definition can
9445     //   specify a brace-or-equal-initializer in which every initalizer-clause
9446     //   that is an assignment-expression is a constant expression. A static
9447     //   data member of literal type can be declared in the class definition
9448     //   with the constexpr specifier; if so, its declaration shall specify a
9449     //   brace-or-equal-initializer in which every initializer-clause that is
9450     //   an assignment-expression is a constant expression.
9451 
9452     // Do nothing on dependent types.
9453     if (DclT->isDependentType()) {
9454 
9455     // Allow any 'static constexpr' members, whether or not they are of literal
9456     // type. We separately check that every constexpr variable is of literal
9457     // type.
9458     } else if (VDecl->isConstexpr()) {
9459 
9460     // Require constness.
9461     } else if (!DclT.isConstQualified()) {
9462       Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
9463         << Init->getSourceRange();
9464       VDecl->setInvalidDecl();
9465 
9466     // We allow integer constant expressions in all cases.
9467     } else if (DclT->isIntegralOrEnumerationType()) {
9468       // Check whether the expression is a constant expression.
9469       SourceLocation Loc;
9470       if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
9471         // In C++11, a non-constexpr const static data member with an
9472         // in-class initializer cannot be volatile.
9473         Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
9474       else if (Init->isValueDependent())
9475         ; // Nothing to check.
9476       else if (Init->isIntegerConstantExpr(Context, &Loc))
9477         ; // Ok, it's an ICE!
9478       else if (Init->isEvaluatable(Context)) {
9479         // If we can constant fold the initializer through heroics, accept it,
9480         // but report this as a use of an extension for -pedantic.
9481         Diag(Loc, diag::ext_in_class_initializer_non_constant)
9482           << Init->getSourceRange();
9483       } else {
9484         // Otherwise, this is some crazy unknown case.  Report the issue at the
9485         // location provided by the isIntegerConstantExpr failed check.
9486         Diag(Loc, diag::err_in_class_initializer_non_constant)
9487           << Init->getSourceRange();
9488         VDecl->setInvalidDecl();
9489       }
9490 
9491     // We allow foldable floating-point constants as an extension.
9492     } else if (DclT->isFloatingType()) { // also permits complex, which is ok
9493       // In C++98, this is a GNU extension. In C++11, it is not, but we support
9494       // it anyway and provide a fixit to add the 'constexpr'.
9495       if (getLangOpts().CPlusPlus11) {
9496         Diag(VDecl->getLocation(),
9497              diag::ext_in_class_initializer_float_type_cxx11)
9498             << DclT << Init->getSourceRange();
9499         Diag(VDecl->getLocStart(),
9500              diag::note_in_class_initializer_float_type_cxx11)
9501             << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9502       } else {
9503         Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
9504           << DclT << Init->getSourceRange();
9505 
9506         if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
9507           Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
9508             << Init->getSourceRange();
9509           VDecl->setInvalidDecl();
9510         }
9511       }
9512 
9513     // Suggest adding 'constexpr' in C++11 for literal types.
9514     } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
9515       Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
9516         << DclT << Init->getSourceRange()
9517         << FixItHint::CreateInsertion(VDecl->getLocStart(), "constexpr ");
9518       VDecl->setConstexpr(true);
9519 
9520     } else {
9521       Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
9522         << DclT << Init->getSourceRange();
9523       VDecl->setInvalidDecl();
9524     }
9525   } else if (VDecl->isFileVarDecl()) {
9526     if (VDecl->getStorageClass() == SC_Extern &&
9527         (!getLangOpts().CPlusPlus ||
9528          !(Context.getBaseElementType(VDecl->getType()).isConstQualified() ||
9529            VDecl->isExternC())) &&
9530         !isTemplateInstantiation(VDecl->getTemplateSpecializationKind()))
9531       Diag(VDecl->getLocation(), diag::warn_extern_init);
9532 
9533     // C99 6.7.8p4. All file scoped initializers need to be constant.
9534     if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
9535       CheckForConstantInitializer(Init, DclT);
9536   }
9537 
9538   // We will represent direct-initialization similarly to copy-initialization:
9539   //    int x(1);  -as-> int x = 1;
9540   //    ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
9541   //
9542   // Clients that want to distinguish between the two forms, can check for
9543   // direct initializer using VarDecl::getInitStyle().
9544   // A major benefit is that clients that don't particularly care about which
9545   // exactly form was it (like the CodeGen) can handle both cases without
9546   // special case code.
9547 
9548   // C++ 8.5p11:
9549   // The form of initialization (using parentheses or '=') is generally
9550   // insignificant, but does matter when the entity being initialized has a
9551   // class type.
9552   if (CXXDirectInit) {
9553     assert(DirectInit && "Call-style initializer must be direct init.");
9554     VDecl->setInitStyle(VarDecl::CallInit);
9555   } else if (DirectInit) {
9556     // This must be list-initialization. No other way is direct-initialization.
9557     VDecl->setInitStyle(VarDecl::ListInit);
9558   }
9559 
9560   CheckCompleteVariableDeclaration(VDecl);
9561 }
9562 
9563 /// ActOnInitializerError - Given that there was an error parsing an
9564 /// initializer for the given declaration, try to return to some form
9565 /// of sanity.
9566 void Sema::ActOnInitializerError(Decl *D) {
9567   // Our main concern here is re-establishing invariants like "a
9568   // variable's type is either dependent or complete".
9569   if (!D || D->isInvalidDecl()) return;
9570 
9571   VarDecl *VD = dyn_cast<VarDecl>(D);
9572   if (!VD) return;
9573 
9574   // Auto types are meaningless if we can't make sense of the initializer.
9575   if (ParsingInitForAutoVars.count(D)) {
9576     D->setInvalidDecl();
9577     return;
9578   }
9579 
9580   QualType Ty = VD->getType();
9581   if (Ty->isDependentType()) return;
9582 
9583   // Require a complete type.
9584   if (RequireCompleteType(VD->getLocation(),
9585                           Context.getBaseElementType(Ty),
9586                           diag::err_typecheck_decl_incomplete_type)) {
9587     VD->setInvalidDecl();
9588     return;
9589   }
9590 
9591   // Require a non-abstract type.
9592   if (RequireNonAbstractType(VD->getLocation(), Ty,
9593                              diag::err_abstract_type_in_decl,
9594                              AbstractVariableType)) {
9595     VD->setInvalidDecl();
9596     return;
9597   }
9598 
9599   // Don't bother complaining about constructors or destructors,
9600   // though.
9601 }
9602 
9603 void Sema::ActOnUninitializedDecl(Decl *RealDecl,
9604                                   bool TypeMayContainAuto) {
9605   // If there is no declaration, there was an error parsing it. Just ignore it.
9606   if (!RealDecl)
9607     return;
9608 
9609   if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
9610     QualType Type = Var->getType();
9611 
9612     // C++11 [dcl.spec.auto]p3
9613     if (TypeMayContainAuto && Type->getContainedAutoType()) {
9614       Diag(Var->getLocation(), diag::err_auto_var_requires_init)
9615         << Var->getDeclName() << Type;
9616       Var->setInvalidDecl();
9617       return;
9618     }
9619 
9620     // C++11 [class.static.data]p3: A static data member can be declared with
9621     // the constexpr specifier; if so, its declaration shall specify
9622     // a brace-or-equal-initializer.
9623     // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
9624     // the definition of a variable [...] or the declaration of a static data
9625     // member.
9626     if (Var->isConstexpr() && !Var->isThisDeclarationADefinition()) {
9627       if (Var->isStaticDataMember())
9628         Diag(Var->getLocation(),
9629              diag::err_constexpr_static_mem_var_requires_init)
9630           << Var->getDeclName();
9631       else
9632         Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
9633       Var->setInvalidDecl();
9634       return;
9635     }
9636 
9637     // C++ Concepts TS [dcl.spec.concept]p1: [...]  A variable template
9638     // definition having the concept specifier is called a variable concept. A
9639     // concept definition refers to [...] a variable concept and its initializer.
9640     if (Var->isConcept()) {
9641       Diag(Var->getLocation(), diag::err_var_concept_not_initialized);
9642       Var->setInvalidDecl();
9643       return;
9644     }
9645 
9646     // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
9647     // be initialized.
9648     if (!Var->isInvalidDecl() &&
9649         Var->getType().getAddressSpace() == LangAS::opencl_constant &&
9650         Var->getStorageClass() != SC_Extern && !Var->getInit()) {
9651       Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
9652       Var->setInvalidDecl();
9653       return;
9654     }
9655 
9656     switch (Var->isThisDeclarationADefinition()) {
9657     case VarDecl::Definition:
9658       if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
9659         break;
9660 
9661       // We have an out-of-line definition of a static data member
9662       // that has an in-class initializer, so we type-check this like
9663       // a declaration.
9664       //
9665       // Fall through
9666 
9667     case VarDecl::DeclarationOnly:
9668       // It's only a declaration.
9669 
9670       // Block scope. C99 6.7p7: If an identifier for an object is
9671       // declared with no linkage (C99 6.2.2p6), the type for the
9672       // object shall be complete.
9673       if (!Type->isDependentType() && Var->isLocalVarDecl() &&
9674           !Var->hasLinkage() && !Var->isInvalidDecl() &&
9675           RequireCompleteType(Var->getLocation(), Type,
9676                               diag::err_typecheck_decl_incomplete_type))
9677         Var->setInvalidDecl();
9678 
9679       // Make sure that the type is not abstract.
9680       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9681           RequireNonAbstractType(Var->getLocation(), Type,
9682                                  diag::err_abstract_type_in_decl,
9683                                  AbstractVariableType))
9684         Var->setInvalidDecl();
9685       if (!Type->isDependentType() && !Var->isInvalidDecl() &&
9686           Var->getStorageClass() == SC_PrivateExtern) {
9687         Diag(Var->getLocation(), diag::warn_private_extern);
9688         Diag(Var->getLocation(), diag::note_private_extern);
9689       }
9690 
9691       return;
9692 
9693     case VarDecl::TentativeDefinition:
9694       // File scope. C99 6.9.2p2: A declaration of an identifier for an
9695       // object that has file scope without an initializer, and without a
9696       // storage-class specifier or with the storage-class specifier "static",
9697       // constitutes a tentative definition. Note: A tentative definition with
9698       // external linkage is valid (C99 6.2.2p5).
9699       if (!Var->isInvalidDecl()) {
9700         if (const IncompleteArrayType *ArrayT
9701                                     = Context.getAsIncompleteArrayType(Type)) {
9702           if (RequireCompleteType(Var->getLocation(),
9703                                   ArrayT->getElementType(),
9704                                   diag::err_illegal_decl_array_incomplete_type))
9705             Var->setInvalidDecl();
9706         } else if (Var->getStorageClass() == SC_Static) {
9707           // C99 6.9.2p3: If the declaration of an identifier for an object is
9708           // a tentative definition and has internal linkage (C99 6.2.2p3), the
9709           // declared type shall not be an incomplete type.
9710           // NOTE: code such as the following
9711           //     static struct s;
9712           //     struct s { int a; };
9713           // is accepted by gcc. Hence here we issue a warning instead of
9714           // an error and we do not invalidate the static declaration.
9715           // NOTE: to avoid multiple warnings, only check the first declaration.
9716           if (Var->isFirstDecl())
9717             RequireCompleteType(Var->getLocation(), Type,
9718                                 diag::ext_typecheck_decl_incomplete_type);
9719         }
9720       }
9721 
9722       // Record the tentative definition; we're done.
9723       if (!Var->isInvalidDecl())
9724         TentativeDefinitions.push_back(Var);
9725       return;
9726     }
9727 
9728     // Provide a specific diagnostic for uninitialized variable
9729     // definitions with incomplete array type.
9730     if (Type->isIncompleteArrayType()) {
9731       Diag(Var->getLocation(),
9732            diag::err_typecheck_incomplete_array_needs_initializer);
9733       Var->setInvalidDecl();
9734       return;
9735     }
9736 
9737     // Provide a specific diagnostic for uninitialized variable
9738     // definitions with reference type.
9739     if (Type->isReferenceType()) {
9740       Diag(Var->getLocation(), diag::err_reference_var_requires_init)
9741         << Var->getDeclName()
9742         << SourceRange(Var->getLocation(), Var->getLocation());
9743       Var->setInvalidDecl();
9744       return;
9745     }
9746 
9747     // Do not attempt to type-check the default initializer for a
9748     // variable with dependent type.
9749     if (Type->isDependentType())
9750       return;
9751 
9752     if (Var->isInvalidDecl())
9753       return;
9754 
9755     if (!Var->hasAttr<AliasAttr>()) {
9756       if (RequireCompleteType(Var->getLocation(),
9757                               Context.getBaseElementType(Type),
9758                               diag::err_typecheck_decl_incomplete_type)) {
9759         Var->setInvalidDecl();
9760         return;
9761       }
9762     } else {
9763       return;
9764     }
9765 
9766     // The variable can not have an abstract class type.
9767     if (RequireNonAbstractType(Var->getLocation(), Type,
9768                                diag::err_abstract_type_in_decl,
9769                                AbstractVariableType)) {
9770       Var->setInvalidDecl();
9771       return;
9772     }
9773 
9774     // Check for jumps past the implicit initializer.  C++0x
9775     // clarifies that this applies to a "variable with automatic
9776     // storage duration", not a "local variable".
9777     // C++11 [stmt.dcl]p3
9778     //   A program that jumps from a point where a variable with automatic
9779     //   storage duration is not in scope to a point where it is in scope is
9780     //   ill-formed unless the variable has scalar type, class type with a
9781     //   trivial default constructor and a trivial destructor, a cv-qualified
9782     //   version of one of these types, or an array of one of the preceding
9783     //   types and is declared without an initializer.
9784     if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
9785       if (const RecordType *Record
9786             = Context.getBaseElementType(Type)->getAs<RecordType>()) {
9787         CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
9788         // Mark the function for further checking even if the looser rules of
9789         // C++11 do not require such checks, so that we can diagnose
9790         // incompatibilities with C++98.
9791         if (!CXXRecord->isPOD())
9792           getCurFunction()->setHasBranchProtectedScope();
9793       }
9794     }
9795 
9796     // C++03 [dcl.init]p9:
9797     //   If no initializer is specified for an object, and the
9798     //   object is of (possibly cv-qualified) non-POD class type (or
9799     //   array thereof), the object shall be default-initialized; if
9800     //   the object is of const-qualified type, the underlying class
9801     //   type shall have a user-declared default
9802     //   constructor. Otherwise, if no initializer is specified for
9803     //   a non- static object, the object and its subobjects, if
9804     //   any, have an indeterminate initial value); if the object
9805     //   or any of its subobjects are of const-qualified type, the
9806     //   program is ill-formed.
9807     // C++0x [dcl.init]p11:
9808     //   If no initializer is specified for an object, the object is
9809     //   default-initialized; [...].
9810     InitializedEntity Entity = InitializedEntity::InitializeVariable(Var);
9811     InitializationKind Kind
9812       = InitializationKind::CreateDefault(Var->getLocation());
9813 
9814     InitializationSequence InitSeq(*this, Entity, Kind, None);
9815     ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
9816     if (Init.isInvalid())
9817       Var->setInvalidDecl();
9818     else if (Init.get()) {
9819       Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
9820       // This is important for template substitution.
9821       Var->setInitStyle(VarDecl::CallInit);
9822     }
9823 
9824     CheckCompleteVariableDeclaration(Var);
9825   }
9826 }
9827 
9828 void Sema::ActOnCXXForRangeDecl(Decl *D) {
9829   VarDecl *VD = dyn_cast<VarDecl>(D);
9830   if (!VD) {
9831     Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
9832     D->setInvalidDecl();
9833     return;
9834   }
9835 
9836   VD->setCXXForRangeDecl(true);
9837 
9838   // for-range-declaration cannot be given a storage class specifier.
9839   int Error = -1;
9840   switch (VD->getStorageClass()) {
9841   case SC_None:
9842     break;
9843   case SC_Extern:
9844     Error = 0;
9845     break;
9846   case SC_Static:
9847     Error = 1;
9848     break;
9849   case SC_PrivateExtern:
9850     Error = 2;
9851     break;
9852   case SC_Auto:
9853     Error = 3;
9854     break;
9855   case SC_Register:
9856     Error = 4;
9857     break;
9858   }
9859   if (Error != -1) {
9860     Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
9861       << VD->getDeclName() << Error;
9862     D->setInvalidDecl();
9863   }
9864 }
9865 
9866 StmtResult
9867 Sema::ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc,
9868                                  IdentifierInfo *Ident,
9869                                  ParsedAttributes &Attrs,
9870                                  SourceLocation AttrEnd) {
9871   // C++1y [stmt.iter]p1:
9872   //   A range-based for statement of the form
9873   //      for ( for-range-identifier : for-range-initializer ) statement
9874   //   is equivalent to
9875   //      for ( auto&& for-range-identifier : for-range-initializer ) statement
9876   DeclSpec DS(Attrs.getPool().getFactory());
9877 
9878   const char *PrevSpec;
9879   unsigned DiagID;
9880   DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
9881                      getPrintingPolicy());
9882 
9883   Declarator D(DS, Declarator::ForContext);
9884   D.SetIdentifier(Ident, IdentLoc);
9885   D.takeAttributes(Attrs, AttrEnd);
9886 
9887   ParsedAttributes EmptyAttrs(Attrs.getPool().getFactory());
9888   D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/false),
9889                 EmptyAttrs, IdentLoc);
9890   Decl *Var = ActOnDeclarator(S, D);
9891   cast<VarDecl>(Var)->setCXXForRangeDecl(true);
9892   FinalizeDeclaration(Var);
9893   return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
9894                        AttrEnd.isValid() ? AttrEnd : IdentLoc);
9895 }
9896 
9897 void Sema::CheckCompleteVariableDeclaration(VarDecl *var) {
9898   if (var->isInvalidDecl()) return;
9899 
9900   // In Objective-C, don't allow jumps past the implicit initialization of a
9901   // local retaining variable.
9902   if (getLangOpts().ObjC1 &&
9903       var->hasLocalStorage()) {
9904     switch (var->getType().getObjCLifetime()) {
9905     case Qualifiers::OCL_None:
9906     case Qualifiers::OCL_ExplicitNone:
9907     case Qualifiers::OCL_Autoreleasing:
9908       break;
9909 
9910     case Qualifiers::OCL_Weak:
9911     case Qualifiers::OCL_Strong:
9912       getCurFunction()->setHasBranchProtectedScope();
9913       break;
9914     }
9915   }
9916 
9917   // Warn about externally-visible variables being defined without a
9918   // prior declaration.  We only want to do this for global
9919   // declarations, but we also specifically need to avoid doing it for
9920   // class members because the linkage of an anonymous class can
9921   // change if it's later given a typedef name.
9922   if (var->isThisDeclarationADefinition() &&
9923       var->getDeclContext()->getRedeclContext()->isFileContext() &&
9924       var->isExternallyVisible() && var->hasLinkage() &&
9925       !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
9926                                   var->getLocation())) {
9927     // Find a previous declaration that's not a definition.
9928     VarDecl *prev = var->getPreviousDecl();
9929     while (prev && prev->isThisDeclarationADefinition())
9930       prev = prev->getPreviousDecl();
9931 
9932     if (!prev)
9933       Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
9934   }
9935 
9936   if (var->getTLSKind() == VarDecl::TLS_Static) {
9937     const Expr *Culprit;
9938     if (var->getType().isDestructedType()) {
9939       // GNU C++98 edits for __thread, [basic.start.term]p3:
9940       //   The type of an object with thread storage duration shall not
9941       //   have a non-trivial destructor.
9942       Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
9943       if (getLangOpts().CPlusPlus11)
9944         Diag(var->getLocation(), diag::note_use_thread_local);
9945     } else if (getLangOpts().CPlusPlus && var->hasInit() &&
9946                !var->getInit()->isConstantInitializer(
9947                    Context, var->getType()->isReferenceType(), &Culprit)) {
9948       // GNU C++98 edits for __thread, [basic.start.init]p4:
9949       //   An object of thread storage duration shall not require dynamic
9950       //   initialization.
9951       // FIXME: Need strict checking here.
9952       Diag(Culprit->getExprLoc(), diag::err_thread_dynamic_init)
9953         << Culprit->getSourceRange();
9954       if (getLangOpts().CPlusPlus11)
9955         Diag(var->getLocation(), diag::note_use_thread_local);
9956     }
9957 
9958   }
9959 
9960   // Apply section attributes and pragmas to global variables.
9961   bool GlobalStorage = var->hasGlobalStorage();
9962   if (GlobalStorage && var->isThisDeclarationADefinition() &&
9963       ActiveTemplateInstantiations.empty()) {
9964     PragmaStack<StringLiteral *> *Stack = nullptr;
9965     int SectionFlags = ASTContext::PSF_Implicit | ASTContext::PSF_Read;
9966     if (var->getType().isConstQualified())
9967       Stack = &ConstSegStack;
9968     else if (!var->getInit()) {
9969       Stack = &BSSSegStack;
9970       SectionFlags |= ASTContext::PSF_Write;
9971     } else {
9972       Stack = &DataSegStack;
9973       SectionFlags |= ASTContext::PSF_Write;
9974     }
9975     if (Stack->CurrentValue && !var->hasAttr<SectionAttr>()) {
9976       var->addAttr(SectionAttr::CreateImplicit(
9977           Context, SectionAttr::Declspec_allocate,
9978           Stack->CurrentValue->getString(), Stack->CurrentPragmaLocation));
9979     }
9980     if (const SectionAttr *SA = var->getAttr<SectionAttr>())
9981       if (UnifySection(SA->getName(), SectionFlags, var))
9982         var->dropAttr<SectionAttr>();
9983 
9984     // Apply the init_seg attribute if this has an initializer.  If the
9985     // initializer turns out to not be dynamic, we'll end up ignoring this
9986     // attribute.
9987     if (CurInitSeg && var->getInit())
9988       var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
9989                                                CurInitSegLoc));
9990   }
9991 
9992   // All the following checks are C++ only.
9993   if (!getLangOpts().CPlusPlus) return;
9994 
9995   QualType type = var->getType();
9996   if (type->isDependentType()) return;
9997 
9998   // __block variables might require us to capture a copy-initializer.
9999   if (var->hasAttr<BlocksAttr>()) {
10000     // It's currently invalid to ever have a __block variable with an
10001     // array type; should we diagnose that here?
10002 
10003     // Regardless, we don't want to ignore array nesting when
10004     // constructing this copy.
10005     if (type->isStructureOrClassType()) {
10006       EnterExpressionEvaluationContext scope(*this, PotentiallyEvaluated);
10007       SourceLocation poi = var->getLocation();
10008       Expr *varRef =new (Context) DeclRefExpr(var, false, type, VK_LValue, poi);
10009       ExprResult result
10010         = PerformMoveOrCopyInitialization(
10011             InitializedEntity::InitializeBlock(poi, type, false),
10012             var, var->getType(), varRef, /*AllowNRVO=*/true);
10013       if (!result.isInvalid()) {
10014         result = MaybeCreateExprWithCleanups(result);
10015         Expr *init = result.getAs<Expr>();
10016         Context.setBlockVarCopyInits(var, init);
10017       }
10018     }
10019   }
10020 
10021   Expr *Init = var->getInit();
10022   bool IsGlobal = GlobalStorage && !var->isStaticLocal();
10023   QualType baseType = Context.getBaseElementType(type);
10024 
10025   if (!var->getDeclContext()->isDependentContext() &&
10026       Init && !Init->isValueDependent()) {
10027     if (IsGlobal && !var->isConstexpr() &&
10028         !getDiagnostics().isIgnored(diag::warn_global_constructor,
10029                                     var->getLocation())) {
10030       // Warn about globals which don't have a constant initializer.  Don't
10031       // warn about globals with a non-trivial destructor because we already
10032       // warned about them.
10033       CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
10034       if (!(RD && !RD->hasTrivialDestructor()) &&
10035           !Init->isConstantInitializer(Context, baseType->isReferenceType()))
10036         Diag(var->getLocation(), diag::warn_global_constructor)
10037           << Init->getSourceRange();
10038     }
10039 
10040     if (var->isConstexpr()) {
10041       SmallVector<PartialDiagnosticAt, 8> Notes;
10042       if (!var->evaluateValue(Notes) || !var->isInitICE()) {
10043         SourceLocation DiagLoc = var->getLocation();
10044         // If the note doesn't add any useful information other than a source
10045         // location, fold it into the primary diagnostic.
10046         if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
10047               diag::note_invalid_subexpr_in_const_expr) {
10048           DiagLoc = Notes[0].first;
10049           Notes.clear();
10050         }
10051         Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
10052           << var << Init->getSourceRange();
10053         for (unsigned I = 0, N = Notes.size(); I != N; ++I)
10054           Diag(Notes[I].first, Notes[I].second);
10055       }
10056     } else if (var->isUsableInConstantExpressions(Context)) {
10057       // Check whether the initializer of a const variable of integral or
10058       // enumeration type is an ICE now, since we can't tell whether it was
10059       // initialized by a constant expression if we check later.
10060       var->checkInitIsICE();
10061     }
10062   }
10063 
10064   // Require the destructor.
10065   if (const RecordType *recordType = baseType->getAs<RecordType>())
10066     FinalizeVarWithDestructor(var, recordType);
10067 }
10068 
10069 /// \brief Determines if a variable's alignment is dependent.
10070 static bool hasDependentAlignment(VarDecl *VD) {
10071   if (VD->getType()->isDependentType())
10072     return true;
10073   for (auto *I : VD->specific_attrs<AlignedAttr>())
10074     if (I->isAlignmentDependent())
10075       return true;
10076   return false;
10077 }
10078 
10079 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
10080 /// any semantic actions necessary after any initializer has been attached.
10081 void
10082 Sema::FinalizeDeclaration(Decl *ThisDecl) {
10083   // Note that we are no longer parsing the initializer for this declaration.
10084   ParsingInitForAutoVars.erase(ThisDecl);
10085 
10086   VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
10087   if (!VD)
10088     return;
10089 
10090   checkAttributesAfterMerging(*this, *VD);
10091 
10092   // Perform TLS alignment check here after attributes attached to the variable
10093   // which may affect the alignment have been processed. Only perform the check
10094   // if the target has a maximum TLS alignment (zero means no constraints).
10095   if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
10096     // Protect the check so that it's not performed on dependent types and
10097     // dependent alignments (we can't determine the alignment in that case).
10098     if (VD->getTLSKind() && !hasDependentAlignment(VD)) {
10099       CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
10100       if (Context.getDeclAlign(VD) > MaxAlignChars) {
10101         Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
10102           << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
10103           << (unsigned)MaxAlignChars.getQuantity();
10104       }
10105     }
10106   }
10107 
10108   // Static locals inherit dll attributes from their function.
10109   if (VD->isStaticLocal()) {
10110     if (FunctionDecl *FD =
10111             dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod())) {
10112       if (Attr *A = getDLLAttr(FD)) {
10113         auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
10114         NewAttr->setInherited(true);
10115         VD->addAttr(NewAttr);
10116       }
10117     }
10118   }
10119 
10120   // Grab the dllimport or dllexport attribute off of the VarDecl.
10121   const InheritableAttr *DLLAttr = getDLLAttr(VD);
10122 
10123   // Imported static data members cannot be defined out-of-line.
10124   if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
10125     if (VD->isStaticDataMember() && VD->isOutOfLine() &&
10126         VD->isThisDeclarationADefinition()) {
10127       // We allow definitions of dllimport class template static data members
10128       // with a warning.
10129       CXXRecordDecl *Context =
10130         cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
10131       bool IsClassTemplateMember =
10132           isa<ClassTemplatePartialSpecializationDecl>(Context) ||
10133           Context->getDescribedClassTemplate();
10134 
10135       Diag(VD->getLocation(),
10136            IsClassTemplateMember
10137                ? diag::warn_attribute_dllimport_static_field_definition
10138                : diag::err_attribute_dllimport_static_field_definition);
10139       Diag(IA->getLocation(), diag::note_attribute);
10140       if (!IsClassTemplateMember)
10141         VD->setInvalidDecl();
10142     }
10143   }
10144 
10145   // dllimport/dllexport variables cannot be thread local, their TLS index
10146   // isn't exported with the variable.
10147   if (DLLAttr && VD->getTLSKind()) {
10148     auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
10149     if (F && getDLLAttr(F)) {
10150       assert(VD->isStaticLocal());
10151       // But if this is a static local in a dlimport/dllexport function, the
10152       // function will never be inlined, which means the var would never be
10153       // imported, so having it marked import/export is safe.
10154     } else {
10155       Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
10156                                                                     << DLLAttr;
10157       VD->setInvalidDecl();
10158     }
10159   }
10160 
10161   if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
10162     if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
10163       Diag(Attr->getLocation(), diag::warn_attribute_ignored) << Attr;
10164       VD->dropAttr<UsedAttr>();
10165     }
10166   }
10167 
10168   const DeclContext *DC = VD->getDeclContext();
10169   // If there's a #pragma GCC visibility in scope, and this isn't a class
10170   // member, set the visibility of this variable.
10171   if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
10172     AddPushedVisibilityAttribute(VD);
10173 
10174   // FIXME: Warn on unused templates.
10175   if (VD->isFileVarDecl() && !VD->getDescribedVarTemplate() &&
10176       !isa<VarTemplatePartialSpecializationDecl>(VD))
10177     MarkUnusedFileScopedDecl(VD);
10178 
10179   // Now we have parsed the initializer and can update the table of magic
10180   // tag values.
10181   if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
10182       !VD->getType()->isIntegralOrEnumerationType())
10183     return;
10184 
10185   for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
10186     const Expr *MagicValueExpr = VD->getInit();
10187     if (!MagicValueExpr) {
10188       continue;
10189     }
10190     llvm::APSInt MagicValueInt;
10191     if (!MagicValueExpr->isIntegerConstantExpr(MagicValueInt, Context)) {
10192       Diag(I->getRange().getBegin(),
10193            diag::err_type_tag_for_datatype_not_ice)
10194         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10195       continue;
10196     }
10197     if (MagicValueInt.getActiveBits() > 64) {
10198       Diag(I->getRange().getBegin(),
10199            diag::err_type_tag_for_datatype_too_large)
10200         << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
10201       continue;
10202     }
10203     uint64_t MagicValue = MagicValueInt.getZExtValue();
10204     RegisterTypeTagForDatatype(I->getArgumentKind(),
10205                                MagicValue,
10206                                I->getMatchingCType(),
10207                                I->getLayoutCompatible(),
10208                                I->getMustBeNull());
10209   }
10210 }
10211 
10212 Sema::DeclGroupPtrTy Sema::FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS,
10213                                                    ArrayRef<Decl *> Group) {
10214   SmallVector<Decl*, 8> Decls;
10215 
10216   if (DS.isTypeSpecOwned())
10217     Decls.push_back(DS.getRepAsDecl());
10218 
10219   DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
10220   for (unsigned i = 0, e = Group.size(); i != e; ++i)
10221     if (Decl *D = Group[i]) {
10222       if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D))
10223         if (!FirstDeclaratorInGroup)
10224           FirstDeclaratorInGroup = DD;
10225       Decls.push_back(D);
10226     }
10227 
10228   if (DeclSpec::isDeclRep(DS.getTypeSpecType())) {
10229     if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
10230       handleTagNumbering(Tag, S);
10231       if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
10232           getLangOpts().CPlusPlus)
10233         Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
10234     }
10235   }
10236 
10237   return BuildDeclaratorGroup(Decls, DS.containsPlaceholderType());
10238 }
10239 
10240 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
10241 /// group, performing any necessary semantic checking.
10242 Sema::DeclGroupPtrTy
10243 Sema::BuildDeclaratorGroup(MutableArrayRef<Decl *> Group,
10244                            bool TypeMayContainAuto) {
10245   // C++0x [dcl.spec.auto]p7:
10246   //   If the type deduced for the template parameter U is not the same in each
10247   //   deduction, the program is ill-formed.
10248   // FIXME: When initializer-list support is added, a distinction is needed
10249   // between the deduced type U and the deduced type which 'auto' stands for.
10250   //   auto a = 0, b = { 1, 2, 3 };
10251   // is legal because the deduced type U is 'int' in both cases.
10252   if (TypeMayContainAuto && Group.size() > 1) {
10253     QualType Deduced;
10254     CanQualType DeducedCanon;
10255     VarDecl *DeducedDecl = nullptr;
10256     for (unsigned i = 0, e = Group.size(); i != e; ++i) {
10257       if (VarDecl *D = dyn_cast<VarDecl>(Group[i])) {
10258         AutoType *AT = D->getType()->getContainedAutoType();
10259         // Don't reissue diagnostics when instantiating a template.
10260         if (AT && D->isInvalidDecl())
10261           break;
10262         QualType U = AT ? AT->getDeducedType() : QualType();
10263         if (!U.isNull()) {
10264           CanQualType UCanon = Context.getCanonicalType(U);
10265           if (Deduced.isNull()) {
10266             Deduced = U;
10267             DeducedCanon = UCanon;
10268             DeducedDecl = D;
10269           } else if (DeducedCanon != UCanon) {
10270             Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
10271                  diag::err_auto_different_deductions)
10272               << (unsigned)AT->getKeyword()
10273               << Deduced << DeducedDecl->getDeclName()
10274               << U << D->getDeclName()
10275               << DeducedDecl->getInit()->getSourceRange()
10276               << D->getInit()->getSourceRange();
10277             D->setInvalidDecl();
10278             break;
10279           }
10280         }
10281       }
10282     }
10283   }
10284 
10285   ActOnDocumentableDecls(Group);
10286 
10287   return DeclGroupPtrTy::make(
10288       DeclGroupRef::Create(Context, Group.data(), Group.size()));
10289 }
10290 
10291 void Sema::ActOnDocumentableDecl(Decl *D) {
10292   ActOnDocumentableDecls(D);
10293 }
10294 
10295 void Sema::ActOnDocumentableDecls(ArrayRef<Decl *> Group) {
10296   // Don't parse the comment if Doxygen diagnostics are ignored.
10297   if (Group.empty() || !Group[0])
10298     return;
10299 
10300   if (Diags.isIgnored(diag::warn_doc_param_not_found,
10301                       Group[0]->getLocation()) &&
10302       Diags.isIgnored(diag::warn_unknown_comment_command_name,
10303                       Group[0]->getLocation()))
10304     return;
10305 
10306   if (Group.size() >= 2) {
10307     // This is a decl group.  Normally it will contain only declarations
10308     // produced from declarator list.  But in case we have any definitions or
10309     // additional declaration references:
10310     //   'typedef struct S {} S;'
10311     //   'typedef struct S *S;'
10312     //   'struct S *pS;'
10313     // FinalizeDeclaratorGroup adds these as separate declarations.
10314     Decl *MaybeTagDecl = Group[0];
10315     if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
10316       Group = Group.slice(1);
10317     }
10318   }
10319 
10320   // See if there are any new comments that are not attached to a decl.
10321   ArrayRef<RawComment *> Comments = Context.getRawCommentList().getComments();
10322   if (!Comments.empty() &&
10323       !Comments.back()->isAttached()) {
10324     // There is at least one comment that not attached to a decl.
10325     // Maybe it should be attached to one of these decls?
10326     //
10327     // Note that this way we pick up not only comments that precede the
10328     // declaration, but also comments that *follow* the declaration -- thanks to
10329     // the lookahead in the lexer: we've consumed the semicolon and looked
10330     // ahead through comments.
10331     for (unsigned i = 0, e = Group.size(); i != e; ++i)
10332       Context.getCommentForDecl(Group[i], &PP);
10333   }
10334 }
10335 
10336 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
10337 /// to introduce parameters into function prototype scope.
10338 Decl *Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
10339   const DeclSpec &DS = D.getDeclSpec();
10340 
10341   // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
10342 
10343   // C++03 [dcl.stc]p2 also permits 'auto'.
10344   StorageClass SC = SC_None;
10345   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
10346     SC = SC_Register;
10347   } else if (getLangOpts().CPlusPlus &&
10348              DS.getStorageClassSpec() == DeclSpec::SCS_auto) {
10349     SC = SC_Auto;
10350   } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
10351     Diag(DS.getStorageClassSpecLoc(),
10352          diag::err_invalid_storage_class_in_func_decl);
10353     D.getMutableDeclSpec().ClearStorageClassSpecs();
10354   }
10355 
10356   if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
10357     Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
10358       << DeclSpec::getSpecifierName(TSCS);
10359   if (DS.isConstexprSpecified())
10360     Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
10361       << 0;
10362   if (DS.isConceptSpecified())
10363     Diag(DS.getConceptSpecLoc(), diag::err_concept_wrong_decl_kind);
10364 
10365   DiagnoseFunctionSpecifiers(DS);
10366 
10367   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
10368   QualType parmDeclType = TInfo->getType();
10369 
10370   if (getLangOpts().CPlusPlus) {
10371     // Check that there are no default arguments inside the type of this
10372     // parameter.
10373     CheckExtraCXXDefaultArguments(D);
10374 
10375     // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
10376     if (D.getCXXScopeSpec().isSet()) {
10377       Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
10378         << D.getCXXScopeSpec().getRange();
10379       D.getCXXScopeSpec().clear();
10380     }
10381   }
10382 
10383   // Ensure we have a valid name
10384   IdentifierInfo *II = nullptr;
10385   if (D.hasName()) {
10386     II = D.getIdentifier();
10387     if (!II) {
10388       Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
10389         << GetNameForDeclarator(D).getName();
10390       D.setInvalidType(true);
10391     }
10392   }
10393 
10394   // Check for redeclaration of parameters, e.g. int foo(int x, int x);
10395   if (II) {
10396     LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
10397                    ForRedeclaration);
10398     LookupName(R, S);
10399     if (R.isSingleResult()) {
10400       NamedDecl *PrevDecl = R.getFoundDecl();
10401       if (PrevDecl->isTemplateParameter()) {
10402         // Maybe we will complain about the shadowed template parameter.
10403         DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
10404         // Just pretend that we didn't see the previous declaration.
10405         PrevDecl = nullptr;
10406       } else if (S->isDeclScope(PrevDecl)) {
10407         Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
10408         Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
10409 
10410         // Recover by removing the name
10411         II = nullptr;
10412         D.SetIdentifier(nullptr, D.getIdentifierLoc());
10413         D.setInvalidType(true);
10414       }
10415     }
10416   }
10417 
10418   // Temporarily put parameter variables in the translation unit, not
10419   // the enclosing context.  This prevents them from accidentally
10420   // looking like class members in C++.
10421   ParmVarDecl *New = CheckParameter(Context.getTranslationUnitDecl(),
10422                                     D.getLocStart(),
10423                                     D.getIdentifierLoc(), II,
10424                                     parmDeclType, TInfo,
10425                                     SC);
10426 
10427   if (D.isInvalidType())
10428     New->setInvalidDecl();
10429 
10430   assert(S->isFunctionPrototypeScope());
10431   assert(S->getFunctionPrototypeDepth() >= 1);
10432   New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
10433                     S->getNextFunctionPrototypeIndex());
10434 
10435   // Add the parameter declaration into this scope.
10436   S->AddDecl(New);
10437   if (II)
10438     IdResolver.AddDecl(New);
10439 
10440   ProcessDeclAttributes(S, New, D);
10441 
10442   if (D.getDeclSpec().isModulePrivateSpecified())
10443     Diag(New->getLocation(), diag::err_module_private_local)
10444       << 1 << New->getDeclName()
10445       << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
10446       << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
10447 
10448   if (New->hasAttr<BlocksAttr>()) {
10449     Diag(New->getLocation(), diag::err_block_on_nonlocal);
10450   }
10451   return New;
10452 }
10453 
10454 /// \brief Synthesizes a variable for a parameter arising from a
10455 /// typedef.
10456 ParmVarDecl *Sema::BuildParmVarDeclForTypedef(DeclContext *DC,
10457                                               SourceLocation Loc,
10458                                               QualType T) {
10459   /* FIXME: setting StartLoc == Loc.
10460      Would it be worth to modify callers so as to provide proper source
10461      location for the unnamed parameters, embedding the parameter's type? */
10462   ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
10463                                 T, Context.getTrivialTypeSourceInfo(T, Loc),
10464                                            SC_None, nullptr);
10465   Param->setImplicit();
10466   return Param;
10467 }
10468 
10469 void Sema::DiagnoseUnusedParameters(ParmVarDecl * const *Param,
10470                                     ParmVarDecl * const *ParamEnd) {
10471   // Don't diagnose unused-parameter errors in template instantiations; we
10472   // will already have done so in the template itself.
10473   if (!ActiveTemplateInstantiations.empty())
10474     return;
10475 
10476   for (; Param != ParamEnd; ++Param) {
10477     if (!(*Param)->isReferenced() && (*Param)->getDeclName() &&
10478         !(*Param)->hasAttr<UnusedAttr>()) {
10479       Diag((*Param)->getLocation(), diag::warn_unused_parameter)
10480         << (*Param)->getDeclName();
10481     }
10482   }
10483 }
10484 
10485 void Sema::DiagnoseSizeOfParametersAndReturnValue(ParmVarDecl * const *Param,
10486                                                   ParmVarDecl * const *ParamEnd,
10487                                                   QualType ReturnTy,
10488                                                   NamedDecl *D) {
10489   if (LangOpts.NumLargeByValueCopy == 0) // No check.
10490     return;
10491 
10492   // Warn if the return value is pass-by-value and larger than the specified
10493   // threshold.
10494   if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
10495     unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
10496     if (Size > LangOpts.NumLargeByValueCopy)
10497       Diag(D->getLocation(), diag::warn_return_value_size)
10498           << D->getDeclName() << Size;
10499   }
10500 
10501   // Warn if any parameter is pass-by-value and larger than the specified
10502   // threshold.
10503   for (; Param != ParamEnd; ++Param) {
10504     QualType T = (*Param)->getType();
10505     if (T->isDependentType() || !T.isPODType(Context))
10506       continue;
10507     unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
10508     if (Size > LangOpts.NumLargeByValueCopy)
10509       Diag((*Param)->getLocation(), diag::warn_parameter_size)
10510           << (*Param)->getDeclName() << Size;
10511   }
10512 }
10513 
10514 ParmVarDecl *Sema::CheckParameter(DeclContext *DC, SourceLocation StartLoc,
10515                                   SourceLocation NameLoc, IdentifierInfo *Name,
10516                                   QualType T, TypeSourceInfo *TSInfo,
10517                                   StorageClass SC) {
10518   // In ARC, infer a lifetime qualifier for appropriate parameter types.
10519   if (getLangOpts().ObjCAutoRefCount &&
10520       T.getObjCLifetime() == Qualifiers::OCL_None &&
10521       T->isObjCLifetimeType()) {
10522 
10523     Qualifiers::ObjCLifetime lifetime;
10524 
10525     // Special cases for arrays:
10526     //   - if it's const, use __unsafe_unretained
10527     //   - otherwise, it's an error
10528     if (T->isArrayType()) {
10529       if (!T.isConstQualified()) {
10530         DelayedDiagnostics.add(
10531             sema::DelayedDiagnostic::makeForbiddenType(
10532             NameLoc, diag::err_arc_array_param_no_ownership, T, false));
10533       }
10534       lifetime = Qualifiers::OCL_ExplicitNone;
10535     } else {
10536       lifetime = T->getObjCARCImplicitLifetime();
10537     }
10538     T = Context.getLifetimeQualifiedType(T, lifetime);
10539   }
10540 
10541   ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
10542                                          Context.getAdjustedParameterType(T),
10543                                          TSInfo, SC, nullptr);
10544 
10545   // Parameters can not be abstract class types.
10546   // For record types, this is done by the AbstractClassUsageDiagnoser once
10547   // the class has been completely parsed.
10548   if (!CurContext->isRecord() &&
10549       RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
10550                              AbstractParamType))
10551     New->setInvalidDecl();
10552 
10553   // Parameter declarators cannot be interface types. All ObjC objects are
10554   // passed by reference.
10555   if (T->isObjCObjectType()) {
10556     SourceLocation TypeEndLoc = TSInfo->getTypeLoc().getLocEnd();
10557     Diag(NameLoc,
10558          diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
10559       << FixItHint::CreateInsertion(TypeEndLoc, "*");
10560     T = Context.getObjCObjectPointerType(T);
10561     New->setType(T);
10562   }
10563 
10564   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
10565   // duration shall not be qualified by an address-space qualifier."
10566   // Since all parameters have automatic store duration, they can not have
10567   // an address space.
10568   if (T.getAddressSpace() != 0) {
10569     // OpenCL allows function arguments declared to be an array of a type
10570     // to be qualified with an address space.
10571     if (!(getLangOpts().OpenCL && T->isArrayType())) {
10572       Diag(NameLoc, diag::err_arg_with_address_space);
10573       New->setInvalidDecl();
10574     }
10575   }
10576 
10577   return New;
10578 }
10579 
10580 void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D,
10581                                            SourceLocation LocAfterDecls) {
10582   DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
10583 
10584   // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
10585   // for a K&R function.
10586   if (!FTI.hasPrototype) {
10587     for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
10588       --i;
10589       if (FTI.Params[i].Param == nullptr) {
10590         SmallString<256> Code;
10591         llvm::raw_svector_ostream(Code)
10592             << "  int " << FTI.Params[i].Ident->getName() << ";\n";
10593         Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
10594             << FTI.Params[i].Ident
10595             << FixItHint::CreateInsertion(LocAfterDecls, Code);
10596 
10597         // Implicitly declare the argument as type 'int' for lack of a better
10598         // type.
10599         AttributeFactory attrs;
10600         DeclSpec DS(attrs);
10601         const char* PrevSpec; // unused
10602         unsigned DiagID; // unused
10603         DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
10604                            DiagID, Context.getPrintingPolicy());
10605         // Use the identifier location for the type source range.
10606         DS.SetRangeStart(FTI.Params[i].IdentLoc);
10607         DS.SetRangeEnd(FTI.Params[i].IdentLoc);
10608         Declarator ParamD(DS, Declarator::KNRTypeListContext);
10609         ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
10610         FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
10611       }
10612     }
10613   }
10614 }
10615 
10616 Decl *
10617 Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D,
10618                               MultiTemplateParamsArg TemplateParameterLists,
10619                               SkipBodyInfo *SkipBody) {
10620   assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
10621   assert(D.isFunctionDeclarator() && "Not a function declarator!");
10622   Scope *ParentScope = FnBodyScope->getParent();
10623 
10624   D.setFunctionDefinitionKind(FDK_Definition);
10625   Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
10626   return ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
10627 }
10628 
10629 void Sema::ActOnFinishInlineMethodDef(CXXMethodDecl *D) {
10630   Consumer.HandleInlineMethodDefinition(D);
10631 }
10632 
10633 static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD,
10634                              const FunctionDecl*& PossibleZeroParamPrototype) {
10635   // Don't warn about invalid declarations.
10636   if (FD->isInvalidDecl())
10637     return false;
10638 
10639   // Or declarations that aren't global.
10640   if (!FD->isGlobal())
10641     return false;
10642 
10643   // Don't warn about C++ member functions.
10644   if (isa<CXXMethodDecl>(FD))
10645     return false;
10646 
10647   // Don't warn about 'main'.
10648   if (FD->isMain())
10649     return false;
10650 
10651   // Don't warn about inline functions.
10652   if (FD->isInlined())
10653     return false;
10654 
10655   // Don't warn about function templates.
10656   if (FD->getDescribedFunctionTemplate())
10657     return false;
10658 
10659   // Don't warn about function template specializations.
10660   if (FD->isFunctionTemplateSpecialization())
10661     return false;
10662 
10663   // Don't warn for OpenCL kernels.
10664   if (FD->hasAttr<OpenCLKernelAttr>())
10665     return false;
10666 
10667   // Don't warn on explicitly deleted functions.
10668   if (FD->isDeleted())
10669     return false;
10670 
10671   bool MissingPrototype = true;
10672   for (const FunctionDecl *Prev = FD->getPreviousDecl();
10673        Prev; Prev = Prev->getPreviousDecl()) {
10674     // Ignore any declarations that occur in function or method
10675     // scope, because they aren't visible from the header.
10676     if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
10677       continue;
10678 
10679     MissingPrototype = !Prev->getType()->isFunctionProtoType();
10680     if (FD->getNumParams() == 0)
10681       PossibleZeroParamPrototype = Prev;
10682     break;
10683   }
10684 
10685   return MissingPrototype;
10686 }
10687 
10688 void
10689 Sema::CheckForFunctionRedefinition(FunctionDecl *FD,
10690                                    const FunctionDecl *EffectiveDefinition,
10691                                    SkipBodyInfo *SkipBody) {
10692   // Don't complain if we're in GNU89 mode and the previous definition
10693   // was an extern inline function.
10694   const FunctionDecl *Definition = EffectiveDefinition;
10695   if (!Definition)
10696     if (!FD->isDefined(Definition))
10697       return;
10698 
10699   if (canRedefineFunction(Definition, getLangOpts()))
10700     return;
10701 
10702   // If we don't have a visible definition of the function, and it's inline or
10703   // a template, skip the new definition.
10704   if (SkipBody && !hasVisibleDefinition(Definition) &&
10705       (Definition->getFormalLinkage() == InternalLinkage ||
10706        Definition->isInlined() ||
10707        Definition->getDescribedFunctionTemplate() ||
10708        Definition->getNumTemplateParameterLists())) {
10709     SkipBody->ShouldSkip = true;
10710     if (auto *TD = Definition->getDescribedFunctionTemplate())
10711       makeMergedDefinitionVisible(TD, FD->getLocation());
10712     else
10713       makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition),
10714                                   FD->getLocation());
10715     return;
10716   }
10717 
10718   if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
10719       Definition->getStorageClass() == SC_Extern)
10720     Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
10721         << FD->getDeclName() << getLangOpts().CPlusPlus;
10722   else
10723     Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
10724 
10725   Diag(Definition->getLocation(), diag::note_previous_definition);
10726   FD->setInvalidDecl();
10727 }
10728 
10729 
10730 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
10731                                    Sema &S) {
10732   CXXRecordDecl *const LambdaClass = CallOperator->getParent();
10733 
10734   LambdaScopeInfo *LSI = S.PushLambdaScope();
10735   LSI->CallOperator = CallOperator;
10736   LSI->Lambda = LambdaClass;
10737   LSI->ReturnType = CallOperator->getReturnType();
10738   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
10739 
10740   if (LCD == LCD_None)
10741     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_None;
10742   else if (LCD == LCD_ByCopy)
10743     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByval;
10744   else if (LCD == LCD_ByRef)
10745     LSI->ImpCaptureStyle = CapturingScopeInfo::ImpCap_LambdaByref;
10746   DeclarationNameInfo DNI = CallOperator->getNameInfo();
10747 
10748   LSI->IntroducerRange = DNI.getCXXOperatorNameRange();
10749   LSI->Mutable = !CallOperator->isConst();
10750 
10751   // Add the captures to the LSI so they can be noted as already
10752   // captured within tryCaptureVar.
10753   auto I = LambdaClass->field_begin();
10754   for (const auto &C : LambdaClass->captures()) {
10755     if (C.capturesVariable()) {
10756       VarDecl *VD = C.getCapturedVar();
10757       if (VD->isInitCapture())
10758         S.CurrentInstantiationScope->InstantiatedLocal(VD, VD);
10759       QualType CaptureType = VD->getType();
10760       const bool ByRef = C.getCaptureKind() == LCK_ByRef;
10761       LSI->addCapture(VD, /*IsBlock*/false, ByRef,
10762           /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
10763           /*EllipsisLoc*/C.isPackExpansion()
10764                          ? C.getEllipsisLoc() : SourceLocation(),
10765           CaptureType, /*Expr*/ nullptr);
10766 
10767     } else if (C.capturesThis()) {
10768       LSI->addThisCapture(/*Nested*/ false, C.getLocation(),
10769                               S.getCurrentThisType(), /*Expr*/ nullptr);
10770     } else {
10771       LSI->addVLATypeCapture(C.getLocation(), I->getType());
10772     }
10773     ++I;
10774   }
10775 }
10776 
10777 Decl *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Decl *D,
10778                                     SkipBodyInfo *SkipBody) {
10779   // Clear the last template instantiation error context.
10780   LastTemplateInstantiationErrorContext = ActiveTemplateInstantiation();
10781 
10782   if (!D)
10783     return D;
10784   FunctionDecl *FD = nullptr;
10785 
10786   if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
10787     FD = FunTmpl->getTemplatedDecl();
10788   else
10789     FD = cast<FunctionDecl>(D);
10790 
10791   // See if this is a redefinition.
10792   if (!FD->isLateTemplateParsed()) {
10793     CheckForFunctionRedefinition(FD, nullptr, SkipBody);
10794 
10795     // If we're skipping the body, we're done. Don't enter the scope.
10796     if (SkipBody && SkipBody->ShouldSkip)
10797       return D;
10798   }
10799 
10800   // If we are instantiating a generic lambda call operator, push
10801   // a LambdaScopeInfo onto the function stack.  But use the information
10802   // that's already been calculated (ActOnLambdaExpr) to prime the current
10803   // LambdaScopeInfo.
10804   // When the template operator is being specialized, the LambdaScopeInfo,
10805   // has to be properly restored so that tryCaptureVariable doesn't try
10806   // and capture any new variables. In addition when calculating potential
10807   // captures during transformation of nested lambdas, it is necessary to
10808   // have the LSI properly restored.
10809   if (isGenericLambdaCallOperatorSpecialization(FD)) {
10810     assert(ActiveTemplateInstantiations.size() &&
10811       "There should be an active template instantiation on the stack "
10812       "when instantiating a generic lambda!");
10813     RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
10814   }
10815   else
10816     // Enter a new function scope
10817     PushFunctionScope();
10818 
10819   // Builtin functions cannot be defined.
10820   if (unsigned BuiltinID = FD->getBuiltinID()) {
10821     if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
10822         !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
10823       Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
10824       FD->setInvalidDecl();
10825     }
10826   }
10827 
10828   // The return type of a function definition must be complete
10829   // (C99 6.9.1p3, C++ [dcl.fct]p6).
10830   QualType ResultType = FD->getReturnType();
10831   if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
10832       !FD->isInvalidDecl() &&
10833       RequireCompleteType(FD->getLocation(), ResultType,
10834                           diag::err_func_def_incomplete_result))
10835     FD->setInvalidDecl();
10836 
10837   if (FnBodyScope)
10838     PushDeclContext(FnBodyScope, FD);
10839 
10840   // Check the validity of our function parameters
10841   CheckParmsForFunctionDef(FD->param_begin(), FD->param_end(),
10842                            /*CheckParameterNames=*/true);
10843 
10844   // Introduce our parameters into the function scope
10845   for (auto Param : FD->params()) {
10846     Param->setOwningFunction(FD);
10847 
10848     // If this has an identifier, add it to the scope stack.
10849     if (Param->getIdentifier() && FnBodyScope) {
10850       CheckShadow(FnBodyScope, Param);
10851 
10852       PushOnScopeChains(Param, FnBodyScope);
10853     }
10854   }
10855 
10856   // If we had any tags defined in the function prototype,
10857   // introduce them into the function scope.
10858   if (FnBodyScope) {
10859     for (ArrayRef<NamedDecl *>::iterator
10860              I = FD->getDeclsInPrototypeScope().begin(),
10861              E = FD->getDeclsInPrototypeScope().end();
10862          I != E; ++I) {
10863       NamedDecl *D = *I;
10864 
10865       // Some of these decls (like enums) may have been pinned to the
10866       // translation unit for lack of a real context earlier. If so, remove
10867       // from the translation unit and reattach to the current context.
10868       if (D->getLexicalDeclContext() == Context.getTranslationUnitDecl()) {
10869         // Is the decl actually in the context?
10870         for (const auto *DI : Context.getTranslationUnitDecl()->decls()) {
10871           if (DI == D) {
10872             Context.getTranslationUnitDecl()->removeDecl(D);
10873             break;
10874           }
10875         }
10876         // Either way, reassign the lexical decl context to our FunctionDecl.
10877         D->setLexicalDeclContext(CurContext);
10878       }
10879 
10880       // If the decl has a non-null name, make accessible in the current scope.
10881       if (!D->getName().empty())
10882         PushOnScopeChains(D, FnBodyScope, /*AddToContext=*/false);
10883 
10884       // Similarly, dive into enums and fish their constants out, making them
10885       // accessible in this scope.
10886       if (auto *ED = dyn_cast<EnumDecl>(D)) {
10887         for (auto *EI : ED->enumerators())
10888           PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
10889       }
10890     }
10891   }
10892 
10893   // Ensure that the function's exception specification is instantiated.
10894   if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
10895     ResolveExceptionSpec(D->getLocation(), FPT);
10896 
10897   // dllimport cannot be applied to non-inline function definitions.
10898   if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
10899       !FD->isTemplateInstantiation()) {
10900     assert(!FD->hasAttr<DLLExportAttr>());
10901     Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
10902     FD->setInvalidDecl();
10903     return D;
10904   }
10905   // We want to attach documentation to original Decl (which might be
10906   // a function template).
10907   ActOnDocumentableDecl(D);
10908   if (getCurLexicalContext()->isObjCContainer() &&
10909       getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
10910       getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
10911     Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
10912 
10913   return D;
10914 }
10915 
10916 /// \brief Given the set of return statements within a function body,
10917 /// compute the variables that are subject to the named return value
10918 /// optimization.
10919 ///
10920 /// Each of the variables that is subject to the named return value
10921 /// optimization will be marked as NRVO variables in the AST, and any
10922 /// return statement that has a marked NRVO variable as its NRVO candidate can
10923 /// use the named return value optimization.
10924 ///
10925 /// This function applies a very simplistic algorithm for NRVO: if every return
10926 /// statement in the scope of a variable has the same NRVO candidate, that
10927 /// candidate is an NRVO variable.
10928 void Sema::computeNRVO(Stmt *Body, FunctionScopeInfo *Scope) {
10929   ReturnStmt **Returns = Scope->Returns.data();
10930 
10931   for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
10932     if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
10933       if (!NRVOCandidate->isNRVOVariable())
10934         Returns[I]->setNRVOCandidate(nullptr);
10935     }
10936   }
10937 }
10938 
10939 bool Sema::canDelayFunctionBody(const Declarator &D) {
10940   // We can't delay parsing the body of a constexpr function template (yet).
10941   if (D.getDeclSpec().isConstexprSpecified())
10942     return false;
10943 
10944   // We can't delay parsing the body of a function template with a deduced
10945   // return type (yet).
10946   if (D.getDeclSpec().containsPlaceholderType()) {
10947     // If the placeholder introduces a non-deduced trailing return type,
10948     // we can still delay parsing it.
10949     if (D.getNumTypeObjects()) {
10950       const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
10951       if (Outer.Kind == DeclaratorChunk::Function &&
10952           Outer.Fun.hasTrailingReturnType()) {
10953         QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
10954         return Ty.isNull() || !Ty->isUndeducedType();
10955       }
10956     }
10957     return false;
10958   }
10959 
10960   return true;
10961 }
10962 
10963 bool Sema::canSkipFunctionBody(Decl *D) {
10964   // We cannot skip the body of a function (or function template) which is
10965   // constexpr, since we may need to evaluate its body in order to parse the
10966   // rest of the file.
10967   // We cannot skip the body of a function with an undeduced return type,
10968   // because any callers of that function need to know the type.
10969   if (const FunctionDecl *FD = D->getAsFunction())
10970     if (FD->isConstexpr() || FD->getReturnType()->isUndeducedType())
10971       return false;
10972   return Consumer.shouldSkipFunctionBody(D);
10973 }
10974 
10975 Decl *Sema::ActOnSkippedFunctionBody(Decl *Decl) {
10976   if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Decl))
10977     FD->setHasSkippedBody();
10978   else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(Decl))
10979     MD->setHasSkippedBody();
10980   return ActOnFinishFunctionBody(Decl, nullptr);
10981 }
10982 
10983 Decl *Sema::ActOnFinishFunctionBody(Decl *D, Stmt *BodyArg) {
10984   return ActOnFinishFunctionBody(D, BodyArg, false);
10985 }
10986 
10987 Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt *Body,
10988                                     bool IsInstantiation) {
10989   FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
10990 
10991   sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
10992   sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
10993 
10994   if (getLangOpts().Coroutines && !getCurFunction()->CoroutineStmts.empty())
10995     CheckCompletedCoroutineBody(FD, Body);
10996 
10997   if (FD) {
10998     FD->setBody(Body);
10999 
11000     if (getLangOpts().CPlusPlus14 && !FD->isInvalidDecl() && Body &&
11001         !FD->isDependentContext() && FD->getReturnType()->isUndeducedType()) {
11002       // If the function has a deduced result type but contains no 'return'
11003       // statements, the result type as written must be exactly 'auto', and
11004       // the deduced result type is 'void'.
11005       if (!FD->getReturnType()->getAs<AutoType>()) {
11006         Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
11007             << FD->getReturnType();
11008         FD->setInvalidDecl();
11009       } else {
11010         // Substitute 'void' for the 'auto' in the type.
11011         TypeLoc ResultType = getReturnTypeLoc(FD);
11012         Context.adjustDeducedFunctionResultType(
11013             FD, SubstAutoType(ResultType.getType(), Context.VoidTy));
11014       }
11015     } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
11016       auto *LSI = getCurLambda();
11017       if (LSI->HasImplicitReturnType) {
11018         deduceClosureReturnType(*LSI);
11019 
11020         // C++11 [expr.prim.lambda]p4:
11021         //   [...] if there are no return statements in the compound-statement
11022         //   [the deduced type is] the type void
11023         QualType RetType =
11024             LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
11025 
11026         // Update the return type to the deduced type.
11027         const FunctionProtoType *Proto =
11028             FD->getType()->getAs<FunctionProtoType>();
11029         FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
11030                                             Proto->getExtProtoInfo()));
11031       }
11032     }
11033 
11034     // The only way to be included in UndefinedButUsed is if there is an
11035     // ODR use before the definition. Avoid the expensive map lookup if this
11036     // is the first declaration.
11037     if (!FD->isFirstDecl() && FD->getPreviousDecl()->isUsed()) {
11038       if (!FD->isExternallyVisible())
11039         UndefinedButUsed.erase(FD);
11040       else if (FD->isInlined() &&
11041                !LangOpts.GNUInline &&
11042                (!FD->getPreviousDecl()->hasAttr<GNUInlineAttr>()))
11043         UndefinedButUsed.erase(FD);
11044     }
11045 
11046     // If the function implicitly returns zero (like 'main') or is naked,
11047     // don't complain about missing return statements.
11048     if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
11049       WP.disableCheckFallThrough();
11050 
11051     // MSVC permits the use of pure specifier (=0) on function definition,
11052     // defined at class scope, warn about this non-standard construct.
11053     if (getLangOpts().MicrosoftExt && FD->isPure() && FD->isCanonicalDecl())
11054       Diag(FD->getLocation(), diag::ext_pure_function_definition);
11055 
11056     if (!FD->isInvalidDecl()) {
11057       // Don't diagnose unused parameters of defaulted or deleted functions.
11058       if (!FD->isDeleted() && !FD->isDefaulted())
11059         DiagnoseUnusedParameters(FD->param_begin(), FD->param_end());
11060       DiagnoseSizeOfParametersAndReturnValue(FD->param_begin(), FD->param_end(),
11061                                              FD->getReturnType(), FD);
11062 
11063       // If this is a structor, we need a vtable.
11064       if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
11065         MarkVTableUsed(FD->getLocation(), Constructor->getParent());
11066       else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(FD))
11067         MarkVTableUsed(FD->getLocation(), Destructor->getParent());
11068 
11069       // Try to apply the named return value optimization. We have to check
11070       // if we can do this here because lambdas keep return statements around
11071       // to deduce an implicit return type.
11072       if (getLangOpts().CPlusPlus && FD->getReturnType()->isRecordType() &&
11073           !FD->isDependentContext())
11074         computeNRVO(Body, getCurFunction());
11075     }
11076 
11077     // GNU warning -Wmissing-prototypes:
11078     //   Warn if a global function is defined without a previous
11079     //   prototype declaration. This warning is issued even if the
11080     //   definition itself provides a prototype. The aim is to detect
11081     //   global functions that fail to be declared in header files.
11082     const FunctionDecl *PossibleZeroParamPrototype = nullptr;
11083     if (ShouldWarnAboutMissingPrototype(FD, PossibleZeroParamPrototype)) {
11084       Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
11085 
11086       if (PossibleZeroParamPrototype) {
11087         // We found a declaration that is not a prototype,
11088         // but that could be a zero-parameter prototype
11089         if (TypeSourceInfo *TI =
11090                 PossibleZeroParamPrototype->getTypeSourceInfo()) {
11091           TypeLoc TL = TI->getTypeLoc();
11092           if (FunctionNoProtoTypeLoc FTL = TL.getAs<FunctionNoProtoTypeLoc>())
11093             Diag(PossibleZeroParamPrototype->getLocation(),
11094                  diag::note_declaration_not_a_prototype)
11095                 << PossibleZeroParamPrototype
11096                 << FixItHint::CreateInsertion(FTL.getRParenLoc(), "void");
11097         }
11098       }
11099     }
11100 
11101     if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
11102       const CXXMethodDecl *KeyFunction;
11103       if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
11104           MD->isVirtual() &&
11105           (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
11106           MD == KeyFunction->getCanonicalDecl()) {
11107         // Update the key-function state if necessary for this ABI.
11108         if (FD->isInlined() &&
11109             !Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline()) {
11110           Context.setNonKeyFunction(MD);
11111 
11112           // If the newly-chosen key function is already defined, then we
11113           // need to mark the vtable as used retroactively.
11114           KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
11115           const FunctionDecl *Definition;
11116           if (KeyFunction && KeyFunction->isDefined(Definition))
11117             MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
11118         } else {
11119           // We just defined they key function; mark the vtable as used.
11120           MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
11121         }
11122       }
11123     }
11124 
11125     assert((FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
11126            "Function parsing confused");
11127   } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
11128     assert(MD == getCurMethodDecl() && "Method parsing confused");
11129     MD->setBody(Body);
11130     if (!MD->isInvalidDecl()) {
11131       DiagnoseUnusedParameters(MD->param_begin(), MD->param_end());
11132       DiagnoseSizeOfParametersAndReturnValue(MD->param_begin(), MD->param_end(),
11133                                              MD->getReturnType(), MD);
11134 
11135       if (Body)
11136         computeNRVO(Body, getCurFunction());
11137     }
11138     if (getCurFunction()->ObjCShouldCallSuper) {
11139       Diag(MD->getLocEnd(), diag::warn_objc_missing_super_call)
11140         << MD->getSelector().getAsString();
11141       getCurFunction()->ObjCShouldCallSuper = false;
11142     }
11143     if (getCurFunction()->ObjCWarnForNoDesignatedInitChain) {
11144       const ObjCMethodDecl *InitMethod = nullptr;
11145       bool isDesignated =
11146           MD->isDesignatedInitializerForTheInterface(&InitMethod);
11147       assert(isDesignated && InitMethod);
11148       (void)isDesignated;
11149 
11150       auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
11151         auto IFace = MD->getClassInterface();
11152         if (!IFace)
11153           return false;
11154         auto SuperD = IFace->getSuperClass();
11155         if (!SuperD)
11156           return false;
11157         return SuperD->getIdentifier() ==
11158             NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
11159       };
11160       // Don't issue this warning for unavailable inits or direct subclasses
11161       // of NSObject.
11162       if (!MD->isUnavailable() && !superIsNSObject(MD)) {
11163         Diag(MD->getLocation(),
11164              diag::warn_objc_designated_init_missing_super_call);
11165         Diag(InitMethod->getLocation(),
11166              diag::note_objc_designated_init_marked_here);
11167       }
11168       getCurFunction()->ObjCWarnForNoDesignatedInitChain = false;
11169     }
11170     if (getCurFunction()->ObjCWarnForNoInitDelegation) {
11171       // Don't issue this warning for unavaialable inits.
11172       if (!MD->isUnavailable())
11173         Diag(MD->getLocation(),
11174              diag::warn_objc_secondary_init_missing_init_call);
11175       getCurFunction()->ObjCWarnForNoInitDelegation = false;
11176     }
11177   } else {
11178     return nullptr;
11179   }
11180 
11181   assert(!getCurFunction()->ObjCShouldCallSuper &&
11182          "This should only be set for ObjC methods, which should have been "
11183          "handled in the block above.");
11184 
11185   // Verify and clean out per-function state.
11186   if (Body && (!FD || !FD->isDefaulted())) {
11187     // C++ constructors that have function-try-blocks can't have return
11188     // statements in the handlers of that block. (C++ [except.handle]p14)
11189     // Verify this.
11190     if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
11191       DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
11192 
11193     // Verify that gotos and switch cases don't jump into scopes illegally.
11194     if (getCurFunction()->NeedsScopeChecking() &&
11195         !PP.isCodeCompletionEnabled())
11196       DiagnoseInvalidJumps(Body);
11197 
11198     if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
11199       if (!Destructor->getParent()->isDependentType())
11200         CheckDestructor(Destructor);
11201 
11202       MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
11203                                              Destructor->getParent());
11204     }
11205 
11206     // If any errors have occurred, clear out any temporaries that may have
11207     // been leftover. This ensures that these temporaries won't be picked up for
11208     // deletion in some later function.
11209     if (getDiagnostics().hasErrorOccurred() ||
11210         getDiagnostics().getSuppressAllDiagnostics()) {
11211       DiscardCleanupsInEvaluationContext();
11212     }
11213     if (!getDiagnostics().hasUncompilableErrorOccurred() &&
11214         !isa<FunctionTemplateDecl>(dcl)) {
11215       // Since the body is valid, issue any analysis-based warnings that are
11216       // enabled.
11217       ActivePolicy = &WP;
11218     }
11219 
11220     if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
11221         (!CheckConstexprFunctionDecl(FD) ||
11222          !CheckConstexprFunctionBody(FD, Body)))
11223       FD->setInvalidDecl();
11224 
11225     if (FD && FD->hasAttr<NakedAttr>()) {
11226       for (const Stmt *S : Body->children()) {
11227         if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
11228           Diag(S->getLocStart(), diag::err_non_asm_stmt_in_naked_function);
11229           Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
11230           FD->setInvalidDecl();
11231           break;
11232         }
11233       }
11234     }
11235 
11236     assert(ExprCleanupObjects.size() ==
11237                ExprEvalContexts.back().NumCleanupObjects &&
11238            "Leftover temporaries in function");
11239     assert(!ExprNeedsCleanups && "Unaccounted cleanups in function");
11240     assert(MaybeODRUseExprs.empty() &&
11241            "Leftover expressions for odr-use checking");
11242   }
11243 
11244   if (!IsInstantiation)
11245     PopDeclContext();
11246 
11247   PopFunctionScopeInfo(ActivePolicy, dcl);
11248   // If any errors have occurred, clear out any temporaries that may have
11249   // been leftover. This ensures that these temporaries won't be picked up for
11250   // deletion in some later function.
11251   if (getDiagnostics().hasErrorOccurred()) {
11252     DiscardCleanupsInEvaluationContext();
11253   }
11254 
11255   return dcl;
11256 }
11257 
11258 
11259 /// When we finish delayed parsing of an attribute, we must attach it to the
11260 /// relevant Decl.
11261 void Sema::ActOnFinishDelayedAttribute(Scope *S, Decl *D,
11262                                        ParsedAttributes &Attrs) {
11263   // Always attach attributes to the underlying decl.
11264   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
11265     D = TD->getTemplatedDecl();
11266   ProcessDeclAttributeList(S, D, Attrs.getList());
11267 
11268   if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
11269     if (Method->isStatic())
11270       checkThisInStaticMemberFunctionAttributes(Method);
11271 }
11272 
11273 
11274 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
11275 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
11276 NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
11277                                           IdentifierInfo &II, Scope *S) {
11278   // Before we produce a declaration for an implicitly defined
11279   // function, see whether there was a locally-scoped declaration of
11280   // this name as a function or variable. If so, use that
11281   // (non-visible) declaration, and complain about it.
11282   if (NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II)) {
11283     Diag(Loc, diag::warn_use_out_of_scope_declaration) << ExternCPrev;
11284     Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
11285     return ExternCPrev;
11286   }
11287 
11288   // Extension in C99.  Legal in C90, but warn about it.
11289   unsigned diag_id;
11290   if (II.getName().startswith("__builtin_"))
11291     diag_id = diag::warn_builtin_unknown;
11292   else if (getLangOpts().C99)
11293     diag_id = diag::ext_implicit_function_decl;
11294   else
11295     diag_id = diag::warn_implicit_function_decl;
11296   Diag(Loc, diag_id) << &II;
11297 
11298   // Because typo correction is expensive, only do it if the implicit
11299   // function declaration is going to be treated as an error.
11300   if (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error) {
11301     TypoCorrection Corrected;
11302     if (S &&
11303         (Corrected = CorrectTypo(
11304              DeclarationNameInfo(&II, Loc), LookupOrdinaryName, S, nullptr,
11305              llvm::make_unique<DeclFilterCCC<FunctionDecl>>(), CTK_NonError)))
11306       diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
11307                    /*ErrorRecovery*/false);
11308   }
11309 
11310   // Set a Declarator for the implicit definition: int foo();
11311   const char *Dummy;
11312   AttributeFactory attrFactory;
11313   DeclSpec DS(attrFactory);
11314   unsigned DiagID;
11315   bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
11316                                   Context.getPrintingPolicy());
11317   (void)Error; // Silence warning.
11318   assert(!Error && "Error setting up implicit decl!");
11319   SourceLocation NoLoc;
11320   Declarator D(DS, Declarator::BlockContext);
11321   D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
11322                                              /*IsAmbiguous=*/false,
11323                                              /*LParenLoc=*/NoLoc,
11324                                              /*Params=*/nullptr,
11325                                              /*NumParams=*/0,
11326                                              /*EllipsisLoc=*/NoLoc,
11327                                              /*RParenLoc=*/NoLoc,
11328                                              /*TypeQuals=*/0,
11329                                              /*RefQualifierIsLvalueRef=*/true,
11330                                              /*RefQualifierLoc=*/NoLoc,
11331                                              /*ConstQualifierLoc=*/NoLoc,
11332                                              /*VolatileQualifierLoc=*/NoLoc,
11333                                              /*RestrictQualifierLoc=*/NoLoc,
11334                                              /*MutableLoc=*/NoLoc,
11335                                              EST_None,
11336                                              /*ESpecRange=*/SourceRange(),
11337                                              /*Exceptions=*/nullptr,
11338                                              /*ExceptionRanges=*/nullptr,
11339                                              /*NumExceptions=*/0,
11340                                              /*NoexceptExpr=*/nullptr,
11341                                              /*ExceptionSpecTokens=*/nullptr,
11342                                              Loc, Loc, D),
11343                 DS.getAttributes(),
11344                 SourceLocation());
11345   D.SetIdentifier(&II, Loc);
11346 
11347   // Insert this function into translation-unit scope.
11348 
11349   DeclContext *PrevDC = CurContext;
11350   CurContext = Context.getTranslationUnitDecl();
11351 
11352   FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(TUScope, D));
11353   FD->setImplicit();
11354 
11355   CurContext = PrevDC;
11356 
11357   AddKnownFunctionAttributes(FD);
11358 
11359   return FD;
11360 }
11361 
11362 /// \brief Adds any function attributes that we know a priori based on
11363 /// the declaration of this function.
11364 ///
11365 /// These attributes can apply both to implicitly-declared builtins
11366 /// (like __builtin___printf_chk) or to library-declared functions
11367 /// like NSLog or printf.
11368 ///
11369 /// We need to check for duplicate attributes both here and where user-written
11370 /// attributes are applied to declarations.
11371 void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
11372   if (FD->isInvalidDecl())
11373     return;
11374 
11375   // If this is a built-in function, map its builtin attributes to
11376   // actual attributes.
11377   if (unsigned BuiltinID = FD->getBuiltinID()) {
11378     // Handle printf-formatting attributes.
11379     unsigned FormatIdx;
11380     bool HasVAListArg;
11381     if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
11382       if (!FD->hasAttr<FormatAttr>()) {
11383         const char *fmt = "printf";
11384         unsigned int NumParams = FD->getNumParams();
11385         if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
11386             FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
11387           fmt = "NSString";
11388         FD->addAttr(FormatAttr::CreateImplicit(Context,
11389                                                &Context.Idents.get(fmt),
11390                                                FormatIdx+1,
11391                                                HasVAListArg ? 0 : FormatIdx+2,
11392                                                FD->getLocation()));
11393       }
11394     }
11395     if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
11396                                              HasVAListArg)) {
11397      if (!FD->hasAttr<FormatAttr>())
11398        FD->addAttr(FormatAttr::CreateImplicit(Context,
11399                                               &Context.Idents.get("scanf"),
11400                                               FormatIdx+1,
11401                                               HasVAListArg ? 0 : FormatIdx+2,
11402                                               FD->getLocation()));
11403     }
11404 
11405     // Mark const if we don't care about errno and that is the only
11406     // thing preventing the function from being const. This allows
11407     // IRgen to use LLVM intrinsics for such functions.
11408     if (!getLangOpts().MathErrno &&
11409         Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
11410       if (!FD->hasAttr<ConstAttr>())
11411         FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11412     }
11413 
11414     if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
11415         !FD->hasAttr<ReturnsTwiceAttr>())
11416       FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
11417                                          FD->getLocation()));
11418     if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
11419       FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
11420     if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
11421       FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
11422     if (getLangOpts().CUDA && getLangOpts().CUDATargetOverloads &&
11423         Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
11424         !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
11425       // Assign appropriate attribute depending on CUDA compilation
11426       // mode and the target builtin belongs to. E.g. during host
11427       // compilation, aux builtins are __device__, the rest are __host__.
11428       if (getLangOpts().CUDAIsDevice !=
11429           Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
11430         FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
11431       else
11432         FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
11433     }
11434   }
11435 
11436   IdentifierInfo *Name = FD->getIdentifier();
11437   if (!Name)
11438     return;
11439   if ((!getLangOpts().CPlusPlus &&
11440        FD->getDeclContext()->isTranslationUnit()) ||
11441       (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
11442        cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
11443        LinkageSpecDecl::lang_c)) {
11444     // Okay: this could be a libc/libm/Objective-C function we know
11445     // about.
11446   } else
11447     return;
11448 
11449   if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
11450     // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
11451     // target-specific builtins, perhaps?
11452     if (!FD->hasAttr<FormatAttr>())
11453       FD->addAttr(FormatAttr::CreateImplicit(Context,
11454                                              &Context.Idents.get("printf"), 2,
11455                                              Name->isStr("vasprintf") ? 0 : 3,
11456                                              FD->getLocation()));
11457   }
11458 
11459   if (Name->isStr("__CFStringMakeConstantString")) {
11460     // We already have a __builtin___CFStringMakeConstantString,
11461     // but builds that use -fno-constant-cfstrings don't go through that.
11462     if (!FD->hasAttr<FormatArgAttr>())
11463       FD->addAttr(FormatArgAttr::CreateImplicit(Context, 1,
11464                                                 FD->getLocation()));
11465   }
11466 }
11467 
11468 TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
11469                                     TypeSourceInfo *TInfo) {
11470   assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
11471   assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
11472 
11473   if (!TInfo) {
11474     assert(D.isInvalidType() && "no declarator info for valid type");
11475     TInfo = Context.getTrivialTypeSourceInfo(T);
11476   }
11477 
11478   // Scope manipulation handled by caller.
11479   TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
11480                                            D.getLocStart(),
11481                                            D.getIdentifierLoc(),
11482                                            D.getIdentifier(),
11483                                            TInfo);
11484 
11485   // Bail out immediately if we have an invalid declaration.
11486   if (D.isInvalidType()) {
11487     NewTD->setInvalidDecl();
11488     return NewTD;
11489   }
11490 
11491   if (D.getDeclSpec().isModulePrivateSpecified()) {
11492     if (CurContext->isFunctionOrMethod())
11493       Diag(NewTD->getLocation(), diag::err_module_private_local)
11494         << 2 << NewTD->getDeclName()
11495         << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
11496         << FixItHint::CreateRemoval(D.getDeclSpec().getModulePrivateSpecLoc());
11497     else
11498       NewTD->setModulePrivate();
11499   }
11500 
11501   // C++ [dcl.typedef]p8:
11502   //   If the typedef declaration defines an unnamed class (or
11503   //   enum), the first typedef-name declared by the declaration
11504   //   to be that class type (or enum type) is used to denote the
11505   //   class type (or enum type) for linkage purposes only.
11506   // We need to check whether the type was declared in the declaration.
11507   switch (D.getDeclSpec().getTypeSpecType()) {
11508   case TST_enum:
11509   case TST_struct:
11510   case TST_interface:
11511   case TST_union:
11512   case TST_class: {
11513     TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
11514     setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
11515     break;
11516   }
11517 
11518   default:
11519     break;
11520   }
11521 
11522   return NewTD;
11523 }
11524 
11525 
11526 /// \brief Check that this is a valid underlying type for an enum declaration.
11527 bool Sema::CheckEnumUnderlyingType(TypeSourceInfo *TI) {
11528   SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
11529   QualType T = TI->getType();
11530 
11531   if (T->isDependentType())
11532     return false;
11533 
11534   if (const BuiltinType *BT = T->getAs<BuiltinType>())
11535     if (BT->isInteger())
11536       return false;
11537 
11538   Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
11539   return true;
11540 }
11541 
11542 /// Check whether this is a valid redeclaration of a previous enumeration.
11543 /// \return true if the redeclaration was invalid.
11544 bool Sema::CheckEnumRedeclaration(
11545     SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy,
11546     bool EnumUnderlyingIsImplicit, const EnumDecl *Prev) {
11547   bool IsFixed = !EnumUnderlyingTy.isNull();
11548 
11549   if (IsScoped != Prev->isScoped()) {
11550     Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
11551       << Prev->isScoped();
11552     Diag(Prev->getLocation(), diag::note_previous_declaration);
11553     return true;
11554   }
11555 
11556   if (IsFixed && Prev->isFixed()) {
11557     if (!EnumUnderlyingTy->isDependentType() &&
11558         !Prev->getIntegerType()->isDependentType() &&
11559         !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
11560                                         Prev->getIntegerType())) {
11561       // TODO: Highlight the underlying type of the redeclaration.
11562       Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
11563         << EnumUnderlyingTy << Prev->getIntegerType();
11564       Diag(Prev->getLocation(), diag::note_previous_declaration)
11565           << Prev->getIntegerTypeRange();
11566       return true;
11567     }
11568   } else if (IsFixed && !Prev->isFixed() && EnumUnderlyingIsImplicit) {
11569     ;
11570   } else if (!IsFixed && Prev->isFixed() && !Prev->getIntegerTypeSourceInfo()) {
11571     ;
11572   } else if (IsFixed != Prev->isFixed()) {
11573     Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
11574       << Prev->isFixed();
11575     Diag(Prev->getLocation(), diag::note_previous_declaration);
11576     return true;
11577   }
11578 
11579   return false;
11580 }
11581 
11582 /// \brief Get diagnostic %select index for tag kind for
11583 /// redeclaration diagnostic message.
11584 /// WARNING: Indexes apply to particular diagnostics only!
11585 ///
11586 /// \returns diagnostic %select index.
11587 static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag) {
11588   switch (Tag) {
11589   case TTK_Struct: return 0;
11590   case TTK_Interface: return 1;
11591   case TTK_Class:  return 2;
11592   default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
11593   }
11594 }
11595 
11596 /// \brief Determine if tag kind is a class-key compatible with
11597 /// class for redeclaration (class, struct, or __interface).
11598 ///
11599 /// \returns true iff the tag kind is compatible.
11600 static bool isClassCompatTagKind(TagTypeKind Tag)
11601 {
11602   return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
11603 }
11604 
11605 /// \brief Determine whether a tag with a given kind is acceptable
11606 /// as a redeclaration of the given tag declaration.
11607 ///
11608 /// \returns true if the new tag kind is acceptable, false otherwise.
11609 bool Sema::isAcceptableTagRedeclaration(const TagDecl *Previous,
11610                                         TagTypeKind NewTag, bool isDefinition,
11611                                         SourceLocation NewTagLoc,
11612                                         const IdentifierInfo *Name) {
11613   // C++ [dcl.type.elab]p3:
11614   //   The class-key or enum keyword present in the
11615   //   elaborated-type-specifier shall agree in kind with the
11616   //   declaration to which the name in the elaborated-type-specifier
11617   //   refers. This rule also applies to the form of
11618   //   elaborated-type-specifier that declares a class-name or
11619   //   friend class since it can be construed as referring to the
11620   //   definition of the class. Thus, in any
11621   //   elaborated-type-specifier, the enum keyword shall be used to
11622   //   refer to an enumeration (7.2), the union class-key shall be
11623   //   used to refer to a union (clause 9), and either the class or
11624   //   struct class-key shall be used to refer to a class (clause 9)
11625   //   declared using the class or struct class-key.
11626   TagTypeKind OldTag = Previous->getTagKind();
11627   if (!isDefinition || !isClassCompatTagKind(NewTag))
11628     if (OldTag == NewTag)
11629       return true;
11630 
11631   if (isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)) {
11632     // Warn about the struct/class tag mismatch.
11633     bool isTemplate = false;
11634     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
11635       isTemplate = Record->getDescribedClassTemplate();
11636 
11637     if (!ActiveTemplateInstantiations.empty()) {
11638       // In a template instantiation, do not offer fix-its for tag mismatches
11639       // since they usually mess up the template instead of fixing the problem.
11640       Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11641         << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11642         << getRedeclDiagFromTagKind(OldTag);
11643       return true;
11644     }
11645 
11646     if (isDefinition) {
11647       // On definitions, check previous tags and issue a fix-it for each
11648       // one that doesn't match the current tag.
11649       if (Previous->getDefinition()) {
11650         // Don't suggest fix-its for redefinitions.
11651         return true;
11652       }
11653 
11654       bool previousMismatch = false;
11655       for (auto I : Previous->redecls()) {
11656         if (I->getTagKind() != NewTag) {
11657           if (!previousMismatch) {
11658             previousMismatch = true;
11659             Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
11660               << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11661               << getRedeclDiagFromTagKind(I->getTagKind());
11662           }
11663           Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
11664             << getRedeclDiagFromTagKind(NewTag)
11665             << FixItHint::CreateReplacement(I->getInnerLocStart(),
11666                  TypeWithKeyword::getTagTypeKindName(NewTag));
11667         }
11668       }
11669       return true;
11670     }
11671 
11672     // Check for a previous definition.  If current tag and definition
11673     // are same type, do nothing.  If no definition, but disagree with
11674     // with previous tag type, give a warning, but no fix-it.
11675     const TagDecl *Redecl = Previous->getDefinition() ?
11676                             Previous->getDefinition() : Previous;
11677     if (Redecl->getTagKind() == NewTag) {
11678       return true;
11679     }
11680 
11681     Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
11682       << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
11683       << getRedeclDiagFromTagKind(OldTag);
11684     Diag(Redecl->getLocation(), diag::note_previous_use);
11685 
11686     // If there is a previous definition, suggest a fix-it.
11687     if (Previous->getDefinition()) {
11688         Diag(NewTagLoc, diag::note_struct_class_suggestion)
11689           << getRedeclDiagFromTagKind(Redecl->getTagKind())
11690           << FixItHint::CreateReplacement(SourceRange(NewTagLoc),
11691                TypeWithKeyword::getTagTypeKindName(Redecl->getTagKind()));
11692     }
11693 
11694     return true;
11695   }
11696   return false;
11697 }
11698 
11699 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
11700 /// from an outer enclosing namespace or file scope inside a friend declaration.
11701 /// This should provide the commented out code in the following snippet:
11702 ///   namespace N {
11703 ///     struct X;
11704 ///     namespace M {
11705 ///       struct Y { friend struct /*N::*/ X; };
11706 ///     }
11707 ///   }
11708 static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S,
11709                                          SourceLocation NameLoc) {
11710   // While the decl is in a namespace, do repeated lookup of that name and see
11711   // if we get the same namespace back.  If we do not, continue until
11712   // translation unit scope, at which point we have a fully qualified NNS.
11713   SmallVector<IdentifierInfo *, 4> Namespaces;
11714   DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11715   for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
11716     // This tag should be declared in a namespace, which can only be enclosed by
11717     // other namespaces.  Bail if there's an anonymous namespace in the chain.
11718     NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
11719     if (!Namespace || Namespace->isAnonymousNamespace())
11720       return FixItHint();
11721     IdentifierInfo *II = Namespace->getIdentifier();
11722     Namespaces.push_back(II);
11723     NamedDecl *Lookup = SemaRef.LookupSingleName(
11724         S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
11725     if (Lookup == Namespace)
11726       break;
11727   }
11728 
11729   // Once we have all the namespaces, reverse them to go outermost first, and
11730   // build an NNS.
11731   SmallString<64> Insertion;
11732   llvm::raw_svector_ostream OS(Insertion);
11733   if (DC->isTranslationUnit())
11734     OS << "::";
11735   std::reverse(Namespaces.begin(), Namespaces.end());
11736   for (auto *II : Namespaces)
11737     OS << II->getName() << "::";
11738   return FixItHint::CreateInsertion(NameLoc, Insertion);
11739 }
11740 
11741 /// \brief Determine whether a tag originally declared in context \p OldDC can
11742 /// be redeclared with an unqualfied name in \p NewDC (assuming name lookup
11743 /// found a declaration in \p OldDC as a previous decl, perhaps through a
11744 /// using-declaration).
11745 static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC,
11746                                          DeclContext *NewDC) {
11747   OldDC = OldDC->getRedeclContext();
11748   NewDC = NewDC->getRedeclContext();
11749 
11750   if (OldDC->Equals(NewDC))
11751     return true;
11752 
11753   // In MSVC mode, we allow a redeclaration if the contexts are related (either
11754   // encloses the other).
11755   if (S.getLangOpts().MSVCCompat &&
11756       (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
11757     return true;
11758 
11759   return false;
11760 }
11761 
11762 /// \brief This is invoked when we see 'struct foo' or 'struct {'.  In the
11763 /// former case, Name will be non-null.  In the later case, Name will be null.
11764 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
11765 /// reference/declaration/definition of a tag.
11766 ///
11767 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
11768 /// trailing-type-specifier) other than one in an alias-declaration.
11769 ///
11770 /// \param SkipBody If non-null, will be set to indicate if the caller should
11771 /// skip the definition of this tag and treat it as if it were a declaration.
11772 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
11773                      SourceLocation KWLoc, CXXScopeSpec &SS,
11774                      IdentifierInfo *Name, SourceLocation NameLoc,
11775                      AttributeList *Attr, AccessSpecifier AS,
11776                      SourceLocation ModulePrivateLoc,
11777                      MultiTemplateParamsArg TemplateParameterLists,
11778                      bool &OwnedDecl, bool &IsDependent,
11779                      SourceLocation ScopedEnumKWLoc,
11780                      bool ScopedEnumUsesClassTag,
11781                      TypeResult UnderlyingType,
11782                      bool IsTypeSpecifier, SkipBodyInfo *SkipBody) {
11783   // If this is not a definition, it must have a name.
11784   IdentifierInfo *OrigName = Name;
11785   assert((Name != nullptr || TUK == TUK_Definition) &&
11786          "Nameless record must be a definition!");
11787   assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
11788 
11789   OwnedDecl = false;
11790   TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
11791   bool ScopedEnum = ScopedEnumKWLoc.isValid();
11792 
11793   // FIXME: Check explicit specializations more carefully.
11794   bool isExplicitSpecialization = false;
11795   bool Invalid = false;
11796 
11797   // We only need to do this matching if we have template parameters
11798   // or a scope specifier, which also conveniently avoids this work
11799   // for non-C++ cases.
11800   if (TemplateParameterLists.size() > 0 ||
11801       (SS.isNotEmpty() && TUK != TUK_Reference)) {
11802     if (TemplateParameterList *TemplateParams =
11803             MatchTemplateParametersToScopeSpecifier(
11804                 KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
11805                 TUK == TUK_Friend, isExplicitSpecialization, Invalid)) {
11806       if (Kind == TTK_Enum) {
11807         Diag(KWLoc, diag::err_enum_template);
11808         return nullptr;
11809       }
11810 
11811       if (TemplateParams->size() > 0) {
11812         // This is a declaration or definition of a class template (which may
11813         // be a member of another template).
11814 
11815         if (Invalid)
11816           return nullptr;
11817 
11818         OwnedDecl = false;
11819         DeclResult Result = CheckClassTemplate(S, TagSpec, TUK, KWLoc,
11820                                                SS, Name, NameLoc, Attr,
11821                                                TemplateParams, AS,
11822                                                ModulePrivateLoc,
11823                                                /*FriendLoc*/SourceLocation(),
11824                                                TemplateParameterLists.size()-1,
11825                                                TemplateParameterLists.data(),
11826                                                SkipBody);
11827         return Result.get();
11828       } else {
11829         // The "template<>" header is extraneous.
11830         Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
11831           << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
11832         isExplicitSpecialization = true;
11833       }
11834     }
11835   }
11836 
11837   // Figure out the underlying type if this a enum declaration. We need to do
11838   // this early, because it's needed to detect if this is an incompatible
11839   // redeclaration.
11840   llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
11841   bool EnumUnderlyingIsImplicit = false;
11842 
11843   if (Kind == TTK_Enum) {
11844     if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum))
11845       // No underlying type explicitly specified, or we failed to parse the
11846       // type, default to int.
11847       EnumUnderlying = Context.IntTy.getTypePtr();
11848     else if (UnderlyingType.get()) {
11849       // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
11850       // integral type; any cv-qualification is ignored.
11851       TypeSourceInfo *TI = nullptr;
11852       GetTypeFromParser(UnderlyingType.get(), &TI);
11853       EnumUnderlying = TI;
11854 
11855       if (CheckEnumUnderlyingType(TI))
11856         // Recover by falling back to int.
11857         EnumUnderlying = Context.IntTy.getTypePtr();
11858 
11859       if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
11860                                           UPPC_FixedUnderlyingType))
11861         EnumUnderlying = Context.IntTy.getTypePtr();
11862 
11863     } else if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
11864       if (getLangOpts().MSVCCompat || TUK == TUK_Definition) {
11865         // Microsoft enums are always of int type.
11866         EnumUnderlying = Context.IntTy.getTypePtr();
11867         EnumUnderlyingIsImplicit = true;
11868       }
11869     }
11870   }
11871 
11872   DeclContext *SearchDC = CurContext;
11873   DeclContext *DC = CurContext;
11874   bool isStdBadAlloc = false;
11875 
11876   RedeclarationKind Redecl = ForRedeclaration;
11877   if (TUK == TUK_Friend || TUK == TUK_Reference)
11878     Redecl = NotForRedeclaration;
11879 
11880   LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
11881   if (Name && SS.isNotEmpty()) {
11882     // We have a nested-name tag ('struct foo::bar').
11883 
11884     // Check for invalid 'foo::'.
11885     if (SS.isInvalid()) {
11886       Name = nullptr;
11887       goto CreateNewDecl;
11888     }
11889 
11890     // If this is a friend or a reference to a class in a dependent
11891     // context, don't try to make a decl for it.
11892     if (TUK == TUK_Friend || TUK == TUK_Reference) {
11893       DC = computeDeclContext(SS, false);
11894       if (!DC) {
11895         IsDependent = true;
11896         return nullptr;
11897       }
11898     } else {
11899       DC = computeDeclContext(SS, true);
11900       if (!DC) {
11901         Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
11902           << SS.getRange();
11903         return nullptr;
11904       }
11905     }
11906 
11907     if (RequireCompleteDeclContext(SS, DC))
11908       return nullptr;
11909 
11910     SearchDC = DC;
11911     // Look-up name inside 'foo::'.
11912     LookupQualifiedName(Previous, DC);
11913 
11914     if (Previous.isAmbiguous())
11915       return nullptr;
11916 
11917     if (Previous.empty()) {
11918       // Name lookup did not find anything. However, if the
11919       // nested-name-specifier refers to the current instantiation,
11920       // and that current instantiation has any dependent base
11921       // classes, we might find something at instantiation time: treat
11922       // this as a dependent elaborated-type-specifier.
11923       // But this only makes any sense for reference-like lookups.
11924       if (Previous.wasNotFoundInCurrentInstantiation() &&
11925           (TUK == TUK_Reference || TUK == TUK_Friend)) {
11926         IsDependent = true;
11927         return nullptr;
11928       }
11929 
11930       // A tag 'foo::bar' must already exist.
11931       Diag(NameLoc, diag::err_not_tag_in_scope)
11932         << Kind << Name << DC << SS.getRange();
11933       Name = nullptr;
11934       Invalid = true;
11935       goto CreateNewDecl;
11936     }
11937   } else if (Name) {
11938     // C++14 [class.mem]p14:
11939     //   If T is the name of a class, then each of the following shall have a
11940     //   name different from T:
11941     //    -- every member of class T that is itself a type
11942     if (TUK != TUK_Reference && TUK != TUK_Friend &&
11943         DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
11944       return nullptr;
11945 
11946     // If this is a named struct, check to see if there was a previous forward
11947     // declaration or definition.
11948     // FIXME: We're looking into outer scopes here, even when we
11949     // shouldn't be. Doing so can result in ambiguities that we
11950     // shouldn't be diagnosing.
11951     LookupName(Previous, S);
11952 
11953     // When declaring or defining a tag, ignore ambiguities introduced
11954     // by types using'ed into this scope.
11955     if (Previous.isAmbiguous() &&
11956         (TUK == TUK_Definition || TUK == TUK_Declaration)) {
11957       LookupResult::Filter F = Previous.makeFilter();
11958       while (F.hasNext()) {
11959         NamedDecl *ND = F.next();
11960         if (ND->getDeclContext()->getRedeclContext() != SearchDC)
11961           F.erase();
11962       }
11963       F.done();
11964     }
11965 
11966     // C++11 [namespace.memdef]p3:
11967     //   If the name in a friend declaration is neither qualified nor
11968     //   a template-id and the declaration is a function or an
11969     //   elaborated-type-specifier, the lookup to determine whether
11970     //   the entity has been previously declared shall not consider
11971     //   any scopes outside the innermost enclosing namespace.
11972     //
11973     // MSVC doesn't implement the above rule for types, so a friend tag
11974     // declaration may be a redeclaration of a type declared in an enclosing
11975     // scope.  They do implement this rule for friend functions.
11976     //
11977     // Does it matter that this should be by scope instead of by
11978     // semantic context?
11979     if (!Previous.empty() && TUK == TUK_Friend) {
11980       DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
11981       LookupResult::Filter F = Previous.makeFilter();
11982       bool FriendSawTagOutsideEnclosingNamespace = false;
11983       while (F.hasNext()) {
11984         NamedDecl *ND = F.next();
11985         DeclContext *DC = ND->getDeclContext()->getRedeclContext();
11986         if (DC->isFileContext() &&
11987             !EnclosingNS->Encloses(ND->getDeclContext())) {
11988           if (getLangOpts().MSVCCompat)
11989             FriendSawTagOutsideEnclosingNamespace = true;
11990           else
11991             F.erase();
11992         }
11993       }
11994       F.done();
11995 
11996       // Diagnose this MSVC extension in the easy case where lookup would have
11997       // unambiguously found something outside the enclosing namespace.
11998       if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
11999         NamedDecl *ND = Previous.getFoundDecl();
12000         Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
12001             << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
12002       }
12003     }
12004 
12005     // Note:  there used to be some attempt at recovery here.
12006     if (Previous.isAmbiguous())
12007       return nullptr;
12008 
12009     if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
12010       // FIXME: This makes sure that we ignore the contexts associated
12011       // with C structs, unions, and enums when looking for a matching
12012       // tag declaration or definition. See the similar lookup tweak
12013       // in Sema::LookupName; is there a better way to deal with this?
12014       while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
12015         SearchDC = SearchDC->getParent();
12016     }
12017   }
12018 
12019   if (Previous.isSingleResult() &&
12020       Previous.getFoundDecl()->isTemplateParameter()) {
12021     // Maybe we will complain about the shadowed template parameter.
12022     DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
12023     // Just pretend that we didn't see the previous declaration.
12024     Previous.clear();
12025   }
12026 
12027   if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
12028       DC->Equals(getStdNamespace()) && Name->isStr("bad_alloc")) {
12029     // This is a declaration of or a reference to "std::bad_alloc".
12030     isStdBadAlloc = true;
12031 
12032     if (Previous.empty() && StdBadAlloc) {
12033       // std::bad_alloc has been implicitly declared (but made invisible to
12034       // name lookup). Fill in this implicit declaration as the previous
12035       // declaration, so that the declarations get chained appropriately.
12036       Previous.addDecl(getStdBadAlloc());
12037     }
12038   }
12039 
12040   // If we didn't find a previous declaration, and this is a reference
12041   // (or friend reference), move to the correct scope.  In C++, we
12042   // also need to do a redeclaration lookup there, just in case
12043   // there's a shadow friend decl.
12044   if (Name && Previous.empty() &&
12045       (TUK == TUK_Reference || TUK == TUK_Friend)) {
12046     if (Invalid) goto CreateNewDecl;
12047     assert(SS.isEmpty());
12048 
12049     if (TUK == TUK_Reference) {
12050       // C++ [basic.scope.pdecl]p5:
12051       //   -- for an elaborated-type-specifier of the form
12052       //
12053       //          class-key identifier
12054       //
12055       //      if the elaborated-type-specifier is used in the
12056       //      decl-specifier-seq or parameter-declaration-clause of a
12057       //      function defined in namespace scope, the identifier is
12058       //      declared as a class-name in the namespace that contains
12059       //      the declaration; otherwise, except as a friend
12060       //      declaration, the identifier is declared in the smallest
12061       //      non-class, non-function-prototype scope that contains the
12062       //      declaration.
12063       //
12064       // C99 6.7.2.3p8 has a similar (but not identical!) provision for
12065       // C structs and unions.
12066       //
12067       // It is an error in C++ to declare (rather than define) an enum
12068       // type, including via an elaborated type specifier.  We'll
12069       // diagnose that later; for now, declare the enum in the same
12070       // scope as we would have picked for any other tag type.
12071       //
12072       // GNU C also supports this behavior as part of its incomplete
12073       // enum types extension, while GNU C++ does not.
12074       //
12075       // Find the context where we'll be declaring the tag.
12076       // FIXME: We would like to maintain the current DeclContext as the
12077       // lexical context,
12078       while (!SearchDC->isFileContext() && !SearchDC->isFunctionOrMethod())
12079         SearchDC = SearchDC->getParent();
12080 
12081       // Find the scope where we'll be declaring the tag.
12082       while (S->isClassScope() ||
12083              (getLangOpts().CPlusPlus &&
12084               S->isFunctionPrototypeScope()) ||
12085              ((S->getFlags() & Scope::DeclScope) == 0) ||
12086              (S->getEntity() && S->getEntity()->isTransparentContext()))
12087         S = S->getParent();
12088     } else {
12089       assert(TUK == TUK_Friend);
12090       // C++ [namespace.memdef]p3:
12091       //   If a friend declaration in a non-local class first declares a
12092       //   class or function, the friend class or function is a member of
12093       //   the innermost enclosing namespace.
12094       SearchDC = SearchDC->getEnclosingNamespaceContext();
12095     }
12096 
12097     // In C++, we need to do a redeclaration lookup to properly
12098     // diagnose some problems.
12099     if (getLangOpts().CPlusPlus) {
12100       Previous.setRedeclarationKind(ForRedeclaration);
12101       LookupQualifiedName(Previous, SearchDC);
12102     }
12103   }
12104 
12105   // If we have a known previous declaration to use, then use it.
12106   if (Previous.empty() && SkipBody && SkipBody->Previous)
12107     Previous.addDecl(SkipBody->Previous);
12108 
12109   if (!Previous.empty()) {
12110     NamedDecl *PrevDecl = Previous.getFoundDecl();
12111     NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
12112 
12113     // It's okay to have a tag decl in the same scope as a typedef
12114     // which hides a tag decl in the same scope.  Finding this
12115     // insanity with a redeclaration lookup can only actually happen
12116     // in C++.
12117     //
12118     // This is also okay for elaborated-type-specifiers, which is
12119     // technically forbidden by the current standard but which is
12120     // okay according to the likely resolution of an open issue;
12121     // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
12122     if (getLangOpts().CPlusPlus) {
12123       if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12124         if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
12125           TagDecl *Tag = TT->getDecl();
12126           if (Tag->getDeclName() == Name &&
12127               Tag->getDeclContext()->getRedeclContext()
12128                           ->Equals(TD->getDeclContext()->getRedeclContext())) {
12129             PrevDecl = Tag;
12130             Previous.clear();
12131             Previous.addDecl(Tag);
12132             Previous.resolveKind();
12133           }
12134         }
12135       }
12136     }
12137 
12138     // If this is a redeclaration of a using shadow declaration, it must
12139     // declare a tag in the same context. In MSVC mode, we allow a
12140     // redefinition if either context is within the other.
12141     if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
12142       auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
12143       if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
12144           isDeclInScope(Shadow, SearchDC, S, isExplicitSpecialization) &&
12145           !(OldTag && isAcceptableTagRedeclContext(
12146                           *this, OldTag->getDeclContext(), SearchDC))) {
12147         Diag(KWLoc, diag::err_using_decl_conflict_reverse);
12148         Diag(Shadow->getTargetDecl()->getLocation(),
12149              diag::note_using_decl_target);
12150         Diag(Shadow->getUsingDecl()->getLocation(), diag::note_using_decl)
12151             << 0;
12152         // Recover by ignoring the old declaration.
12153         Previous.clear();
12154         goto CreateNewDecl;
12155       }
12156     }
12157 
12158     if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
12159       // If this is a use of a previous tag, or if the tag is already declared
12160       // in the same scope (so that the definition/declaration completes or
12161       // rementions the tag), reuse the decl.
12162       if (TUK == TUK_Reference || TUK == TUK_Friend ||
12163           isDeclInScope(DirectPrevDecl, SearchDC, S,
12164                         SS.isNotEmpty() || isExplicitSpecialization)) {
12165         // Make sure that this wasn't declared as an enum and now used as a
12166         // struct or something similar.
12167         if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
12168                                           TUK == TUK_Definition, KWLoc,
12169                                           Name)) {
12170           bool SafeToContinue
12171             = (PrevTagDecl->getTagKind() != TTK_Enum &&
12172                Kind != TTK_Enum);
12173           if (SafeToContinue)
12174             Diag(KWLoc, diag::err_use_with_wrong_tag)
12175               << Name
12176               << FixItHint::CreateReplacement(SourceRange(KWLoc),
12177                                               PrevTagDecl->getKindName());
12178           else
12179             Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
12180           Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
12181 
12182           if (SafeToContinue)
12183             Kind = PrevTagDecl->getTagKind();
12184           else {
12185             // Recover by making this an anonymous redefinition.
12186             Name = nullptr;
12187             Previous.clear();
12188             Invalid = true;
12189           }
12190         }
12191 
12192         if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
12193           const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
12194 
12195           // If this is an elaborated-type-specifier for a scoped enumeration,
12196           // the 'class' keyword is not necessary and not permitted.
12197           if (TUK == TUK_Reference || TUK == TUK_Friend) {
12198             if (ScopedEnum)
12199               Diag(ScopedEnumKWLoc, diag::err_enum_class_reference)
12200                 << PrevEnum->isScoped()
12201                 << FixItHint::CreateRemoval(ScopedEnumKWLoc);
12202             return PrevTagDecl;
12203           }
12204 
12205           QualType EnumUnderlyingTy;
12206           if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12207             EnumUnderlyingTy = TI->getType().getUnqualifiedType();
12208           else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
12209             EnumUnderlyingTy = QualType(T, 0);
12210 
12211           // All conflicts with previous declarations are recovered by
12212           // returning the previous declaration, unless this is a definition,
12213           // in which case we want the caller to bail out.
12214           if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
12215                                      ScopedEnum, EnumUnderlyingTy,
12216                                      EnumUnderlyingIsImplicit, PrevEnum))
12217             return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
12218         }
12219 
12220         // C++11 [class.mem]p1:
12221         //   A member shall not be declared twice in the member-specification,
12222         //   except that a nested class or member class template can be declared
12223         //   and then later defined.
12224         if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
12225             S->isDeclScope(PrevDecl)) {
12226           Diag(NameLoc, diag::ext_member_redeclared);
12227           Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
12228         }
12229 
12230         if (!Invalid) {
12231           // If this is a use, just return the declaration we found, unless
12232           // we have attributes.
12233 
12234           // FIXME: In the future, return a variant or some other clue
12235           // for the consumer of this Decl to know it doesn't own it.
12236           // For our current ASTs this shouldn't be a problem, but will
12237           // need to be changed with DeclGroups.
12238           if (!Attr &&
12239               ((TUK == TUK_Reference &&
12240                 (!PrevTagDecl->getFriendObjectKind() || getLangOpts().MicrosoftExt))
12241                || TUK == TUK_Friend))
12242             return PrevTagDecl;
12243 
12244           // Diagnose attempts to redefine a tag.
12245           if (TUK == TUK_Definition) {
12246             if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
12247               // If we're defining a specialization and the previous definition
12248               // is from an implicit instantiation, don't emit an error
12249               // here; we'll catch this in the general case below.
12250               bool IsExplicitSpecializationAfterInstantiation = false;
12251               if (isExplicitSpecialization) {
12252                 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
12253                   IsExplicitSpecializationAfterInstantiation =
12254                     RD->getTemplateSpecializationKind() !=
12255                     TSK_ExplicitSpecialization;
12256                 else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
12257                   IsExplicitSpecializationAfterInstantiation =
12258                     ED->getTemplateSpecializationKind() !=
12259                     TSK_ExplicitSpecialization;
12260               }
12261 
12262               NamedDecl *Hidden = nullptr;
12263               if (SkipBody && getLangOpts().CPlusPlus &&
12264                   !hasVisibleDefinition(Def, &Hidden)) {
12265                 // There is a definition of this tag, but it is not visible. We
12266                 // explicitly make use of C++'s one definition rule here, and
12267                 // assume that this definition is identical to the hidden one
12268                 // we already have. Make the existing definition visible and
12269                 // use it in place of this one.
12270                 SkipBody->ShouldSkip = true;
12271                 makeMergedDefinitionVisible(Hidden, KWLoc);
12272                 return Def;
12273               } else if (!IsExplicitSpecializationAfterInstantiation) {
12274                 // A redeclaration in function prototype scope in C isn't
12275                 // visible elsewhere, so merely issue a warning.
12276                 if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
12277                   Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
12278                 else
12279                   Diag(NameLoc, diag::err_redefinition) << Name;
12280                 Diag(Def->getLocation(), diag::note_previous_definition);
12281                 // If this is a redefinition, recover by making this
12282                 // struct be anonymous, which will make any later
12283                 // references get the previous definition.
12284                 Name = nullptr;
12285                 Previous.clear();
12286                 Invalid = true;
12287               }
12288             } else {
12289               // If the type is currently being defined, complain
12290               // about a nested redefinition.
12291               auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
12292               if (TD->isBeingDefined()) {
12293                 Diag(NameLoc, diag::err_nested_redefinition) << Name;
12294                 Diag(PrevTagDecl->getLocation(),
12295                      diag::note_previous_definition);
12296                 Name = nullptr;
12297                 Previous.clear();
12298                 Invalid = true;
12299               }
12300             }
12301 
12302             // Okay, this is definition of a previously declared or referenced
12303             // tag. We're going to create a new Decl for it.
12304           }
12305 
12306           // Okay, we're going to make a redeclaration.  If this is some kind
12307           // of reference, make sure we build the redeclaration in the same DC
12308           // as the original, and ignore the current access specifier.
12309           if (TUK == TUK_Friend || TUK == TUK_Reference) {
12310             SearchDC = PrevTagDecl->getDeclContext();
12311             AS = AS_none;
12312           }
12313         }
12314         // If we get here we have (another) forward declaration or we
12315         // have a definition.  Just create a new decl.
12316 
12317       } else {
12318         // If we get here, this is a definition of a new tag type in a nested
12319         // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
12320         // new decl/type.  We set PrevDecl to NULL so that the entities
12321         // have distinct types.
12322         Previous.clear();
12323       }
12324       // If we get here, we're going to create a new Decl. If PrevDecl
12325       // is non-NULL, it's a definition of the tag declared by
12326       // PrevDecl. If it's NULL, we have a new definition.
12327 
12328 
12329     // Otherwise, PrevDecl is not a tag, but was found with tag
12330     // lookup.  This is only actually possible in C++, where a few
12331     // things like templates still live in the tag namespace.
12332     } else {
12333       // Use a better diagnostic if an elaborated-type-specifier
12334       // found the wrong kind of type on the first
12335       // (non-redeclaration) lookup.
12336       if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
12337           !Previous.isForRedeclaration()) {
12338         unsigned Kind = 0;
12339         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12340         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12341         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12342         Diag(NameLoc, diag::err_tag_reference_non_tag) << Kind;
12343         Diag(PrevDecl->getLocation(), diag::note_declared_at);
12344         Invalid = true;
12345 
12346       // Otherwise, only diagnose if the declaration is in scope.
12347       } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
12348                                 SS.isNotEmpty() || isExplicitSpecialization)) {
12349         // do nothing
12350 
12351       // Diagnose implicit declarations introduced by elaborated types.
12352       } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
12353         unsigned Kind = 0;
12354         if (isa<TypedefDecl>(PrevDecl)) Kind = 1;
12355         else if (isa<TypeAliasDecl>(PrevDecl)) Kind = 2;
12356         else if (isa<ClassTemplateDecl>(PrevDecl)) Kind = 3;
12357         Diag(NameLoc, diag::err_tag_reference_conflict) << Kind;
12358         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12359         Invalid = true;
12360 
12361       // Otherwise it's a declaration.  Call out a particularly common
12362       // case here.
12363       } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
12364         unsigned Kind = 0;
12365         if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
12366         Diag(NameLoc, diag::err_tag_definition_of_typedef)
12367           << Name << Kind << TND->getUnderlyingType();
12368         Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
12369         Invalid = true;
12370 
12371       // Otherwise, diagnose.
12372       } else {
12373         // The tag name clashes with something else in the target scope,
12374         // issue an error and recover by making this tag be anonymous.
12375         Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
12376         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
12377         Name = nullptr;
12378         Invalid = true;
12379       }
12380 
12381       // The existing declaration isn't relevant to us; we're in a
12382       // new scope, so clear out the previous declaration.
12383       Previous.clear();
12384     }
12385   }
12386 
12387 CreateNewDecl:
12388 
12389   TagDecl *PrevDecl = nullptr;
12390   if (Previous.isSingleResult())
12391     PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
12392 
12393   // If there is an identifier, use the location of the identifier as the
12394   // location of the decl, otherwise use the location of the struct/union
12395   // keyword.
12396   SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
12397 
12398   // Otherwise, create a new declaration. If there is a previous
12399   // declaration of the same entity, the two will be linked via
12400   // PrevDecl.
12401   TagDecl *New;
12402 
12403   bool IsForwardReference = false;
12404   if (Kind == TTK_Enum) {
12405     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12406     // enum X { A, B, C } D;    D should chain to X.
12407     New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
12408                            cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
12409                            ScopedEnumUsesClassTag, !EnumUnderlying.isNull());
12410     // If this is an undefined enum, warn.
12411     if (TUK != TUK_Definition && !Invalid) {
12412       TagDecl *Def;
12413       if ((getLangOpts().CPlusPlus11 || getLangOpts().ObjC2) &&
12414           cast<EnumDecl>(New)->isFixed()) {
12415         // C++0x: 7.2p2: opaque-enum-declaration.
12416         // Conflicts are diagnosed above. Do nothing.
12417       }
12418       else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
12419         Diag(Loc, diag::ext_forward_ref_enum_def)
12420           << New;
12421         Diag(Def->getLocation(), diag::note_previous_definition);
12422       } else {
12423         unsigned DiagID = diag::ext_forward_ref_enum;
12424         if (getLangOpts().MSVCCompat)
12425           DiagID = diag::ext_ms_forward_ref_enum;
12426         else if (getLangOpts().CPlusPlus)
12427           DiagID = diag::err_forward_ref_enum;
12428         Diag(Loc, DiagID);
12429 
12430         // If this is a forward-declared reference to an enumeration, make a
12431         // note of it; we won't actually be introducing the declaration into
12432         // the declaration context.
12433         if (TUK == TUK_Reference)
12434           IsForwardReference = true;
12435       }
12436     }
12437 
12438     if (EnumUnderlying) {
12439       EnumDecl *ED = cast<EnumDecl>(New);
12440       if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
12441         ED->setIntegerTypeSourceInfo(TI);
12442       else
12443         ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
12444       ED->setPromotionType(ED->getIntegerType());
12445     }
12446 
12447   } else {
12448     // struct/union/class
12449 
12450     // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
12451     // struct X { int A; } D;    D should chain to X.
12452     if (getLangOpts().CPlusPlus) {
12453       // FIXME: Look for a way to use RecordDecl for simple structs.
12454       New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12455                                   cast_or_null<CXXRecordDecl>(PrevDecl));
12456 
12457       if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
12458         StdBadAlloc = cast<CXXRecordDecl>(New);
12459     } else
12460       New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
12461                                cast_or_null<RecordDecl>(PrevDecl));
12462   }
12463 
12464   // C++11 [dcl.type]p3:
12465   //   A type-specifier-seq shall not define a class or enumeration [...].
12466   if (getLangOpts().CPlusPlus && IsTypeSpecifier && TUK == TUK_Definition) {
12467     Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
12468       << Context.getTagDeclType(New);
12469     Invalid = true;
12470   }
12471 
12472   // Maybe add qualifier info.
12473   if (SS.isNotEmpty()) {
12474     if (SS.isSet()) {
12475       // If this is either a declaration or a definition, check the
12476       // nested-name-specifier against the current context. We don't do this
12477       // for explicit specializations, because they have similar checking
12478       // (with more specific diagnostics) in the call to
12479       // CheckMemberSpecialization, below.
12480       if (!isExplicitSpecialization &&
12481           (TUK == TUK_Definition || TUK == TUK_Declaration) &&
12482           diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc))
12483         Invalid = true;
12484 
12485       New->setQualifierInfo(SS.getWithLocInContext(Context));
12486       if (TemplateParameterLists.size() > 0) {
12487         New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
12488       }
12489     }
12490     else
12491       Invalid = true;
12492   }
12493 
12494   if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
12495     // Add alignment attributes if necessary; these attributes are checked when
12496     // the ASTContext lays out the structure.
12497     //
12498     // It is important for implementing the correct semantics that this
12499     // happen here (in act on tag decl). The #pragma pack stack is
12500     // maintained as a result of parser callbacks which can occur at
12501     // many points during the parsing of a struct declaration (because
12502     // the #pragma tokens are effectively skipped over during the
12503     // parsing of the struct).
12504     if (TUK == TUK_Definition) {
12505       AddAlignmentAttributesForRecord(RD);
12506       AddMsStructLayoutForRecord(RD);
12507     }
12508   }
12509 
12510   if (ModulePrivateLoc.isValid()) {
12511     if (isExplicitSpecialization)
12512       Diag(New->getLocation(), diag::err_module_private_specialization)
12513         << 2
12514         << FixItHint::CreateRemoval(ModulePrivateLoc);
12515     // __module_private__ does not apply to local classes. However, we only
12516     // diagnose this as an error when the declaration specifiers are
12517     // freestanding. Here, we just ignore the __module_private__.
12518     else if (!SearchDC->isFunctionOrMethod())
12519       New->setModulePrivate();
12520   }
12521 
12522   // If this is a specialization of a member class (of a class template),
12523   // check the specialization.
12524   if (isExplicitSpecialization && CheckMemberSpecialization(New, Previous))
12525     Invalid = true;
12526 
12527   // If we're declaring or defining a tag in function prototype scope in C,
12528   // note that this type can only be used within the function and add it to
12529   // the list of decls to inject into the function definition scope.
12530   if ((Name || Kind == TTK_Enum) &&
12531       getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
12532     if (getLangOpts().CPlusPlus) {
12533       // C++ [dcl.fct]p6:
12534       //   Types shall not be defined in return or parameter types.
12535       if (TUK == TUK_Definition && !IsTypeSpecifier) {
12536         Diag(Loc, diag::err_type_defined_in_param_type)
12537             << Name;
12538         Invalid = true;
12539       }
12540     } else {
12541       Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
12542     }
12543     DeclsInPrototypeScope.push_back(New);
12544   }
12545 
12546   if (Invalid)
12547     New->setInvalidDecl();
12548 
12549   if (Attr)
12550     ProcessDeclAttributeList(S, New, Attr);
12551 
12552   // Set the lexical context. If the tag has a C++ scope specifier, the
12553   // lexical context will be different from the semantic context.
12554   New->setLexicalDeclContext(CurContext);
12555 
12556   // Mark this as a friend decl if applicable.
12557   // In Microsoft mode, a friend declaration also acts as a forward
12558   // declaration so we always pass true to setObjectOfFriendDecl to make
12559   // the tag name visible.
12560   if (TUK == TUK_Friend)
12561     New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
12562 
12563   // Set the access specifier.
12564   if (!Invalid && SearchDC->isRecord())
12565     SetMemberAccessSpecifier(New, PrevDecl, AS);
12566 
12567   if (TUK == TUK_Definition)
12568     New->startDefinition();
12569 
12570   // If this has an identifier, add it to the scope stack.
12571   if (TUK == TUK_Friend) {
12572     // We might be replacing an existing declaration in the lookup tables;
12573     // if so, borrow its access specifier.
12574     if (PrevDecl)
12575       New->setAccess(PrevDecl->getAccess());
12576 
12577     DeclContext *DC = New->getDeclContext()->getRedeclContext();
12578     DC->makeDeclVisibleInContext(New);
12579     if (Name) // can be null along some error paths
12580       if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
12581         PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
12582   } else if (Name) {
12583     S = getNonFieldDeclScope(S);
12584     PushOnScopeChains(New, S, !IsForwardReference);
12585     if (IsForwardReference)
12586       SearchDC->makeDeclVisibleInContext(New);
12587 
12588   } else {
12589     CurContext->addDecl(New);
12590   }
12591 
12592   // If this is the C FILE type, notify the AST context.
12593   if (IdentifierInfo *II = New->getIdentifier())
12594     if (!New->isInvalidDecl() &&
12595         New->getDeclContext()->getRedeclContext()->isTranslationUnit() &&
12596         II->isStr("FILE"))
12597       Context.setFILEDecl(New);
12598 
12599   if (PrevDecl)
12600     mergeDeclAttributes(New, PrevDecl);
12601 
12602   // If there's a #pragma GCC visibility in scope, set the visibility of this
12603   // record.
12604   AddPushedVisibilityAttribute(New);
12605 
12606   OwnedDecl = true;
12607   // In C++, don't return an invalid declaration. We can't recover well from
12608   // the cases where we make the type anonymous.
12609   return (Invalid && getLangOpts().CPlusPlus) ? nullptr : New;
12610 }
12611 
12612 void Sema::ActOnTagStartDefinition(Scope *S, Decl *TagD) {
12613   AdjustDeclIfTemplate(TagD);
12614   TagDecl *Tag = cast<TagDecl>(TagD);
12615 
12616   // Enter the tag context.
12617   PushDeclContext(S, Tag);
12618 
12619   ActOnDocumentableDecl(TagD);
12620 
12621   // If there's a #pragma GCC visibility in scope, set the visibility of this
12622   // record.
12623   AddPushedVisibilityAttribute(Tag);
12624 }
12625 
12626 Decl *Sema::ActOnObjCContainerStartDefinition(Decl *IDecl) {
12627   assert(isa<ObjCContainerDecl>(IDecl) &&
12628          "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
12629   DeclContext *OCD = cast<DeclContext>(IDecl);
12630   assert(getContainingDC(OCD) == CurContext &&
12631       "The next DeclContext should be lexically contained in the current one.");
12632   CurContext = OCD;
12633   return IDecl;
12634 }
12635 
12636 void Sema::ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagD,
12637                                            SourceLocation FinalLoc,
12638                                            bool IsFinalSpelledSealed,
12639                                            SourceLocation LBraceLoc) {
12640   AdjustDeclIfTemplate(TagD);
12641   CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
12642 
12643   FieldCollector->StartClass();
12644 
12645   if (!Record->getIdentifier())
12646     return;
12647 
12648   if (FinalLoc.isValid())
12649     Record->addAttr(new (Context)
12650                     FinalAttr(FinalLoc, Context, IsFinalSpelledSealed));
12651 
12652   // C++ [class]p2:
12653   //   [...] The class-name is also inserted into the scope of the
12654   //   class itself; this is known as the injected-class-name. For
12655   //   purposes of access checking, the injected-class-name is treated
12656   //   as if it were a public member name.
12657   CXXRecordDecl *InjectedClassName
12658     = CXXRecordDecl::Create(Context, Record->getTagKind(), CurContext,
12659                             Record->getLocStart(), Record->getLocation(),
12660                             Record->getIdentifier(),
12661                             /*PrevDecl=*/nullptr,
12662                             /*DelayTypeCreation=*/true);
12663   Context.getTypeDeclType(InjectedClassName, Record);
12664   InjectedClassName->setImplicit();
12665   InjectedClassName->setAccess(AS_public);
12666   if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
12667       InjectedClassName->setDescribedClassTemplate(Template);
12668   PushOnScopeChains(InjectedClassName, S);
12669   assert(InjectedClassName->isInjectedClassName() &&
12670          "Broken injected-class-name");
12671 }
12672 
12673 void Sema::ActOnTagFinishDefinition(Scope *S, Decl *TagD,
12674                                     SourceLocation RBraceLoc) {
12675   AdjustDeclIfTemplate(TagD);
12676   TagDecl *Tag = cast<TagDecl>(TagD);
12677   Tag->setRBraceLoc(RBraceLoc);
12678 
12679   // Make sure we "complete" the definition even it is invalid.
12680   if (Tag->isBeingDefined()) {
12681     assert(Tag->isInvalidDecl() && "We should already have completed it");
12682     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12683       RD->completeDefinition();
12684   }
12685 
12686   if (isa<CXXRecordDecl>(Tag))
12687     FieldCollector->FinishClass();
12688 
12689   // Exit this scope of this tag's definition.
12690   PopDeclContext();
12691 
12692   if (getCurLexicalContext()->isObjCContainer() &&
12693       Tag->getDeclContext()->isFileContext())
12694     Tag->setTopLevelDeclInObjCContainer();
12695 
12696   // Notify the consumer that we've defined a tag.
12697   if (!Tag->isInvalidDecl())
12698     Consumer.HandleTagDeclDefinition(Tag);
12699 }
12700 
12701 void Sema::ActOnObjCContainerFinishDefinition() {
12702   // Exit this scope of this interface definition.
12703   PopDeclContext();
12704 }
12705 
12706 void Sema::ActOnObjCTemporaryExitContainerContext(DeclContext *DC) {
12707   assert(DC == CurContext && "Mismatch of container contexts");
12708   OriginalLexicalContext = DC;
12709   ActOnObjCContainerFinishDefinition();
12710 }
12711 
12712 void Sema::ActOnObjCReenterContainerContext(DeclContext *DC) {
12713   ActOnObjCContainerStartDefinition(cast<Decl>(DC));
12714   OriginalLexicalContext = nullptr;
12715 }
12716 
12717 void Sema::ActOnTagDefinitionError(Scope *S, Decl *TagD) {
12718   AdjustDeclIfTemplate(TagD);
12719   TagDecl *Tag = cast<TagDecl>(TagD);
12720   Tag->setInvalidDecl();
12721 
12722   // Make sure we "complete" the definition even it is invalid.
12723   if (Tag->isBeingDefined()) {
12724     if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
12725       RD->completeDefinition();
12726   }
12727 
12728   // We're undoing ActOnTagStartDefinition here, not
12729   // ActOnStartCXXMemberDeclarations, so we don't have to mess with
12730   // the FieldCollector.
12731 
12732   PopDeclContext();
12733 }
12734 
12735 // Note that FieldName may be null for anonymous bitfields.
12736 ExprResult Sema::VerifyBitField(SourceLocation FieldLoc,
12737                                 IdentifierInfo *FieldName,
12738                                 QualType FieldTy, bool IsMsStruct,
12739                                 Expr *BitWidth, bool *ZeroWidth) {
12740   // Default to true; that shouldn't confuse checks for emptiness
12741   if (ZeroWidth)
12742     *ZeroWidth = true;
12743 
12744   // C99 6.7.2.1p4 - verify the field type.
12745   // C++ 9.6p3: A bit-field shall have integral or enumeration type.
12746   if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
12747     // Handle incomplete types with specific error.
12748     if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
12749       return ExprError();
12750     if (FieldName)
12751       return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
12752         << FieldName << FieldTy << BitWidth->getSourceRange();
12753     return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
12754       << FieldTy << BitWidth->getSourceRange();
12755   } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
12756                                              UPPC_BitFieldWidth))
12757     return ExprError();
12758 
12759   // If the bit-width is type- or value-dependent, don't try to check
12760   // it now.
12761   if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
12762     return BitWidth;
12763 
12764   llvm::APSInt Value;
12765   ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value);
12766   if (ICE.isInvalid())
12767     return ICE;
12768   BitWidth = ICE.get();
12769 
12770   if (Value != 0 && ZeroWidth)
12771     *ZeroWidth = false;
12772 
12773   // Zero-width bitfield is ok for anonymous field.
12774   if (Value == 0 && FieldName)
12775     return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
12776 
12777   if (Value.isSigned() && Value.isNegative()) {
12778     if (FieldName)
12779       return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
12780                << FieldName << Value.toString(10);
12781     return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
12782       << Value.toString(10);
12783   }
12784 
12785   if (!FieldTy->isDependentType()) {
12786     uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
12787     uint64_t TypeWidth = Context.getIntWidth(FieldTy);
12788     bool BitfieldIsOverwide = Value.ugt(TypeWidth);
12789 
12790     // Over-wide bitfields are an error in C or when using the MSVC bitfield
12791     // ABI.
12792     bool CStdConstraintViolation =
12793         BitfieldIsOverwide && !getLangOpts().CPlusPlus;
12794     bool MSBitfieldViolation =
12795         Value.ugt(TypeStorageSize) &&
12796         (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
12797     if (CStdConstraintViolation || MSBitfieldViolation) {
12798       unsigned DiagWidth =
12799           CStdConstraintViolation ? TypeWidth : TypeStorageSize;
12800       if (FieldName)
12801         return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
12802                << FieldName << (unsigned)Value.getZExtValue()
12803                << !CStdConstraintViolation << DiagWidth;
12804 
12805       return Diag(FieldLoc, diag::err_anon_bitfield_width_exceeds_type_width)
12806              << (unsigned)Value.getZExtValue() << !CStdConstraintViolation
12807              << DiagWidth;
12808     }
12809 
12810     // Warn on types where the user might conceivably expect to get all
12811     // specified bits as value bits: that's all integral types other than
12812     // 'bool'.
12813     if (BitfieldIsOverwide && !FieldTy->isBooleanType()) {
12814       if (FieldName)
12815         Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
12816             << FieldName << (unsigned)Value.getZExtValue()
12817             << (unsigned)TypeWidth;
12818       else
12819         Diag(FieldLoc, diag::warn_anon_bitfield_width_exceeds_type_width)
12820             << (unsigned)Value.getZExtValue() << (unsigned)TypeWidth;
12821     }
12822   }
12823 
12824   return BitWidth;
12825 }
12826 
12827 /// ActOnField - Each field of a C struct/union is passed into this in order
12828 /// to create a FieldDecl object for it.
12829 Decl *Sema::ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart,
12830                        Declarator &D, Expr *BitfieldWidth) {
12831   FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
12832                                DeclStart, D, static_cast<Expr*>(BitfieldWidth),
12833                                /*InitStyle=*/ICIS_NoInit, AS_public);
12834   return Res;
12835 }
12836 
12837 /// HandleField - Analyze a field of a C struct or a C++ data member.
12838 ///
12839 FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
12840                              SourceLocation DeclStart,
12841                              Declarator &D, Expr *BitWidth,
12842                              InClassInitStyle InitStyle,
12843                              AccessSpecifier AS) {
12844   IdentifierInfo *II = D.getIdentifier();
12845   SourceLocation Loc = DeclStart;
12846   if (II) Loc = D.getIdentifierLoc();
12847 
12848   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
12849   QualType T = TInfo->getType();
12850   if (getLangOpts().CPlusPlus) {
12851     CheckExtraCXXDefaultArguments(D);
12852 
12853     if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
12854                                         UPPC_DataMemberType)) {
12855       D.setInvalidType();
12856       T = Context.IntTy;
12857       TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
12858     }
12859   }
12860 
12861   // TR 18037 does not allow fields to be declared with address spaces.
12862   if (T.getQualifiers().hasAddressSpace()) {
12863     Diag(Loc, diag::err_field_with_address_space);
12864     D.setInvalidType();
12865   }
12866 
12867   // OpenCL 1.2 spec, s6.9 r:
12868   // The event type cannot be used to declare a structure or union field.
12869   if (LangOpts.OpenCL && T->isEventT()) {
12870     Diag(Loc, diag::err_event_t_struct_field);
12871     D.setInvalidType();
12872   }
12873 
12874   DiagnoseFunctionSpecifiers(D.getDeclSpec());
12875 
12876   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
12877     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
12878          diag::err_invalid_thread)
12879       << DeclSpec::getSpecifierName(TSCS);
12880 
12881   // Check to see if this name was declared as a member previously
12882   NamedDecl *PrevDecl = nullptr;
12883   LookupResult Previous(*this, II, Loc, LookupMemberName, ForRedeclaration);
12884   LookupName(Previous, S);
12885   switch (Previous.getResultKind()) {
12886     case LookupResult::Found:
12887     case LookupResult::FoundUnresolvedValue:
12888       PrevDecl = Previous.getAsSingle<NamedDecl>();
12889       break;
12890 
12891     case LookupResult::FoundOverloaded:
12892       PrevDecl = Previous.getRepresentativeDecl();
12893       break;
12894 
12895     case LookupResult::NotFound:
12896     case LookupResult::NotFoundInCurrentInstantiation:
12897     case LookupResult::Ambiguous:
12898       break;
12899   }
12900   Previous.suppressDiagnostics();
12901 
12902   if (PrevDecl && PrevDecl->isTemplateParameter()) {
12903     // Maybe we will complain about the shadowed template parameter.
12904     DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
12905     // Just pretend that we didn't see the previous declaration.
12906     PrevDecl = nullptr;
12907   }
12908 
12909   if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
12910     PrevDecl = nullptr;
12911 
12912   bool Mutable
12913     = (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable);
12914   SourceLocation TSSL = D.getLocStart();
12915   FieldDecl *NewFD
12916     = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
12917                      TSSL, AS, PrevDecl, &D);
12918 
12919   if (NewFD->isInvalidDecl())
12920     Record->setInvalidDecl();
12921 
12922   if (D.getDeclSpec().isModulePrivateSpecified())
12923     NewFD->setModulePrivate();
12924 
12925   if (NewFD->isInvalidDecl() && PrevDecl) {
12926     // Don't introduce NewFD into scope; there's already something
12927     // with the same name in the same scope.
12928   } else if (II) {
12929     PushOnScopeChains(NewFD, S);
12930   } else
12931     Record->addDecl(NewFD);
12932 
12933   return NewFD;
12934 }
12935 
12936 /// \brief Build a new FieldDecl and check its well-formedness.
12937 ///
12938 /// This routine builds a new FieldDecl given the fields name, type,
12939 /// record, etc. \p PrevDecl should refer to any previous declaration
12940 /// with the same name and in the same scope as the field to be
12941 /// created.
12942 ///
12943 /// \returns a new FieldDecl.
12944 ///
12945 /// \todo The Declarator argument is a hack. It will be removed once
12946 FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
12947                                 TypeSourceInfo *TInfo,
12948                                 RecordDecl *Record, SourceLocation Loc,
12949                                 bool Mutable, Expr *BitWidth,
12950                                 InClassInitStyle InitStyle,
12951                                 SourceLocation TSSL,
12952                                 AccessSpecifier AS, NamedDecl *PrevDecl,
12953                                 Declarator *D) {
12954   IdentifierInfo *II = Name.getAsIdentifierInfo();
12955   bool InvalidDecl = false;
12956   if (D) InvalidDecl = D->isInvalidType();
12957 
12958   // If we receive a broken type, recover by assuming 'int' and
12959   // marking this declaration as invalid.
12960   if (T.isNull()) {
12961     InvalidDecl = true;
12962     T = Context.IntTy;
12963   }
12964 
12965   QualType EltTy = Context.getBaseElementType(T);
12966   if (!EltTy->isDependentType()) {
12967     if (RequireCompleteType(Loc, EltTy, diag::err_field_incomplete)) {
12968       // Fields of incomplete type force their record to be invalid.
12969       Record->setInvalidDecl();
12970       InvalidDecl = true;
12971     } else {
12972       NamedDecl *Def;
12973       EltTy->isIncompleteType(&Def);
12974       if (Def && Def->isInvalidDecl()) {
12975         Record->setInvalidDecl();
12976         InvalidDecl = true;
12977       }
12978     }
12979   }
12980 
12981   // OpenCL v1.2 s6.9.c: bitfields are not supported.
12982   if (BitWidth && getLangOpts().OpenCL) {
12983     Diag(Loc, diag::err_opencl_bitfields);
12984     InvalidDecl = true;
12985   }
12986 
12987   // C99 6.7.2.1p8: A member of a structure or union may have any type other
12988   // than a variably modified type.
12989   if (!InvalidDecl && T->isVariablyModifiedType()) {
12990     bool SizeIsNegative;
12991     llvm::APSInt Oversized;
12992 
12993     TypeSourceInfo *FixedTInfo =
12994       TryToFixInvalidVariablyModifiedTypeSourceInfo(TInfo, Context,
12995                                                     SizeIsNegative,
12996                                                     Oversized);
12997     if (FixedTInfo) {
12998       Diag(Loc, diag::warn_illegal_constant_array_size);
12999       TInfo = FixedTInfo;
13000       T = FixedTInfo->getType();
13001     } else {
13002       if (SizeIsNegative)
13003         Diag(Loc, diag::err_typecheck_negative_array_size);
13004       else if (Oversized.getBoolValue())
13005         Diag(Loc, diag::err_array_too_large)
13006           << Oversized.toString(10);
13007       else
13008         Diag(Loc, diag::err_typecheck_field_variable_size);
13009       InvalidDecl = true;
13010     }
13011   }
13012 
13013   // Fields can not have abstract class types
13014   if (!InvalidDecl && RequireNonAbstractType(Loc, T,
13015                                              diag::err_abstract_type_in_decl,
13016                                              AbstractFieldType))
13017     InvalidDecl = true;
13018 
13019   bool ZeroWidth = false;
13020   if (InvalidDecl)
13021     BitWidth = nullptr;
13022   // If this is declared as a bit-field, check the bit-field.
13023   if (BitWidth) {
13024     BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
13025                               &ZeroWidth).get();
13026     if (!BitWidth) {
13027       InvalidDecl = true;
13028       BitWidth = nullptr;
13029       ZeroWidth = false;
13030     }
13031   }
13032 
13033   // Check that 'mutable' is consistent with the type of the declaration.
13034   if (!InvalidDecl && Mutable) {
13035     unsigned DiagID = 0;
13036     if (T->isReferenceType())
13037       DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
13038                                         : diag::err_mutable_reference;
13039     else if (T.isConstQualified())
13040       DiagID = diag::err_mutable_const;
13041 
13042     if (DiagID) {
13043       SourceLocation ErrLoc = Loc;
13044       if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
13045         ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
13046       Diag(ErrLoc, DiagID);
13047       if (DiagID != diag::ext_mutable_reference) {
13048         Mutable = false;
13049         InvalidDecl = true;
13050       }
13051     }
13052   }
13053 
13054   // C++11 [class.union]p8 (DR1460):
13055   //   At most one variant member of a union may have a
13056   //   brace-or-equal-initializer.
13057   if (InitStyle != ICIS_NoInit)
13058     checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
13059 
13060   FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
13061                                        BitWidth, Mutable, InitStyle);
13062   if (InvalidDecl)
13063     NewFD->setInvalidDecl();
13064 
13065   if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
13066     Diag(Loc, diag::err_duplicate_member) << II;
13067     Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13068     NewFD->setInvalidDecl();
13069   }
13070 
13071   if (!InvalidDecl && getLangOpts().CPlusPlus) {
13072     if (Record->isUnion()) {
13073       if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13074         CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
13075         if (RDecl->getDefinition()) {
13076           // C++ [class.union]p1: An object of a class with a non-trivial
13077           // constructor, a non-trivial copy constructor, a non-trivial
13078           // destructor, or a non-trivial copy assignment operator
13079           // cannot be a member of a union, nor can an array of such
13080           // objects.
13081           if (CheckNontrivialField(NewFD))
13082             NewFD->setInvalidDecl();
13083         }
13084       }
13085 
13086       // C++ [class.union]p1: If a union contains a member of reference type,
13087       // the program is ill-formed, except when compiling with MSVC extensions
13088       // enabled.
13089       if (EltTy->isReferenceType()) {
13090         Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
13091                                     diag::ext_union_member_of_reference_type :
13092                                     diag::err_union_member_of_reference_type)
13093           << NewFD->getDeclName() << EltTy;
13094         if (!getLangOpts().MicrosoftExt)
13095           NewFD->setInvalidDecl();
13096       }
13097     }
13098   }
13099 
13100   // FIXME: We need to pass in the attributes given an AST
13101   // representation, not a parser representation.
13102   if (D) {
13103     // FIXME: The current scope is almost... but not entirely... correct here.
13104     ProcessDeclAttributes(getCurScope(), NewFD, *D);
13105 
13106     if (NewFD->hasAttrs())
13107       CheckAlignasUnderalignment(NewFD);
13108   }
13109 
13110   // In auto-retain/release, infer strong retension for fields of
13111   // retainable type.
13112   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
13113     NewFD->setInvalidDecl();
13114 
13115   if (T.isObjCGCWeak())
13116     Diag(Loc, diag::warn_attribute_weak_on_field);
13117 
13118   NewFD->setAccess(AS);
13119   return NewFD;
13120 }
13121 
13122 bool Sema::CheckNontrivialField(FieldDecl *FD) {
13123   assert(FD);
13124   assert(getLangOpts().CPlusPlus && "valid check only for C++");
13125 
13126   if (FD->isInvalidDecl() || FD->getType()->isDependentType())
13127     return false;
13128 
13129   QualType EltTy = Context.getBaseElementType(FD->getType());
13130   if (const RecordType *RT = EltTy->getAs<RecordType>()) {
13131     CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
13132     if (RDecl->getDefinition()) {
13133       // We check for copy constructors before constructors
13134       // because otherwise we'll never get complaints about
13135       // copy constructors.
13136 
13137       CXXSpecialMember member = CXXInvalid;
13138       // We're required to check for any non-trivial constructors. Since the
13139       // implicit default constructor is suppressed if there are any
13140       // user-declared constructors, we just need to check that there is a
13141       // trivial default constructor and a trivial copy constructor. (We don't
13142       // worry about move constructors here, since this is a C++98 check.)
13143       if (RDecl->hasNonTrivialCopyConstructor())
13144         member = CXXCopyConstructor;
13145       else if (!RDecl->hasTrivialDefaultConstructor())
13146         member = CXXDefaultConstructor;
13147       else if (RDecl->hasNonTrivialCopyAssignment())
13148         member = CXXCopyAssignment;
13149       else if (RDecl->hasNonTrivialDestructor())
13150         member = CXXDestructor;
13151 
13152       if (member != CXXInvalid) {
13153         if (!getLangOpts().CPlusPlus11 &&
13154             getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
13155           // Objective-C++ ARC: it is an error to have a non-trivial field of
13156           // a union. However, system headers in Objective-C programs
13157           // occasionally have Objective-C lifetime objects within unions,
13158           // and rather than cause the program to fail, we make those
13159           // members unavailable.
13160           SourceLocation Loc = FD->getLocation();
13161           if (getSourceManager().isInSystemHeader(Loc)) {
13162             if (!FD->hasAttr<UnavailableAttr>())
13163               FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13164                             UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
13165             return false;
13166           }
13167         }
13168 
13169         Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
13170                diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
13171                diag::err_illegal_union_or_anon_struct_member)
13172           << FD->getParent()->isUnion() << FD->getDeclName() << member;
13173         DiagnoseNontrivial(RDecl, member);
13174         return !getLangOpts().CPlusPlus11;
13175       }
13176     }
13177   }
13178 
13179   return false;
13180 }
13181 
13182 /// TranslateIvarVisibility - Translate visibility from a token ID to an
13183 ///  AST enum value.
13184 static ObjCIvarDecl::AccessControl
13185 TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
13186   switch (ivarVisibility) {
13187   default: llvm_unreachable("Unknown visitibility kind");
13188   case tok::objc_private: return ObjCIvarDecl::Private;
13189   case tok::objc_public: return ObjCIvarDecl::Public;
13190   case tok::objc_protected: return ObjCIvarDecl::Protected;
13191   case tok::objc_package: return ObjCIvarDecl::Package;
13192   }
13193 }
13194 
13195 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
13196 /// in order to create an IvarDecl object for it.
13197 Decl *Sema::ActOnIvar(Scope *S,
13198                                 SourceLocation DeclStart,
13199                                 Declarator &D, Expr *BitfieldWidth,
13200                                 tok::ObjCKeywordKind Visibility) {
13201 
13202   IdentifierInfo *II = D.getIdentifier();
13203   Expr *BitWidth = (Expr*)BitfieldWidth;
13204   SourceLocation Loc = DeclStart;
13205   if (II) Loc = D.getIdentifierLoc();
13206 
13207   // FIXME: Unnamed fields can be handled in various different ways, for
13208   // example, unnamed unions inject all members into the struct namespace!
13209 
13210   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13211   QualType T = TInfo->getType();
13212 
13213   if (BitWidth) {
13214     // 6.7.2.1p3, 6.7.2.1p4
13215     BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
13216     if (!BitWidth)
13217       D.setInvalidType();
13218   } else {
13219     // Not a bitfield.
13220 
13221     // validate II.
13222 
13223   }
13224   if (T->isReferenceType()) {
13225     Diag(Loc, diag::err_ivar_reference_type);
13226     D.setInvalidType();
13227   }
13228   // C99 6.7.2.1p8: A member of a structure or union may have any type other
13229   // than a variably modified type.
13230   else if (T->isVariablyModifiedType()) {
13231     Diag(Loc, diag::err_typecheck_ivar_variable_size);
13232     D.setInvalidType();
13233   }
13234 
13235   // Get the visibility (access control) for this ivar.
13236   ObjCIvarDecl::AccessControl ac =
13237     Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
13238                                         : ObjCIvarDecl::None;
13239   // Must set ivar's DeclContext to its enclosing interface.
13240   ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
13241   if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
13242     return nullptr;
13243   ObjCContainerDecl *EnclosingContext;
13244   if (ObjCImplementationDecl *IMPDecl =
13245       dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13246     if (LangOpts.ObjCRuntime.isFragile()) {
13247     // Case of ivar declared in an implementation. Context is that of its class.
13248       EnclosingContext = IMPDecl->getClassInterface();
13249       assert(EnclosingContext && "Implementation has no class interface!");
13250     }
13251     else
13252       EnclosingContext = EnclosingDecl;
13253   } else {
13254     if (ObjCCategoryDecl *CDecl =
13255         dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13256       if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
13257         Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
13258         return nullptr;
13259       }
13260     }
13261     EnclosingContext = EnclosingDecl;
13262   }
13263 
13264   // Construct the decl.
13265   ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
13266                                              DeclStart, Loc, II, T,
13267                                              TInfo, ac, (Expr *)BitfieldWidth);
13268 
13269   if (II) {
13270     NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
13271                                            ForRedeclaration);
13272     if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
13273         && !isa<TagDecl>(PrevDecl)) {
13274       Diag(Loc, diag::err_duplicate_member) << II;
13275       Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
13276       NewID->setInvalidDecl();
13277     }
13278   }
13279 
13280   // Process attributes attached to the ivar.
13281   ProcessDeclAttributes(S, NewID, D);
13282 
13283   if (D.isInvalidType())
13284     NewID->setInvalidDecl();
13285 
13286   // In ARC, infer 'retaining' for ivars of retainable type.
13287   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
13288     NewID->setInvalidDecl();
13289 
13290   if (D.getDeclSpec().isModulePrivateSpecified())
13291     NewID->setModulePrivate();
13292 
13293   if (II) {
13294     // FIXME: When interfaces are DeclContexts, we'll need to add
13295     // these to the interface.
13296     S->AddDecl(NewID);
13297     IdResolver.AddDecl(NewID);
13298   }
13299 
13300   if (LangOpts.ObjCRuntime.isNonFragile() &&
13301       !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
13302     Diag(Loc, diag::warn_ivars_in_interface);
13303 
13304   return NewID;
13305 }
13306 
13307 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
13308 /// class and class extensions. For every class \@interface and class
13309 /// extension \@interface, if the last ivar is a bitfield of any type,
13310 /// then add an implicit `char :0` ivar to the end of that interface.
13311 void Sema::ActOnLastBitfield(SourceLocation DeclLoc,
13312                              SmallVectorImpl<Decl *> &AllIvarDecls) {
13313   if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
13314     return;
13315 
13316   Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
13317   ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
13318 
13319   if (!Ivar->isBitField() || Ivar->getBitWidthValue(Context) == 0)
13320     return;
13321   ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
13322   if (!ID) {
13323     if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
13324       if (!CD->IsClassExtension())
13325         return;
13326     }
13327     // No need to add this to end of @implementation.
13328     else
13329       return;
13330   }
13331   // All conditions are met. Add a new bitfield to the tail end of ivars.
13332   llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
13333   Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
13334 
13335   Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
13336                               DeclLoc, DeclLoc, nullptr,
13337                               Context.CharTy,
13338                               Context.getTrivialTypeSourceInfo(Context.CharTy,
13339                                                                DeclLoc),
13340                               ObjCIvarDecl::Private, BW,
13341                               true);
13342   AllIvarDecls.push_back(Ivar);
13343 }
13344 
13345 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
13346                        ArrayRef<Decl *> Fields, SourceLocation LBrac,
13347                        SourceLocation RBrac, AttributeList *Attr) {
13348   assert(EnclosingDecl && "missing record or interface decl");
13349 
13350   // If this is an Objective-C @implementation or category and we have
13351   // new fields here we should reset the layout of the interface since
13352   // it will now change.
13353   if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
13354     ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
13355     switch (DC->getKind()) {
13356     default: break;
13357     case Decl::ObjCCategory:
13358       Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
13359       break;
13360     case Decl::ObjCImplementation:
13361       Context.
13362         ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
13363       break;
13364     }
13365   }
13366 
13367   RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
13368 
13369   // Start counting up the number of named members; make sure to include
13370   // members of anonymous structs and unions in the total.
13371   unsigned NumNamedMembers = 0;
13372   if (Record) {
13373     for (const auto *I : Record->decls()) {
13374       if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
13375         if (IFD->getDeclName())
13376           ++NumNamedMembers;
13377     }
13378   }
13379 
13380   // Verify that all the fields are okay.
13381   SmallVector<FieldDecl*, 32> RecFields;
13382 
13383   bool ARCErrReported = false;
13384   for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
13385        i != end; ++i) {
13386     FieldDecl *FD = cast<FieldDecl>(*i);
13387 
13388     // Get the type for the field.
13389     const Type *FDTy = FD->getType().getTypePtr();
13390 
13391     if (!FD->isAnonymousStructOrUnion()) {
13392       // Remember all fields written by the user.
13393       RecFields.push_back(FD);
13394     }
13395 
13396     // If the field is already invalid for some reason, don't emit more
13397     // diagnostics about it.
13398     if (FD->isInvalidDecl()) {
13399       EnclosingDecl->setInvalidDecl();
13400       continue;
13401     }
13402 
13403     // C99 6.7.2.1p2:
13404     //   A structure or union shall not contain a member with
13405     //   incomplete or function type (hence, a structure shall not
13406     //   contain an instance of itself, but may contain a pointer to
13407     //   an instance of itself), except that the last member of a
13408     //   structure with more than one named member may have incomplete
13409     //   array type; such a structure (and any union containing,
13410     //   possibly recursively, a member that is such a structure)
13411     //   shall not be a member of a structure or an element of an
13412     //   array.
13413     if (FDTy->isFunctionType()) {
13414       // Field declared as a function.
13415       Diag(FD->getLocation(), diag::err_field_declared_as_function)
13416         << FD->getDeclName();
13417       FD->setInvalidDecl();
13418       EnclosingDecl->setInvalidDecl();
13419       continue;
13420     } else if (FDTy->isIncompleteArrayType() && Record &&
13421                ((i + 1 == Fields.end() && !Record->isUnion()) ||
13422                 ((getLangOpts().MicrosoftExt ||
13423                   getLangOpts().CPlusPlus) &&
13424                  (i + 1 == Fields.end() || Record->isUnion())))) {
13425       // Flexible array member.
13426       // Microsoft and g++ is more permissive regarding flexible array.
13427       // It will accept flexible array in union and also
13428       // as the sole element of a struct/class.
13429       unsigned DiagID = 0;
13430       if (Record->isUnion())
13431         DiagID = getLangOpts().MicrosoftExt
13432                      ? diag::ext_flexible_array_union_ms
13433                      : getLangOpts().CPlusPlus
13434                            ? diag::ext_flexible_array_union_gnu
13435                            : diag::err_flexible_array_union;
13436       else if (Fields.size() == 1)
13437         DiagID = getLangOpts().MicrosoftExt
13438                      ? diag::ext_flexible_array_empty_aggregate_ms
13439                      : getLangOpts().CPlusPlus
13440                            ? diag::ext_flexible_array_empty_aggregate_gnu
13441                            : NumNamedMembers < 1
13442                                  ? diag::err_flexible_array_empty_aggregate
13443                                  : 0;
13444 
13445       if (DiagID)
13446         Diag(FD->getLocation(), DiagID) << FD->getDeclName()
13447                                         << Record->getTagKind();
13448       // While the layout of types that contain virtual bases is not specified
13449       // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
13450       // virtual bases after the derived members.  This would make a flexible
13451       // array member declared at the end of an object not adjacent to the end
13452       // of the type.
13453       if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record))
13454         if (RD->getNumVBases() != 0)
13455           Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
13456             << FD->getDeclName() << Record->getTagKind();
13457       if (!getLangOpts().C99)
13458         Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
13459           << FD->getDeclName() << Record->getTagKind();
13460 
13461       // If the element type has a non-trivial destructor, we would not
13462       // implicitly destroy the elements, so disallow it for now.
13463       //
13464       // FIXME: GCC allows this. We should probably either implicitly delete
13465       // the destructor of the containing class, or just allow this.
13466       QualType BaseElem = Context.getBaseElementType(FD->getType());
13467       if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
13468         Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
13469           << FD->getDeclName() << FD->getType();
13470         FD->setInvalidDecl();
13471         EnclosingDecl->setInvalidDecl();
13472         continue;
13473       }
13474       // Okay, we have a legal flexible array member at the end of the struct.
13475       Record->setHasFlexibleArrayMember(true);
13476     } else if (!FDTy->isDependentType() &&
13477                RequireCompleteType(FD->getLocation(), FD->getType(),
13478                                    diag::err_field_incomplete)) {
13479       // Incomplete type
13480       FD->setInvalidDecl();
13481       EnclosingDecl->setInvalidDecl();
13482       continue;
13483     } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
13484       if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
13485         // A type which contains a flexible array member is considered to be a
13486         // flexible array member.
13487         Record->setHasFlexibleArrayMember(true);
13488         if (!Record->isUnion()) {
13489           // If this is a struct/class and this is not the last element, reject
13490           // it.  Note that GCC supports variable sized arrays in the middle of
13491           // structures.
13492           if (i + 1 != Fields.end())
13493             Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
13494               << FD->getDeclName() << FD->getType();
13495           else {
13496             // We support flexible arrays at the end of structs in
13497             // other structs as an extension.
13498             Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
13499               << FD->getDeclName();
13500           }
13501         }
13502       }
13503       if (isa<ObjCContainerDecl>(EnclosingDecl) &&
13504           RequireNonAbstractType(FD->getLocation(), FD->getType(),
13505                                  diag::err_abstract_type_in_decl,
13506                                  AbstractIvarType)) {
13507         // Ivars can not have abstract class types
13508         FD->setInvalidDecl();
13509       }
13510       if (Record && FDTTy->getDecl()->hasObjectMember())
13511         Record->setHasObjectMember(true);
13512       if (Record && FDTTy->getDecl()->hasVolatileMember())
13513         Record->setHasVolatileMember(true);
13514     } else if (FDTy->isObjCObjectType()) {
13515       /// A field cannot be an Objective-c object
13516       Diag(FD->getLocation(), diag::err_statically_allocated_object)
13517         << FixItHint::CreateInsertion(FD->getLocation(), "*");
13518       QualType T = Context.getObjCObjectPointerType(FD->getType());
13519       FD->setType(T);
13520     } else if (getLangOpts().ObjCAutoRefCount && Record && !ARCErrReported &&
13521                (!getLangOpts().CPlusPlus || Record->isUnion())) {
13522       // It's an error in ARC if a field has lifetime.
13523       // We don't want to report this in a system header, though,
13524       // so we just make the field unavailable.
13525       // FIXME: that's really not sufficient; we need to make the type
13526       // itself invalid to, say, initialize or copy.
13527       QualType T = FD->getType();
13528       Qualifiers::ObjCLifetime lifetime = T.getObjCLifetime();
13529       if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone) {
13530         SourceLocation loc = FD->getLocation();
13531         if (getSourceManager().isInSystemHeader(loc)) {
13532           if (!FD->hasAttr<UnavailableAttr>()) {
13533             FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
13534                           UnavailableAttr::IR_ARCFieldWithOwnership, loc));
13535           }
13536         } else {
13537           Diag(FD->getLocation(), diag::err_arc_objc_object_in_tag)
13538             << T->isBlockPointerType() << Record->getTagKind();
13539         }
13540         ARCErrReported = true;
13541       }
13542     } else if (getLangOpts().ObjC1 &&
13543                getLangOpts().getGC() != LangOptions::NonGC &&
13544                Record && !Record->hasObjectMember()) {
13545       if (FD->getType()->isObjCObjectPointerType() ||
13546           FD->getType().isObjCGCStrong())
13547         Record->setHasObjectMember(true);
13548       else if (Context.getAsArrayType(FD->getType())) {
13549         QualType BaseType = Context.getBaseElementType(FD->getType());
13550         if (BaseType->isRecordType() &&
13551             BaseType->getAs<RecordType>()->getDecl()->hasObjectMember())
13552           Record->setHasObjectMember(true);
13553         else if (BaseType->isObjCObjectPointerType() ||
13554                  BaseType.isObjCGCStrong())
13555                Record->setHasObjectMember(true);
13556       }
13557     }
13558     if (Record && FD->getType().isVolatileQualified())
13559       Record->setHasVolatileMember(true);
13560     // Keep track of the number of named members.
13561     if (FD->getIdentifier())
13562       ++NumNamedMembers;
13563   }
13564 
13565   // Okay, we successfully defined 'Record'.
13566   if (Record) {
13567     bool Completed = false;
13568     if (CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
13569       if (!CXXRecord->isInvalidDecl()) {
13570         // Set access bits correctly on the directly-declared conversions.
13571         for (CXXRecordDecl::conversion_iterator
13572                I = CXXRecord->conversion_begin(),
13573                E = CXXRecord->conversion_end(); I != E; ++I)
13574           I.setAccess((*I)->getAccess());
13575 
13576         if (!CXXRecord->isDependentType()) {
13577           if (CXXRecord->hasUserDeclaredDestructor()) {
13578             // Adjust user-defined destructor exception spec.
13579             if (getLangOpts().CPlusPlus11)
13580               AdjustDestructorExceptionSpec(CXXRecord,
13581                                             CXXRecord->getDestructor());
13582           }
13583 
13584           // Add any implicitly-declared members to this class.
13585           AddImplicitlyDeclaredMembersToClass(CXXRecord);
13586 
13587           // If we have virtual base classes, we may end up finding multiple
13588           // final overriders for a given virtual function. Check for this
13589           // problem now.
13590           if (CXXRecord->getNumVBases()) {
13591             CXXFinalOverriderMap FinalOverriders;
13592             CXXRecord->getFinalOverriders(FinalOverriders);
13593 
13594             for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
13595                                              MEnd = FinalOverriders.end();
13596                  M != MEnd; ++M) {
13597               for (OverridingMethods::iterator SO = M->second.begin(),
13598                                             SOEnd = M->second.end();
13599                    SO != SOEnd; ++SO) {
13600                 assert(SO->second.size() > 0 &&
13601                        "Virtual function without overridding functions?");
13602                 if (SO->second.size() == 1)
13603                   continue;
13604 
13605                 // C++ [class.virtual]p2:
13606                 //   In a derived class, if a virtual member function of a base
13607                 //   class subobject has more than one final overrider the
13608                 //   program is ill-formed.
13609                 Diag(Record->getLocation(), diag::err_multiple_final_overriders)
13610                   << (const NamedDecl *)M->first << Record;
13611                 Diag(M->first->getLocation(),
13612                      diag::note_overridden_virtual_function);
13613                 for (OverridingMethods::overriding_iterator
13614                           OM = SO->second.begin(),
13615                        OMEnd = SO->second.end();
13616                      OM != OMEnd; ++OM)
13617                   Diag(OM->Method->getLocation(), diag::note_final_overrider)
13618                     << (const NamedDecl *)M->first << OM->Method->getParent();
13619 
13620                 Record->setInvalidDecl();
13621               }
13622             }
13623             CXXRecord->completeDefinition(&FinalOverriders);
13624             Completed = true;
13625           }
13626         }
13627       }
13628     }
13629 
13630     if (!Completed)
13631       Record->completeDefinition();
13632 
13633     if (Record->hasAttrs()) {
13634       CheckAlignasUnderalignment(Record);
13635 
13636       if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
13637         checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
13638                                            IA->getRange(), IA->getBestCase(),
13639                                            IA->getSemanticSpelling());
13640     }
13641 
13642     // Check if the structure/union declaration is a type that can have zero
13643     // size in C. For C this is a language extension, for C++ it may cause
13644     // compatibility problems.
13645     bool CheckForZeroSize;
13646     if (!getLangOpts().CPlusPlus) {
13647       CheckForZeroSize = true;
13648     } else {
13649       // For C++ filter out types that cannot be referenced in C code.
13650       CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
13651       CheckForZeroSize =
13652           CXXRecord->getLexicalDeclContext()->isExternCContext() &&
13653           !CXXRecord->isDependentType() &&
13654           CXXRecord->isCLike();
13655     }
13656     if (CheckForZeroSize) {
13657       bool ZeroSize = true;
13658       bool IsEmpty = true;
13659       unsigned NonBitFields = 0;
13660       for (RecordDecl::field_iterator I = Record->field_begin(),
13661                                       E = Record->field_end();
13662            (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
13663         IsEmpty = false;
13664         if (I->isUnnamedBitfield()) {
13665           if (I->getBitWidthValue(Context) > 0)
13666             ZeroSize = false;
13667         } else {
13668           ++NonBitFields;
13669           QualType FieldType = I->getType();
13670           if (FieldType->isIncompleteType() ||
13671               !Context.getTypeSizeInChars(FieldType).isZero())
13672             ZeroSize = false;
13673         }
13674       }
13675 
13676       // Empty structs are an extension in C (C99 6.7.2.1p7). They are
13677       // allowed in C++, but warn if its declaration is inside
13678       // extern "C" block.
13679       if (ZeroSize) {
13680         Diag(RecLoc, getLangOpts().CPlusPlus ?
13681                          diag::warn_zero_size_struct_union_in_extern_c :
13682                          diag::warn_zero_size_struct_union_compat)
13683           << IsEmpty << Record->isUnion() << (NonBitFields > 1);
13684       }
13685 
13686       // Structs without named members are extension in C (C99 6.7.2.1p7),
13687       // but are accepted by GCC.
13688       if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
13689         Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
13690                                diag::ext_no_named_members_in_struct_union)
13691           << Record->isUnion();
13692       }
13693     }
13694   } else {
13695     ObjCIvarDecl **ClsFields =
13696       reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
13697     if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
13698       ID->setEndOfDefinitionLoc(RBrac);
13699       // Add ivar's to class's DeclContext.
13700       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13701         ClsFields[i]->setLexicalDeclContext(ID);
13702         ID->addDecl(ClsFields[i]);
13703       }
13704       // Must enforce the rule that ivars in the base classes may not be
13705       // duplicates.
13706       if (ID->getSuperClass())
13707         DiagnoseDuplicateIvars(ID, ID->getSuperClass());
13708     } else if (ObjCImplementationDecl *IMPDecl =
13709                   dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
13710       assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
13711       for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
13712         // Ivar declared in @implementation never belongs to the implementation.
13713         // Only it is in implementation's lexical context.
13714         ClsFields[I]->setLexicalDeclContext(IMPDecl);
13715       CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
13716       IMPDecl->setIvarLBraceLoc(LBrac);
13717       IMPDecl->setIvarRBraceLoc(RBrac);
13718     } else if (ObjCCategoryDecl *CDecl =
13719                 dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
13720       // case of ivars in class extension; all other cases have been
13721       // reported as errors elsewhere.
13722       // FIXME. Class extension does not have a LocEnd field.
13723       // CDecl->setLocEnd(RBrac);
13724       // Add ivar's to class extension's DeclContext.
13725       // Diagnose redeclaration of private ivars.
13726       ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
13727       for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
13728         if (IDecl) {
13729           if (const ObjCIvarDecl *ClsIvar =
13730               IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
13731             Diag(ClsFields[i]->getLocation(),
13732                  diag::err_duplicate_ivar_declaration);
13733             Diag(ClsIvar->getLocation(), diag::note_previous_definition);
13734             continue;
13735           }
13736           for (const auto *Ext : IDecl->known_extensions()) {
13737             if (const ObjCIvarDecl *ClsExtIvar
13738                   = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
13739               Diag(ClsFields[i]->getLocation(),
13740                    diag::err_duplicate_ivar_declaration);
13741               Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
13742               continue;
13743             }
13744           }
13745         }
13746         ClsFields[i]->setLexicalDeclContext(CDecl);
13747         CDecl->addDecl(ClsFields[i]);
13748       }
13749       CDecl->setIvarLBraceLoc(LBrac);
13750       CDecl->setIvarRBraceLoc(RBrac);
13751     }
13752   }
13753 
13754   if (Attr)
13755     ProcessDeclAttributeList(S, Record, Attr);
13756 }
13757 
13758 /// \brief Determine whether the given integral value is representable within
13759 /// the given type T.
13760 static bool isRepresentableIntegerValue(ASTContext &Context,
13761                                         llvm::APSInt &Value,
13762                                         QualType T) {
13763   assert(T->isIntegralType(Context) && "Integral type required!");
13764   unsigned BitWidth = Context.getIntWidth(T);
13765 
13766   if (Value.isUnsigned() || Value.isNonNegative()) {
13767     if (T->isSignedIntegerOrEnumerationType())
13768       --BitWidth;
13769     return Value.getActiveBits() <= BitWidth;
13770   }
13771   return Value.getMinSignedBits() <= BitWidth;
13772 }
13773 
13774 // \brief Given an integral type, return the next larger integral type
13775 // (or a NULL type of no such type exists).
13776 static QualType getNextLargerIntegralType(ASTContext &Context, QualType T) {
13777   // FIXME: Int128/UInt128 support, which also needs to be introduced into
13778   // enum checking below.
13779   assert(T->isIntegralType(Context) && "Integral type required!");
13780   const unsigned NumTypes = 4;
13781   QualType SignedIntegralTypes[NumTypes] = {
13782     Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
13783   };
13784   QualType UnsignedIntegralTypes[NumTypes] = {
13785     Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
13786     Context.UnsignedLongLongTy
13787   };
13788 
13789   unsigned BitWidth = Context.getTypeSize(T);
13790   QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
13791                                                         : UnsignedIntegralTypes;
13792   for (unsigned I = 0; I != NumTypes; ++I)
13793     if (Context.getTypeSize(Types[I]) > BitWidth)
13794       return Types[I];
13795 
13796   return QualType();
13797 }
13798 
13799 EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
13800                                           EnumConstantDecl *LastEnumConst,
13801                                           SourceLocation IdLoc,
13802                                           IdentifierInfo *Id,
13803                                           Expr *Val) {
13804   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
13805   llvm::APSInt EnumVal(IntWidth);
13806   QualType EltTy;
13807 
13808   if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
13809     Val = nullptr;
13810 
13811   if (Val)
13812     Val = DefaultLvalueConversion(Val).get();
13813 
13814   if (Val) {
13815     if (Enum->isDependentType() || Val->isTypeDependent())
13816       EltTy = Context.DependentTy;
13817     else {
13818       SourceLocation ExpLoc;
13819       if (getLangOpts().CPlusPlus11 && Enum->isFixed() &&
13820           !getLangOpts().MSVCCompat) {
13821         // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
13822         // constant-expression in the enumerator-definition shall be a converted
13823         // constant expression of the underlying type.
13824         EltTy = Enum->getIntegerType();
13825         ExprResult Converted =
13826           CheckConvertedConstantExpression(Val, EltTy, EnumVal,
13827                                            CCEK_Enumerator);
13828         if (Converted.isInvalid())
13829           Val = nullptr;
13830         else
13831           Val = Converted.get();
13832       } else if (!Val->isValueDependent() &&
13833                  !(Val = VerifyIntegerConstantExpression(Val,
13834                                                          &EnumVal).get())) {
13835         // C99 6.7.2.2p2: Make sure we have an integer constant expression.
13836       } else {
13837         if (Enum->isFixed()) {
13838           EltTy = Enum->getIntegerType();
13839 
13840           // In Obj-C and Microsoft mode, require the enumeration value to be
13841           // representable in the underlying type of the enumeration. In C++11,
13842           // we perform a non-narrowing conversion as part of converted constant
13843           // expression checking.
13844           if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13845             if (getLangOpts().MSVCCompat) {
13846               Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
13847               Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13848             } else
13849               Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
13850           } else
13851             Val = ImpCastExprToType(Val, EltTy, CK_IntegralCast).get();
13852         } else if (getLangOpts().CPlusPlus) {
13853           // C++11 [dcl.enum]p5:
13854           //   If the underlying type is not fixed, the type of each enumerator
13855           //   is the type of its initializing value:
13856           //     - If an initializer is specified for an enumerator, the
13857           //       initializing value has the same type as the expression.
13858           EltTy = Val->getType();
13859         } else {
13860           // C99 6.7.2.2p2:
13861           //   The expression that defines the value of an enumeration constant
13862           //   shall be an integer constant expression that has a value
13863           //   representable as an int.
13864 
13865           // Complain if the value is not representable in an int.
13866           if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
13867             Diag(IdLoc, diag::ext_enum_value_not_int)
13868               << EnumVal.toString(10) << Val->getSourceRange()
13869               << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
13870           else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
13871             // Force the type of the expression to 'int'.
13872             Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
13873           }
13874           EltTy = Val->getType();
13875         }
13876       }
13877     }
13878   }
13879 
13880   if (!Val) {
13881     if (Enum->isDependentType())
13882       EltTy = Context.DependentTy;
13883     else if (!LastEnumConst) {
13884       // C++0x [dcl.enum]p5:
13885       //   If the underlying type is not fixed, the type of each enumerator
13886       //   is the type of its initializing value:
13887       //     - If no initializer is specified for the first enumerator, the
13888       //       initializing value has an unspecified integral type.
13889       //
13890       // GCC uses 'int' for its unspecified integral type, as does
13891       // C99 6.7.2.2p3.
13892       if (Enum->isFixed()) {
13893         EltTy = Enum->getIntegerType();
13894       }
13895       else {
13896         EltTy = Context.IntTy;
13897       }
13898     } else {
13899       // Assign the last value + 1.
13900       EnumVal = LastEnumConst->getInitVal();
13901       ++EnumVal;
13902       EltTy = LastEnumConst->getType();
13903 
13904       // Check for overflow on increment.
13905       if (EnumVal < LastEnumConst->getInitVal()) {
13906         // C++0x [dcl.enum]p5:
13907         //   If the underlying type is not fixed, the type of each enumerator
13908         //   is the type of its initializing value:
13909         //
13910         //     - Otherwise the type of the initializing value is the same as
13911         //       the type of the initializing value of the preceding enumerator
13912         //       unless the incremented value is not representable in that type,
13913         //       in which case the type is an unspecified integral type
13914         //       sufficient to contain the incremented value. If no such type
13915         //       exists, the program is ill-formed.
13916         QualType T = getNextLargerIntegralType(Context, EltTy);
13917         if (T.isNull() || Enum->isFixed()) {
13918           // There is no integral type larger enough to represent this
13919           // value. Complain, then allow the value to wrap around.
13920           EnumVal = LastEnumConst->getInitVal();
13921           EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
13922           ++EnumVal;
13923           if (Enum->isFixed())
13924             // When the underlying type is fixed, this is ill-formed.
13925             Diag(IdLoc, diag::err_enumerator_wrapped)
13926               << EnumVal.toString(10)
13927               << EltTy;
13928           else
13929             Diag(IdLoc, diag::ext_enumerator_increment_too_large)
13930               << EnumVal.toString(10);
13931         } else {
13932           EltTy = T;
13933         }
13934 
13935         // Retrieve the last enumerator's value, extent that type to the
13936         // type that is supposed to be large enough to represent the incremented
13937         // value, then increment.
13938         EnumVal = LastEnumConst->getInitVal();
13939         EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13940         EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
13941         ++EnumVal;
13942 
13943         // If we're not in C++, diagnose the overflow of enumerator values,
13944         // which in C99 means that the enumerator value is not representable in
13945         // an int (C99 6.7.2.2p2). However, we support GCC's extension that
13946         // permits enumerator values that are representable in some larger
13947         // integral type.
13948         if (!getLangOpts().CPlusPlus && !T.isNull())
13949           Diag(IdLoc, diag::warn_enum_value_overflow);
13950       } else if (!getLangOpts().CPlusPlus &&
13951                  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
13952         // Enforce C99 6.7.2.2p2 even when we compute the next value.
13953         Diag(IdLoc, diag::ext_enum_value_not_int)
13954           << EnumVal.toString(10) << 1;
13955       }
13956     }
13957   }
13958 
13959   if (!EltTy->isDependentType()) {
13960     // Make the enumerator value match the signedness and size of the
13961     // enumerator's type.
13962     EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
13963     EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
13964   }
13965 
13966   return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
13967                                   Val, EnumVal);
13968 }
13969 
13970 Sema::SkipBodyInfo Sema::shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II,
13971                                                 SourceLocation IILoc) {
13972   if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
13973       !getLangOpts().CPlusPlus)
13974     return SkipBodyInfo();
13975 
13976   // We have an anonymous enum definition. Look up the first enumerator to
13977   // determine if we should merge the definition with an existing one and
13978   // skip the body.
13979   NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
13980                                          ForRedeclaration);
13981   auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
13982   if (!PrevECD)
13983     return SkipBodyInfo();
13984 
13985   EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
13986   NamedDecl *Hidden;
13987   if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
13988     SkipBodyInfo Skip;
13989     Skip.Previous = Hidden;
13990     return Skip;
13991   }
13992 
13993   return SkipBodyInfo();
13994 }
13995 
13996 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
13997                               SourceLocation IdLoc, IdentifierInfo *Id,
13998                               AttributeList *Attr,
13999                               SourceLocation EqualLoc, Expr *Val) {
14000   EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
14001   EnumConstantDecl *LastEnumConst =
14002     cast_or_null<EnumConstantDecl>(lastEnumConst);
14003 
14004   // The scope passed in may not be a decl scope.  Zip up the scope tree until
14005   // we find one that is.
14006   S = getNonFieldDeclScope(S);
14007 
14008   // Verify that there isn't already something declared with this name in this
14009   // scope.
14010   NamedDecl *PrevDecl = LookupSingleName(S, Id, IdLoc, LookupOrdinaryName,
14011                                          ForRedeclaration);
14012   if (PrevDecl && PrevDecl->isTemplateParameter()) {
14013     // Maybe we will complain about the shadowed template parameter.
14014     DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
14015     // Just pretend that we didn't see the previous declaration.
14016     PrevDecl = nullptr;
14017   }
14018 
14019   // C++ [class.mem]p15:
14020   // If T is the name of a class, then each of the following shall have a name
14021   // different from T:
14022   // - every enumerator of every member of class T that is an unscoped
14023   // enumerated type
14024   if (!TheEnumDecl->isScoped())
14025     DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
14026                             DeclarationNameInfo(Id, IdLoc));
14027 
14028   EnumConstantDecl *New =
14029     CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
14030   if (!New)
14031     return nullptr;
14032 
14033   if (PrevDecl) {
14034     // When in C++, we may get a TagDecl with the same name; in this case the
14035     // enum constant will 'hide' the tag.
14036     assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
14037            "Received TagDecl when not in C++!");
14038     if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S) &&
14039         shouldLinkPossiblyHiddenDecl(PrevDecl, New)) {
14040       if (isa<EnumConstantDecl>(PrevDecl))
14041         Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
14042       else
14043         Diag(IdLoc, diag::err_redefinition) << Id;
14044       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
14045       return nullptr;
14046     }
14047   }
14048 
14049   // Process attributes.
14050   if (Attr) ProcessDeclAttributeList(S, New, Attr);
14051 
14052   // Register this decl in the current scope stack.
14053   New->setAccess(TheEnumDecl->getAccess());
14054   PushOnScopeChains(New, S);
14055 
14056   ActOnDocumentableDecl(New);
14057 
14058   return New;
14059 }
14060 
14061 // Returns true when the enum initial expression does not trigger the
14062 // duplicate enum warning.  A few common cases are exempted as follows:
14063 // Element2 = Element1
14064 // Element2 = Element1 + 1
14065 // Element2 = Element1 - 1
14066 // Where Element2 and Element1 are from the same enum.
14067 static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum) {
14068   Expr *InitExpr = ECD->getInitExpr();
14069   if (!InitExpr)
14070     return true;
14071   InitExpr = InitExpr->IgnoreImpCasts();
14072 
14073   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
14074     if (!BO->isAdditiveOp())
14075       return true;
14076     IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
14077     if (!IL)
14078       return true;
14079     if (IL->getValue() != 1)
14080       return true;
14081 
14082     InitExpr = BO->getLHS();
14083   }
14084 
14085   // This checks if the elements are from the same enum.
14086   DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
14087   if (!DRE)
14088     return true;
14089 
14090   EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
14091   if (!EnumConstant)
14092     return true;
14093 
14094   if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
14095       Enum)
14096     return true;
14097 
14098   return false;
14099 }
14100 
14101 namespace {
14102 struct DupKey {
14103   int64_t val;
14104   bool isTombstoneOrEmptyKey;
14105   DupKey(int64_t val, bool isTombstoneOrEmptyKey)
14106     : val(val), isTombstoneOrEmptyKey(isTombstoneOrEmptyKey) {}
14107 };
14108 
14109 static DupKey GetDupKey(const llvm::APSInt& Val) {
14110   return DupKey(Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue(),
14111                 false);
14112 }
14113 
14114 struct DenseMapInfoDupKey {
14115   static DupKey getEmptyKey() { return DupKey(0, true); }
14116   static DupKey getTombstoneKey() { return DupKey(1, true); }
14117   static unsigned getHashValue(const DupKey Key) {
14118     return (unsigned)(Key.val * 37);
14119   }
14120   static bool isEqual(const DupKey& LHS, const DupKey& RHS) {
14121     return LHS.isTombstoneOrEmptyKey == RHS.isTombstoneOrEmptyKey &&
14122            LHS.val == RHS.val;
14123   }
14124 };
14125 } // end anonymous namespace
14126 
14127 // Emits a warning when an element is implicitly set a value that
14128 // a previous element has already been set to.
14129 static void CheckForDuplicateEnumValues(Sema &S, ArrayRef<Decl *> Elements,
14130                                         EnumDecl *Enum,
14131                                         QualType EnumType) {
14132   if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
14133     return;
14134   // Avoid anonymous enums
14135   if (!Enum->getIdentifier())
14136     return;
14137 
14138   // Only check for small enums.
14139   if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
14140     return;
14141 
14142   typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
14143   typedef SmallVector<ECDVector *, 3> DuplicatesVector;
14144 
14145   typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
14146   typedef llvm::DenseMap<DupKey, DeclOrVector, DenseMapInfoDupKey>
14147           ValueToVectorMap;
14148 
14149   DuplicatesVector DupVector;
14150   ValueToVectorMap EnumMap;
14151 
14152   // Populate the EnumMap with all values represented by enum constants without
14153   // an initialier.
14154   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14155     EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Elements[i]);
14156 
14157     // Null EnumConstantDecl means a previous diagnostic has been emitted for
14158     // this constant.  Skip this enum since it may be ill-formed.
14159     if (!ECD) {
14160       return;
14161     }
14162 
14163     if (ECD->getInitExpr())
14164       continue;
14165 
14166     DupKey Key = GetDupKey(ECD->getInitVal());
14167     DeclOrVector &Entry = EnumMap[Key];
14168 
14169     // First time encountering this value.
14170     if (Entry.isNull())
14171       Entry = ECD;
14172   }
14173 
14174   // Create vectors for any values that has duplicates.
14175   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14176     EnumConstantDecl *ECD = cast<EnumConstantDecl>(Elements[i]);
14177     if (!ValidDuplicateEnum(ECD, Enum))
14178       continue;
14179 
14180     DupKey Key = GetDupKey(ECD->getInitVal());
14181 
14182     DeclOrVector& Entry = EnumMap[Key];
14183     if (Entry.isNull())
14184       continue;
14185 
14186     if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
14187       // Ensure constants are different.
14188       if (D == ECD)
14189         continue;
14190 
14191       // Create new vector and push values onto it.
14192       ECDVector *Vec = new ECDVector();
14193       Vec->push_back(D);
14194       Vec->push_back(ECD);
14195 
14196       // Update entry to point to the duplicates vector.
14197       Entry = Vec;
14198 
14199       // Store the vector somewhere we can consult later for quick emission of
14200       // diagnostics.
14201       DupVector.push_back(Vec);
14202       continue;
14203     }
14204 
14205     ECDVector *Vec = Entry.get<ECDVector*>();
14206     // Make sure constants are not added more than once.
14207     if (*Vec->begin() == ECD)
14208       continue;
14209 
14210     Vec->push_back(ECD);
14211   }
14212 
14213   // Emit diagnostics.
14214   for (DuplicatesVector::iterator DupVectorIter = DupVector.begin(),
14215                                   DupVectorEnd = DupVector.end();
14216        DupVectorIter != DupVectorEnd; ++DupVectorIter) {
14217     ECDVector *Vec = *DupVectorIter;
14218     assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
14219 
14220     // Emit warning for one enum constant.
14221     ECDVector::iterator I = Vec->begin();
14222     S.Diag((*I)->getLocation(), diag::warn_duplicate_enum_values)
14223       << (*I)->getName() << (*I)->getInitVal().toString(10)
14224       << (*I)->getSourceRange();
14225     ++I;
14226 
14227     // Emit one note for each of the remaining enum constants with
14228     // the same value.
14229     for (ECDVector::iterator E = Vec->end(); I != E; ++I)
14230       S.Diag((*I)->getLocation(), diag::note_duplicate_element)
14231         << (*I)->getName() << (*I)->getInitVal().toString(10)
14232         << (*I)->getSourceRange();
14233     delete Vec;
14234   }
14235 }
14236 
14237 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
14238                              bool AllowMask) const {
14239   assert(ED->hasAttr<FlagEnumAttr>() && "looking for value in non-flag enum");
14240   assert(ED->isCompleteDefinition() && "expected enum definition");
14241 
14242   auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
14243   llvm::APInt &FlagBits = R.first->second;
14244 
14245   if (R.second) {
14246     for (auto *E : ED->enumerators()) {
14247       const auto &EVal = E->getInitVal();
14248       // Only single-bit enumerators introduce new flag values.
14249       if (EVal.isPowerOf2())
14250         FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
14251     }
14252   }
14253 
14254   // A value is in a flag enum if either its bits are a subset of the enum's
14255   // flag bits (the first condition) or we are allowing masks and the same is
14256   // true of its complement (the second condition). When masks are allowed, we
14257   // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
14258   //
14259   // While it's true that any value could be used as a mask, the assumption is
14260   // that a mask will have all of the insignificant bits set. Anything else is
14261   // likely a logic error.
14262   llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
14263   return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
14264 }
14265 
14266 void Sema::ActOnEnumBody(SourceLocation EnumLoc, SourceLocation LBraceLoc,
14267                          SourceLocation RBraceLoc, Decl *EnumDeclX,
14268                          ArrayRef<Decl *> Elements,
14269                          Scope *S, AttributeList *Attr) {
14270   EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
14271   QualType EnumType = Context.getTypeDeclType(Enum);
14272 
14273   if (Attr)
14274     ProcessDeclAttributeList(S, Enum, Attr);
14275 
14276   if (Enum->isDependentType()) {
14277     for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14278       EnumConstantDecl *ECD =
14279         cast_or_null<EnumConstantDecl>(Elements[i]);
14280       if (!ECD) continue;
14281 
14282       ECD->setType(EnumType);
14283     }
14284 
14285     Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
14286     return;
14287   }
14288 
14289   // TODO: If the result value doesn't fit in an int, it must be a long or long
14290   // long value.  ISO C does not support this, but GCC does as an extension,
14291   // emit a warning.
14292   unsigned IntWidth = Context.getTargetInfo().getIntWidth();
14293   unsigned CharWidth = Context.getTargetInfo().getCharWidth();
14294   unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
14295 
14296   // Verify that all the values are okay, compute the size of the values, and
14297   // reverse the list.
14298   unsigned NumNegativeBits = 0;
14299   unsigned NumPositiveBits = 0;
14300 
14301   // Keep track of whether all elements have type int.
14302   bool AllElementsInt = true;
14303 
14304   for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
14305     EnumConstantDecl *ECD =
14306       cast_or_null<EnumConstantDecl>(Elements[i]);
14307     if (!ECD) continue;  // Already issued a diagnostic.
14308 
14309     const llvm::APSInt &InitVal = ECD->getInitVal();
14310 
14311     // Keep track of the size of positive and negative values.
14312     if (InitVal.isUnsigned() || InitVal.isNonNegative())
14313       NumPositiveBits = std::max(NumPositiveBits,
14314                                  (unsigned)InitVal.getActiveBits());
14315     else
14316       NumNegativeBits = std::max(NumNegativeBits,
14317                                  (unsigned)InitVal.getMinSignedBits());
14318 
14319     // Keep track of whether every enum element has type int (very commmon).
14320     if (AllElementsInt)
14321       AllElementsInt = ECD->getType() == Context.IntTy;
14322   }
14323 
14324   // Figure out the type that should be used for this enum.
14325   QualType BestType;
14326   unsigned BestWidth;
14327 
14328   // C++0x N3000 [conv.prom]p3:
14329   //   An rvalue of an unscoped enumeration type whose underlying
14330   //   type is not fixed can be converted to an rvalue of the first
14331   //   of the following types that can represent all the values of
14332   //   the enumeration: int, unsigned int, long int, unsigned long
14333   //   int, long long int, or unsigned long long int.
14334   // C99 6.4.4.3p2:
14335   //   An identifier declared as an enumeration constant has type int.
14336   // The C99 rule is modified by a gcc extension
14337   QualType BestPromotionType;
14338 
14339   bool Packed = Enum->hasAttr<PackedAttr>();
14340   // -fshort-enums is the equivalent to specifying the packed attribute on all
14341   // enum definitions.
14342   if (LangOpts.ShortEnums)
14343     Packed = true;
14344 
14345   if (Enum->isFixed()) {
14346     BestType = Enum->getIntegerType();
14347     if (BestType->isPromotableIntegerType())
14348       BestPromotionType = Context.getPromotedIntegerType(BestType);
14349     else
14350       BestPromotionType = BestType;
14351 
14352     BestWidth = Context.getIntWidth(BestType);
14353   }
14354   else if (NumNegativeBits) {
14355     // If there is a negative value, figure out the smallest integer type (of
14356     // int/long/longlong) that fits.
14357     // If it's packed, check also if it fits a char or a short.
14358     if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
14359       BestType = Context.SignedCharTy;
14360       BestWidth = CharWidth;
14361     } else if (Packed && NumNegativeBits <= ShortWidth &&
14362                NumPositiveBits < ShortWidth) {
14363       BestType = Context.ShortTy;
14364       BestWidth = ShortWidth;
14365     } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
14366       BestType = Context.IntTy;
14367       BestWidth = IntWidth;
14368     } else {
14369       BestWidth = Context.getTargetInfo().getLongWidth();
14370 
14371       if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
14372         BestType = Context.LongTy;
14373       } else {
14374         BestWidth = Context.getTargetInfo().getLongLongWidth();
14375 
14376         if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
14377           Diag(Enum->getLocation(), diag::ext_enum_too_large);
14378         BestType = Context.LongLongTy;
14379       }
14380     }
14381     BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
14382   } else {
14383     // If there is no negative value, figure out the smallest type that fits
14384     // all of the enumerator values.
14385     // If it's packed, check also if it fits a char or a short.
14386     if (Packed && NumPositiveBits <= CharWidth) {
14387       BestType = Context.UnsignedCharTy;
14388       BestPromotionType = Context.IntTy;
14389       BestWidth = CharWidth;
14390     } else if (Packed && NumPositiveBits <= ShortWidth) {
14391       BestType = Context.UnsignedShortTy;
14392       BestPromotionType = Context.IntTy;
14393       BestWidth = ShortWidth;
14394     } else if (NumPositiveBits <= IntWidth) {
14395       BestType = Context.UnsignedIntTy;
14396       BestWidth = IntWidth;
14397       BestPromotionType
14398         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14399                            ? Context.UnsignedIntTy : Context.IntTy;
14400     } else if (NumPositiveBits <=
14401                (BestWidth = Context.getTargetInfo().getLongWidth())) {
14402       BestType = Context.UnsignedLongTy;
14403       BestPromotionType
14404         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14405                            ? Context.UnsignedLongTy : Context.LongTy;
14406     } else {
14407       BestWidth = Context.getTargetInfo().getLongLongWidth();
14408       assert(NumPositiveBits <= BestWidth &&
14409              "How could an initializer get larger than ULL?");
14410       BestType = Context.UnsignedLongLongTy;
14411       BestPromotionType
14412         = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
14413                            ? Context.UnsignedLongLongTy : Context.LongLongTy;
14414     }
14415   }
14416 
14417   // Loop over all of the enumerator constants, changing their types to match
14418   // the type of the enum if needed.
14419   for (auto *D : Elements) {
14420     auto *ECD = cast_or_null<EnumConstantDecl>(D);
14421     if (!ECD) continue;  // Already issued a diagnostic.
14422 
14423     // Standard C says the enumerators have int type, but we allow, as an
14424     // extension, the enumerators to be larger than int size.  If each
14425     // enumerator value fits in an int, type it as an int, otherwise type it the
14426     // same as the enumerator decl itself.  This means that in "enum { X = 1U }"
14427     // that X has type 'int', not 'unsigned'.
14428 
14429     // Determine whether the value fits into an int.
14430     llvm::APSInt InitVal = ECD->getInitVal();
14431 
14432     // If it fits into an integer type, force it.  Otherwise force it to match
14433     // the enum decl type.
14434     QualType NewTy;
14435     unsigned NewWidth;
14436     bool NewSign;
14437     if (!getLangOpts().CPlusPlus &&
14438         !Enum->isFixed() &&
14439         isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
14440       NewTy = Context.IntTy;
14441       NewWidth = IntWidth;
14442       NewSign = true;
14443     } else if (ECD->getType() == BestType) {
14444       // Already the right type!
14445       if (getLangOpts().CPlusPlus)
14446         // C++ [dcl.enum]p4: Following the closing brace of an
14447         // enum-specifier, each enumerator has the type of its
14448         // enumeration.
14449         ECD->setType(EnumType);
14450       continue;
14451     } else {
14452       NewTy = BestType;
14453       NewWidth = BestWidth;
14454       NewSign = BestType->isSignedIntegerOrEnumerationType();
14455     }
14456 
14457     // Adjust the APSInt value.
14458     InitVal = InitVal.extOrTrunc(NewWidth);
14459     InitVal.setIsSigned(NewSign);
14460     ECD->setInitVal(InitVal);
14461 
14462     // Adjust the Expr initializer and type.
14463     if (ECD->getInitExpr() &&
14464         !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
14465       ECD->setInitExpr(ImplicitCastExpr::Create(Context, NewTy,
14466                                                 CK_IntegralCast,
14467                                                 ECD->getInitExpr(),
14468                                                 /*base paths*/ nullptr,
14469                                                 VK_RValue));
14470     if (getLangOpts().CPlusPlus)
14471       // C++ [dcl.enum]p4: Following the closing brace of an
14472       // enum-specifier, each enumerator has the type of its
14473       // enumeration.
14474       ECD->setType(EnumType);
14475     else
14476       ECD->setType(NewTy);
14477   }
14478 
14479   Enum->completeDefinition(BestType, BestPromotionType,
14480                            NumPositiveBits, NumNegativeBits);
14481 
14482   CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
14483 
14484   if (Enum->hasAttr<FlagEnumAttr>()) {
14485     for (Decl *D : Elements) {
14486       EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
14487       if (!ECD) continue;  // Already issued a diagnostic.
14488 
14489       llvm::APSInt InitVal = ECD->getInitVal();
14490       if (InitVal != 0 && !InitVal.isPowerOf2() &&
14491           !IsValueInFlagEnum(Enum, InitVal, true))
14492         Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
14493           << ECD << Enum;
14494     }
14495   }
14496 
14497   // Now that the enum type is defined, ensure it's not been underaligned.
14498   if (Enum->hasAttrs())
14499     CheckAlignasUnderalignment(Enum);
14500 }
14501 
14502 Decl *Sema::ActOnFileScopeAsmDecl(Expr *expr,
14503                                   SourceLocation StartLoc,
14504                                   SourceLocation EndLoc) {
14505   StringLiteral *AsmString = cast<StringLiteral>(expr);
14506 
14507   FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
14508                                                    AsmString, StartLoc,
14509                                                    EndLoc);
14510   CurContext->addDecl(New);
14511   return New;
14512 }
14513 
14514 static void checkModuleImportContext(Sema &S, Module *M,
14515                                      SourceLocation ImportLoc, DeclContext *DC,
14516                                      bool FromInclude = false) {
14517   SourceLocation ExternCLoc;
14518 
14519   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
14520     switch (LSD->getLanguage()) {
14521     case LinkageSpecDecl::lang_c:
14522       if (ExternCLoc.isInvalid())
14523         ExternCLoc = LSD->getLocStart();
14524       break;
14525     case LinkageSpecDecl::lang_cxx:
14526       break;
14527     }
14528     DC = LSD->getParent();
14529   }
14530 
14531   while (isa<LinkageSpecDecl>(DC))
14532     DC = DC->getParent();
14533 
14534   if (!isa<TranslationUnitDecl>(DC)) {
14535     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
14536                           ? diag::ext_module_import_not_at_top_level_noop
14537                           : diag::err_module_import_not_at_top_level_fatal)
14538         << M->getFullModuleName() << DC;
14539     S.Diag(cast<Decl>(DC)->getLocStart(),
14540            diag::note_module_import_not_at_top_level) << DC;
14541   } else if (!M->IsExternC && ExternCLoc.isValid()) {
14542     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
14543       << M->getFullModuleName();
14544     S.Diag(ExternCLoc, diag::note_module_import_in_extern_c);
14545   }
14546 }
14547 
14548 void Sema::diagnoseMisplacedModuleImport(Module *M, SourceLocation ImportLoc) {
14549   return checkModuleImportContext(*this, M, ImportLoc, CurContext);
14550 }
14551 
14552 DeclResult Sema::ActOnModuleImport(SourceLocation AtLoc,
14553                                    SourceLocation ImportLoc,
14554                                    ModuleIdPath Path) {
14555   Module *Mod =
14556       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
14557                                    /*IsIncludeDirective=*/false);
14558   if (!Mod)
14559     return true;
14560 
14561   VisibleModules.setVisible(Mod, ImportLoc);
14562 
14563   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
14564 
14565   // FIXME: we should support importing a submodule within a different submodule
14566   // of the same top-level module. Until we do, make it an error rather than
14567   // silently ignoring the import.
14568   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule)
14569     Diag(ImportLoc, diag::err_module_self_import)
14570         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
14571   else if (Mod->getTopLevelModuleName() == getLangOpts().ImplementationOfModule)
14572     Diag(ImportLoc, diag::err_module_import_in_implementation)
14573         << Mod->getFullModuleName() << getLangOpts().ImplementationOfModule;
14574 
14575   SmallVector<SourceLocation, 2> IdentifierLocs;
14576   Module *ModCheck = Mod;
14577   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
14578     // If we've run out of module parents, just drop the remaining identifiers.
14579     // We need the length to be consistent.
14580     if (!ModCheck)
14581       break;
14582     ModCheck = ModCheck->Parent;
14583 
14584     IdentifierLocs.push_back(Path[I].second);
14585   }
14586 
14587   ImportDecl *Import = ImportDecl::Create(Context,
14588                                           Context.getTranslationUnitDecl(),
14589                                           AtLoc.isValid()? AtLoc : ImportLoc,
14590                                           Mod, IdentifierLocs);
14591   Context.getTranslationUnitDecl()->addDecl(Import);
14592   return Import;
14593 }
14594 
14595 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
14596   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
14597 
14598   // Determine whether we're in the #include buffer for a module. The #includes
14599   // in that buffer do not qualify as module imports; they're just an
14600   // implementation detail of us building the module.
14601   //
14602   // FIXME: Should we even get ActOnModuleInclude calls for those?
14603   bool IsInModuleIncludes =
14604       TUKind == TU_Module &&
14605       getSourceManager().isWrittenInMainFile(DirectiveLoc);
14606 
14607   // If this module import was due to an inclusion directive, create an
14608   // implicit import declaration to capture it in the AST.
14609   if (!IsInModuleIncludes) {
14610     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
14611     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
14612                                                      DirectiveLoc, Mod,
14613                                                      DirectiveLoc);
14614     TU->addDecl(ImportD);
14615     Consumer.HandleImplicitImportDecl(ImportD);
14616   }
14617 
14618   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
14619   VisibleModules.setVisible(Mod, DirectiveLoc);
14620 }
14621 
14622 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
14623   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14624 
14625   if (getLangOpts().ModulesLocalVisibility)
14626     VisibleModulesStack.push_back(std::move(VisibleModules));
14627   VisibleModules.setVisible(Mod, DirectiveLoc);
14628 }
14629 
14630 void Sema::ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod) {
14631   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext);
14632 
14633   if (getLangOpts().ModulesLocalVisibility) {
14634     VisibleModules = std::move(VisibleModulesStack.back());
14635     VisibleModulesStack.pop_back();
14636     VisibleModules.setVisible(Mod, DirectiveLoc);
14637   }
14638 }
14639 
14640 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
14641                                                       Module *Mod) {
14642   // Bail if we're not allowed to implicitly import a module here.
14643   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery)
14644     return;
14645 
14646   // Create the implicit import declaration.
14647   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
14648   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
14649                                                    Loc, Mod, Loc);
14650   TU->addDecl(ImportD);
14651   Consumer.HandleImplicitImportDecl(ImportD);
14652 
14653   // Make the module visible.
14654   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
14655   VisibleModules.setVisible(Mod, Loc);
14656 }
14657 
14658 void Sema::ActOnPragmaRedefineExtname(IdentifierInfo* Name,
14659                                       IdentifierInfo* AliasName,
14660                                       SourceLocation PragmaLoc,
14661                                       SourceLocation NameLoc,
14662                                       SourceLocation AliasNameLoc) {
14663   NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
14664                                          LookupOrdinaryName);
14665   AsmLabelAttr *Attr =
14666       AsmLabelAttr::CreateImplicit(Context, AliasName->getName(), AliasNameLoc);
14667 
14668   // If a declaration that:
14669   // 1) declares a function or a variable
14670   // 2) has external linkage
14671   // already exists, add a label attribute to it.
14672   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
14673     if (isDeclExternC(PrevDecl))
14674       PrevDecl->addAttr(Attr);
14675     else
14676       Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
14677           << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
14678   // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
14679   } else
14680     (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
14681 }
14682 
14683 void Sema::ActOnPragmaWeakID(IdentifierInfo* Name,
14684                              SourceLocation PragmaLoc,
14685                              SourceLocation NameLoc) {
14686   Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
14687 
14688   if (PrevDecl) {
14689     PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc));
14690   } else {
14691     (void)WeakUndeclaredIdentifiers.insert(
14692       std::pair<IdentifierInfo*,WeakInfo>
14693         (Name, WeakInfo((IdentifierInfo*)nullptr, NameLoc)));
14694   }
14695 }
14696 
14697 void Sema::ActOnPragmaWeakAlias(IdentifierInfo* Name,
14698                                 IdentifierInfo* AliasName,
14699                                 SourceLocation PragmaLoc,
14700                                 SourceLocation NameLoc,
14701                                 SourceLocation AliasNameLoc) {
14702   Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
14703                                     LookupOrdinaryName);
14704   WeakInfo W = WeakInfo(Name, NameLoc);
14705 
14706   if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
14707     if (!PrevDecl->hasAttr<AliasAttr>())
14708       if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
14709         DeclApplyPragmaWeak(TUScope, ND, W);
14710   } else {
14711     (void)WeakUndeclaredIdentifiers.insert(
14712       std::pair<IdentifierInfo*,WeakInfo>(AliasName, W));
14713   }
14714 }
14715 
14716 Decl *Sema::getObjCDeclContext() const {
14717   return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
14718 }
14719 
14720 AvailabilityResult Sema::getCurContextAvailability() const {
14721   const Decl *D = cast_or_null<Decl>(getCurObjCLexicalContext());
14722   if (!D)
14723     return AR_Available;
14724 
14725   // If we are within an Objective-C method, we should consult
14726   // both the availability of the method as well as the
14727   // enclosing class.  If the class is (say) deprecated,
14728   // the entire method is considered deprecated from the
14729   // purpose of checking if the current context is deprecated.
14730   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
14731     AvailabilityResult R = MD->getAvailability();
14732     if (R != AR_Available)
14733       return R;
14734     D = MD->getClassInterface();
14735   }
14736   // If we are within an Objective-c @implementation, it
14737   // gets the same availability context as the @interface.
14738   else if (const ObjCImplementationDecl *ID =
14739             dyn_cast<ObjCImplementationDecl>(D)) {
14740     D = ID->getClassInterface();
14741   }
14742   // Recover from user error.
14743   return D ? D->getAvailability() : AR_Available;
14744 }
14745